2018.01.01

Week 1

What is Machine Learning?

Two definitions of Machine Learning are offered. Arthur Samuel described it as: «the field of study that gives computers the ability to learn without being explicitly programmed.» This is an older, informal definition.

Tom Mitchell provides a more modern definition: «A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E.»

Example: playing checkers.

E = the experience of playing many games of checkers(玩很多棋子的经验)

T = the task of playing checkers.（玩跳棋的任务）

P = the probability that the program will win the next game.（程序赢得比赛的概率）

In general, any machine learning problem can be assigned to one of two broad classifications:（两个分类）

Supervised learning (监督学习)and Unsupervised(非监督学习) learning.

Useful variables

m = Number of training examples（训练样本数量）
x’s = «input» variable / feature （输入变量）
y’s = «ouput» variable / «target» variable （输出变量）
h = hypothesis (假设，表示一个函数，拟合输入与输出对应的关系)
hθ(x)=θ0+θ1*x

Cost function（代价函数,或平方误差函数）

$$\theta_0+\theta_1x_1+\theta_2x_2+\cdots+\theta_nx_n = h_\theta(x^{(i)})$$

$$\theta^TX = h_\theta(x^{(i)})$$

$X=\begin{bmatrix}x_0\\x_1\\x_2\\\cdots\\x_n\end{bmatrix}\theta=\begin{bmatrix}\theta_0\\ \theta_1\\ \theta_2\\ \cdots\\ \theta_n\end{bmatrix}$

$X=\begin{bmatrix} 1 & x^{(1)}_1 & x^{(1)}_2 & \cdots & x^{(1)}_n \\ 1 & x^{(2)}_1 & x^{(2)}_2 & \cdots & x^{(2)}_n \\ \vdots & \vdots & \vdots & x_j^{(i)} & \vdots \\ 1 & x^{(m)}_1 & x^{(m)}_2 & \cdots & x^{(m)}_n \\ \end{bmatrix}_{m\times (n+1)} =\begin{bmatrix} x^{(1)}\\x^{(2)}\\\vdots\\x^{(m)} \end{bmatrix}_{m\times1} =\begin{bmatrix} x_0&x_1&x_2&\cdots&x_n \end{bmatrix}_{1\times (n+1)}$

$$X\theta =\begin{bmatrix}h_\theta(x^{(1)})\\ h_\theta(x^{(2)})\\\cdots\\h_\theta(x^{(m)})\\\end{bmatrix}= h_\theta(X)$$

$$J(\theta)=\frac{1}{2m}\sum_{i=1}^m{(h_\theta(x^{(i)})-y^{(i)})^2}$$

$$E=\begin{bmatrix}h_\theta(x^{(1)})-y^{(1)}\\ h_\theta(x^{(2)})-y^{(2)} \\\cdots\\h_\theta(x^{(m)})-y^{(m)} \\\end{bmatrix}$$

E 为可以理解为误差向量，就是每个预测结果 hθ(x(i))hθ(x(i))和对应的 y(i)y(i)之间的误差组成的列向量。注意到假设的矩阵表示形式（1.1 最后一个公式），则有：
$$E=X\theta-y$$

$$J(\theta)=\frac{1}{2m}E^T E=\frac{1}{2m}(X\theta-y)^T(X\theta-y)$$

θ0 和 θ1 called parameters of the model（模型参数）

We can measure the accuracy of our hypothesis function by using a cost function. This takes an average difference (actually a fancier version of an average) of all the results of the hypothesis with inputs from x’s and the actual output y’s.

To break it apart, it is 12 x¯ where x¯ is the mean of the squares of hθ(xi)−yi , or the difference between the predicted value and the actual value.

This function is otherwise called the «Squared error function», or «Mean squared error». The mean is halved (12) as a convenience for the computation of the gradient descent, as the derivative term of the square function will cancel out the 12 term. The following image summarizes what the cost function does:

Hθ(x)假设函数，J(θ1)代价函数

If we try to think of it in visual terms, our training data set is scattered on the x-y plane. We are trying to make a straight line (defined by hθ(x)) which passes through these scattered data points.

Our objective is to get the best possible line. The best possible line will be such so that the average squared vertical distances of the scattered points from the line will be the least. Ideally, the line should pass through all the points of our training data set. In such a case, the value of J(θ0,θ1) will be 0. The following example shows the ideal situation where we have a cost function of 0.

When θ1=1, we get a slope of 1 which goes through every single data point in our model. Conversely, when θ1=0.5, we see the vertical distance from our fit to the data points increase.

This increases our cost function to 0.58. Plotting several other points yields to the following graph:

Thus as a goal, we should try to minimize the cost function. In this case, θ1=1 is our global minimum.

contour plots / contour figures（轮廓图）

A contour plot is a graph that contains many contour lines. A contour line of a two variable function has a constant value at all points of the same line. An example of such a graph is the one to the right below.

Taking any color and going along the ‘circle’, one would expect to get the same value of the cost function. For example, the three green points found on the green line above have the same value for J(θ0,θ1) and as a result, they are found along the same line. The circled x displays the value of the cost function for the graph on the left when θ0 = 800 and θ1= -0.15. Taking another h(x) and plotting its contour plot, one gets the following graphs:

When θ0 = 360 and θ1 = 0, the value of J(θ0,θ1) in the contour plot gets closer to the center thus reducing the cost function error. Now giving our hypothesis function a slightly positive slope results in a better fit of the data.

The graph above minimizes the cost function as much as possible and consequently, the result of θ1 and θ0 tend to be around 0.12 and 250 respectively. Plotting those values on our graph to the right seems to put our point in the center of the inner most ‘circle’.

$$\nabla = \langle\frac{\partial }{\partial x},\frac{\partial }{\partial y},\frac{\partial }{\partial z}\rangle$$

$$\nabla f= \langle\frac{\partial f}{\partial x},\frac{\partial f}{\partial y},\frac{\partial f}{\partial z}\rangle$$

$$\theta_j\ := \theta_j - \alpha\frac{\partial}{\partial\theta_j}J(\theta)$$

$$\frac{\partial }{\partial\theta_j}J(\theta)=\frac{1}{m}\sum_{i=1}^m{(h_\theta^{x(i)}-y^{(i)})x_j^{(i)}}$$

$$\frac{\partial }{\partial\theta}J(\theta)=\frac{1}{m}X^T E$$

$$\theta\ := \theta - \alpha\frac{1}{m}X^T E$$

local optimum (局部最优解)

So we have our hypothesis function and we have a way of measuring how well it fits into the data. Now we need to estimate the parameters in the hypothesis function. That’s where gradient descent comes in.

Imagine that we graph our hypothesis function based on its fields θ0 and θ1 (actually we are graphing the cost function as a function of the parameter estimates). We are not graphing x and y itself, but the parameter range of our hypothesis function and the cost resulting from selecting a particular set of parameters.

We put θ0 on the x axis and θ1 on the y axis, with the cost function on the vertical z axis. The points on our graph will be the result of the cost function using our hypothesis with those specific theta parameters. The graph below depicts such a setup.

We will know that we have succeeded when our cost function is at the very bottom of the pits in our graph, i.e. when its value is the minimum. The red arrows show the minimum points in the graph.

The way we do this is by taking the derivative (the tangential line to a function) of our cost function. The slope of the tangent is the derivative at that point and it will give us a direction to move towards. We make steps down the cost function in the direction with the steepest descent. The size of each step is determined by the parameter α, which is called the learning rate.

For example, the distance between each ‘star’ in the graph above represents a step determined by our parameter α. A smaller α would result in a smaller step and a larger α results in a larger step. The direction in which the step is taken is determined by the partial derivative of J(θ0,θ1). Depending on where one starts on the graph, one could end up at different points. The image above shows us two different starting points that end up in two different places.

repeat until convergence:

θj:=θj−α∂∂θjJ(θ0,θ1)
where

j=0,1 represents the feature index number.

At each iteration j, one should simultaneously update the parameters θ1,θ2,…,θn. Updating a specific parameter prior to calculating another one on the j(th) iteration would yield to a wrong implementation.

alpha is called Learning Rate(学习速率)，控制逐次下降的幅度

In this video we explored the scenario where we used one parameter θ1 and plotted its cost function to implement a gradient descent. Our formula for a single parameter was :

Repeat until convergence:

Regardless of the slope’s sign for ddθ1J(θ1), θ1 eventually converges to its minimum value. The following graph shows that when the slope is negative, the value of θ1 increases and when it is positive, the value of θ1 decreases.

On a side note, we should adjust our parameter α to ensure that the gradient descent algorithm converges in a reasonable time. Failure to converge or too much time to obtain the minimum value imply that our step size is wrong.

On a side note, we should adjust our parameter α to ensure that the gradient descent algorithm converges in a reasonable time. Failure to converge or too much time to obtain the minimum value imply that our step size is wrong.

θ1:=θ1−α∗0

When specifically applied to the case of linear regression, a new form of the gradient descent equation can be derived. We can substitute our actual cost function and our actual hypothesis function and modify the equation to :

where m is the size of the training set, θ0 a constant that will be changing simultaneously with θ1 and xi,yiare values of the given training set (data).

Note that we have separated out the two cases for θj into separate equations for θ0 and θ1; and that for θ1 we are multiplying xi at the end due to the derivative. The following is a derivation of ∂∂θjJ(θ) for a single example :

$$∇_𝜃𝐽(θ)= 𝑋^𝑇𝑋𝜃 − 𝑋^𝑇𝑌$$

The point of all this is that if we start with a guess for our hypothesis and then repeatedly apply these gradient descent equations, our hypothesis will become more and more accurate.

So, this is simply gradient descent on the original cost function J. This method looks at every example in the entire training set on every step, and is called batch gradient descent. Note that, while gradient descent can be susceptible to local minima in general, the optimization problem we have posed here for linear regression has only one global, and no other local, optima; thus gradient descent always converges (assuming the learning rate α is not too large) to the global minimum. Indeed, J is a convex quadratic function. Here is an example of gradient descent as it is run to minimize a quadratic function.

The ellipses shown above are the contours of a quadratic function. Also shown is the trajectory taken by gradient descent, which was initialized at (48,30). The x’s in the figure (joined by straight lines) mark the successive values of θ that gradient descent went through as it converged to its minimum.

Linear algebra review(线代复习)

matrix 矩阵
dimension of matrix 纬度
2 by 3 matrix == 2 X 3 矩阵

Week 2

Multiple Variables

hθ(x)==θ^T x

Feature Scaling(特征缩放)

-3 $\leq x_i \leq$ 3 基本上可以
$-\frac{1}{3} \leq x_i \leq \frac{1}{3}$ 也是可以接受的范围

Learning Rate

If α is too small: slow convergence.

If α is too large: may not decrease on every iteration and thus may not converge.

Features and Polynomial Regression(多项式回归)

$h_\theta(x) = \theta_0 + \theta_1(\text{size}) + \theta2\sqrt{(\text{size})}$
size 范围为 1-1000 拟合模型
$h \theta(x) = \theta_0 + \theta_1x_1 + \theta_2x_2$

$x_1 = \frac{\text{size}}{1000},\ x_2 = \frac{\sqrt{(\text{size})}}{32}$

如果这样处理，同时缩放特征值范围很重要

Normal Equation 正规方程

$$X^T X\theta=X^T y$$ $$\theta = (X^T X)^{-1}X^T y$$

O (kn2)O (n3), 需要计算$X^TX$的逆

n$\leq$10000 说明 n 相对较小，可以使用正规方程

Week 3

Classification 逻辑回归

hypothesis representation 假设函数表达式

Our new form uses the «Sigmoid Function,» also called the «Logistic Function»:

\begin{align*}& h_\theta (x) = g ( \theta^T x ) \newline \newline& z = \theta^T x \newline& g(z) = \dfrac{1}{1 + e^{-z}}\end{align*}

$g (z )$函数看起来是

\begin{align*}& h_\theta(x) = P(y=1 | x ; \theta) = 1 - P(y=0 | x ; \theta) \newline& P(y = 0 | x;\theta) + P(y = 1 | x ; \theta) = 1\end{align*}

$hθ(x)$将给出我们的输出为 1 的概率。例如，$hθ(x)$= 0.7 给出了我们的输出为 1 的 70％的概率。我们的预测为 0 的概率只是我们的 概率为 1（例如，如果为 1 的概率为 70％，则为 0 的概率为 30％）。

###Decision Boundary 决策边界

\begin{align*}& h_\theta(x) \geq 0.5 \rightarrow y = 1 \newline& h_\theta(x) < 0.5 \rightarrow y = 0 \newline\end{align*}

\begin{align}& g(z) \geq 0.5 \newline& when \; z \geq 0\end{align}

Tips：

\begin{align*}z=0, e^{0}=1 \Rightarrow g(z)=1/2\newline z \to \infty, e^{-\infty} \to 0 \Rightarrow g(z)=1 \newline z \to -\infty, e^{\infty}\to \infty \Rightarrow g(z)=0 \end{align*}

\begin{align*}& h_\theta(x) = g(\theta^T x) \geq 0.5 \newline& when \; \theta^T x \geq 0\end{align*}

\begin{align*}& \theta^T x \geq 0 \Rightarrow y = 1 \newline& \theta^T x < 0 \Rightarrow y = 0 \newline\end{align*}

Example:

\begin{align*}& \theta = \begin{bmatrix}5 \newline -1 \newline 0\end{bmatrix} \newline & y = 1 \; if \; 5 + (-1) x_1 + 0 x_2 \geq 0 \newline & 5 - x_1 \geq 0 \newline & - x_1 \geq -5 \newline& x_1 \leq 5 \newline \end{align*}

Cost Function

\begin{align*}& J(\theta) = \dfrac{1}{m} \sum_{i=1}^m \mathrm{Cost}(h_\theta(x^{(i)}),y^{(i)}) \newline & \mathrm{Cost}(h_\theta(x),y) = -\log(h_\theta(x)) \; & \text{if y = 1} \newline & \mathrm{Cost}(h_\theta(x),y) = -\log(1-h_\theta(x)) \; & \text{if y = 0}\end{align*}

\begin{align*}& \mathrm{Cost}(h_\theta(x),y) = 0 \text{ if } h_\theta(x) = y \newline & \mathrm{Cost}(h_\theta(x),y) \rightarrow \infty \text{ if } y = 0 \; \mathrm{and} \; h_\theta(x) \rightarrow 1 \newline & \mathrm{Cost}(h_\theta(x),y) \rightarrow \infty \text{ if } y = 1 \; \mathrm{and} \; h_\theta(x) \rightarrow 0 \newline \end{align*}

$$\mathrm{Cost}(h_\theta(x),y) = - y \; \log(h_\theta(x)) - (1 - y) \log(1 - h_\theta(x))$$

$$J(\theta) = - \frac{1}{m} \displaystyle \sum_{i=1}^m [y^{(i)}\log (h_\theta (x^{(i)})) + (1 - y^{(i)})\log (1 - h_\theta(x^{(i)}))]$$