기본 콘텐츠로 건너뛰기

Logistic Regression


By Andrew Ng

1. Logistic Regression 
    1.1 Visualizing Data Part
            └ plotData function
    1.2 Advanced Optimization Part
            └ mapFeature function
            └ costFunctionReg function
            └ fminunc function    
    1.3 Decision Boundary and Prediction Part
            └ plotDecisionBoundary function
            └ predict function




1. Logistic Regression

We'll implement regularized logistic regression to predict whether microchips from a fabrication plant passes quality assurance (QA). During QA, each microchip goes through various tests to ensure it is functioning correctly. Suppose you're the product manager of factory and you have the test results for some microchips on two different tests. From these two tests, you would like to determine whether the microchips should be accepted or rejected. To help you make the decision, you have a dataset of test results on past microchips, from which you can build a logistic regression model.


1.1 Visualizing Data Part

plotData(X, y);
Plot of training data
ex2data2.txt
1.1.1 plotData function
This function plots the data points X and y into a new figure. In other words, it plots the data points with + for the positive examples and o for the negative examples. X is assumed to be a M x 2 matrix.



1.2 Advanced Optimization Part
First, you're given a dataset with data points that are not linearly separable. However, you would still like to use logistic regression to classify the data points. To do so, you introduce more features to use. In particular, you add polynomial features to our data matrix (similar to polynomial regression).
Second, to get optimized theta, we'll use an advanced optimization function called fminunc(i.e., function minimization unconstrained), rather than naive gradient descent algorithm. It has a clever inner-loop called a line search algorithm that automatically tries out different values for learning rate alpha and automatically picks a good learning rate alpha.

1.2.1 mapFeature function
One way to fit the data better is to create more features from each data point. In this function, we'll map the features into all polynomial terms of $x_1$ and $x_2$ up to the sixth power.
As a result of this mapping, out vector of two features (the scores on two QA tests) has been transformed into a 28-dimensional vector. A logistic regression classifier trained on this higher-dimension feature vector will have a more complex decision boundary and will appear nonlinear when drawn in our 2-dimensional plot. While the feature mapping allows us to build a more expressive classifier, it also more susceptible to overfitting. So, we need to implement regularized logistic regression to fit the data.

1.2.2 costFunctionReg function
We'll implement code to compute the cost function and gradient for regularized logistic regression. Before starting with the actual cost function, recall that the logistic regression hypothesis is defined as: $$h_\theta(x) = g(\theta^Tx) ,$$ where function $g$ is the sigmoid function which defined as: $$g(z) = {1\over{1+e^{-z}}}$$ Recall that the regularized cost function in logistic regression is:
Notice that we should not regularize the parameter $theta_0$. The gradient of the cost function is a vector where the $j^{th}$ element is defined as follows:



1.3 Decision Boundary and Prediction
After learning the parameters $theta$, now we plot the non-linear decision boundary by computing the classifier's predictions on an evenly spaced grid and then draw a contour plot of where the predictions change from y=0 to y=1.

plotDecisionBoundary(theta, X, y);
Training data with decision boundary ($\lambda=1$)
No regularization (Overfitting) ($\lambda=0$)
Too much regularization (Underfitting) ($\lambda=100$)

1.3.1 plotDecisionBoundary function
This function plots the data points X and y into a new figure with the decision boundary defined by theta.

1.3.2 predict function
To predict whether the label is 0 or 1 using learned logistic regression parameters theta



REFERENCES
[1] Machine Learning, Stanford University, Andrew Ng, Coursera

댓글

이 블로그의 인기 게시물

Pattern Discovery in Data Mining

Coursera Illinois at Urbana-Champaign by Jiawei Han 2015.03.19 CONTENT 1. A brief Introduction to Data Mining 2. Pattern Discovery : Basic Concepts 3. Efficient Pattern Mining Methods 4. Pattern Evaluation 5. Mining Diverse Patterns 6. Constraint-Based Pattern Mining 7. Sequential Pattern Mining 8. Graph Pattern Mining 9. Pattern-Based Classification 10. Exploring Pattern Mining Applications Lecture 1 : A brief Introduction to Data Mining - We'are drowning in data but starving for knowledge ( a lot of data are unstructured ) - Data mining : a misnomer ! -> Knowledge mining from data - Extraction of interesting patterns (non-trivial, implicit, previously unknown and potentially useful) or knowledge from massive data. - Data mining is a interdisciplinary field (machine learning, pattern recognition, statistics, databases, big data, business intelligence..) Knowledge Discovery (KDD) Process Methodology View: Confluence of Multiple Disciplines Lecture 2 : Pattern Discovery : Ba...

Introduction to Data Structure Using C

윤성우의 열혈 자료구조 자료구조에 대한 기본적 이해 프로그램 = 자료구조(데이터 표현) + 알고리즘(데이터 처리) 자료구조가 결정되어야 그에 따른 효율적인 알고리즘 설계 가능하다. 알고리즘은 자료구조에 의존적이다. 알고리즘의 성능분석 방법 시간 복잡도(Time Complexity) - 속도      연산의 횟수를 통해 알고리즘의 빠르기 판단           데이터 수의 증가에 따른 연산횟수의 변화 정도 판단           탐색 알고리즘에서 시간 복잡도를 결정하는 핵심 연산자는 동등비교(==)이다. 공간 복잡도(Space Complexity) - 메모리 사용량 일반적으로 알고리즘 성능 평가할 때 메모리 사용량보다 실행속도에 초점을 둔다. 일반적인 알고리즘의 평가에는 논란의 소지가 거의 없는 '최악의 경우(worst case)가 선택된다. Big-Oh Notation은 '데이터 수의 증가에 따른 연산횟수의 증가패턴을 나타내는 표기법이다.' 또는 '데이터 수의 증가에 따른 연산횟수 증가율의 상한선을 표현한 것'이다. Recursive 하노이 타워      가장 작은 단위 패턴을 코딩하고 이를 일반화시키면 된다. 리스트 (List)      순차 리스트 (배열 기반)           배열 자료구조 특징인 Index를 통해서 어느 곳이든 바로 이동이 가능하다.           하지만, 프로그램 실행 전에 크기가 결정되어야 한다.           그리고 배열은 메모리의 특성이 정적이므로 메모리 길이 변경이 불가능하다.           정적인 배열은 필요로 하는 메모리의 크기에 유연하게 대처하지 못한다. ...