Lecture 2 : linear regression

线性模型是监督学习中的一种最简单的模型。

在监督学习中,我们将数据集喂给学习算法,学习算法输出一个函数 (hypothesis), 然后我们用这个 hypothesis 来进行预测和决策。

因此首先需要考虑如何表示这个 hypothesis 。线性模型中我们使用线性函数 i.e. \(h(x) = \theta_0 + \theta_1x\)

约定一些记号:

#: number of ...

\(\theta\) : parameters

\(m:\) #training examples

\(x\) : input features

\(y\) : ouput/target variable

\((x,y)\): training example

\((x^{(i)},y^{(i)})\): \(i^{th}\) training example

\(n\): #features

接下来要考虑的是如何调整参数 \(\theta\) 使得得到的 hypothesis 有较好的预测效果,要达到这个目标,这个 hypothesis 首先在训练集上要有好的效果,即找 \(h(x)\) ≈ y。

定义 cost function \(J(\theta) = \frac{1}{2}\sum_{i=1}^m (h(x^{(i)}) - y^{(i)})^2\), 即残差平方和。

优化目标即为最小化 \(J(\theta)\), 对应的参数即为合适的 \(\theta\)

优化方法采用梯度下降算法:

  1. 随机初始化参数 \(\theta\)

  2. 不断改变参数来使得 cost function 变小(每次朝着梯度的方向下降一小步)

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

    do this for j = 1, 2, 3, 4, 5......, n simultaneaously

梯度下降算法的一个性质是可能会陷入局部最优解(local optima) 而非全局最优解 (global optima), 因为局部最优处梯度也是 0,但是线性模型的 cost function 由于其性质 local optima 即为 global optima

对于线性模型, \(\frac{\partial J(\theta)}{\partial \theta_j} = \sum_{i=1}^m (h(x^{(i)}) - y^{(i)})x^{(i)}_j\)

上面这种梯度下降算法叫做 Batch Gradient Descent, 在实际应用中对于比较大的数据集,由于梯度下降的每个 step 需要遍历整个数据集,而遍历一整个数据集的代价是巨大的,此时 Batch Gradient Descent 效率不高,下面使用的一种梯度下降的变种 Schochastic Gradient Descent 每次只看一个 training example,好处是每个 step 都很快,但是最后没办法收敛,只能得到某个接近 optima 的对应的参数。实际应用时这样得到的参数往往也能有较好的效果。

除了梯度下降这种 iterative 算法,对于线性模型,有一种方法得到闭式解,通过几次矩阵乘法和求逆就可以得到对应的参数。

考虑 \(J(\theta)\) 的向量化形式 :\(J(\theta) = \frac{1}{2} (X\theta - y)^T(X\theta - y)\)

其中

\[X = \begin{bmatrix} ——————(x^{(1)})^T———————\\ ——————(x^{(2)})^T———————\\ ...\\ ——————(x^{(m)})^T——————— \end{bmatrix} \\ \theta = \begin{bmatrix} \theta_0\\ \theta_1\\ \theta_2\\ ...\\ \theta_n \end{bmatrix} \\ y = \begin{bmatrix} y^{(1)}\\ y^{(2)}\\ ...\\ y^{(m)} \end{bmatrix} \]

通过解方程:

\[\nabla_{\theta} J(\theta) = 0 \]

具体过程参考 CS229 NOTES 1,用到了一些矩阵求导法则。

解得闭式解:

\[\theta = (X^TX)^{-1}X^Ty \]

posted @ 2022-03-19 21:46  今天AC了吗  阅读(49)  评论(0)    收藏  举报