线性回归模型公式推导完整简洁版
这里做模型简化,假设有4个样本,每个样本有3个特征,然后使用平方误差作为损失函数,公式推导反向传播的求导过程。
设训练样本为
\[X = \left[ \begin{matrix} x_{1}^{(1)} & x_{2}^{(1)} & x_{3}^{(1)}\\ x_{1}^{(2)} & x_{2}^{(2)} & x_{3}^{(2)}\\ x_{1}^{(3)} & x_{2}^{(3)} & x_{3}^{(3)}\\ x_{1}^{(4)} & x_{2}^{(4)} & x_{3}^{(4)}\\ \end{matrix} \right] \]其中,有4个样本,每个样本三个特征值分别为\([x_1,x_2, x_3]\)。
设标签数据为
\[\hat{y} = \left[ \begin{matrix} y^{(1)} \\ y^{(2)} \\ y^{(3)} \\ y^{(4)} \\ \end{matrix} \right] \]设需要学习的参数为\(w\)(3维度向量)和\(b\)(标量)
\[w = \left[ \begin{matrix} w_{1} \\ w_{2} \\ w_{3} \\ \end{matrix} \right] \]则损失函数为
\[Loss(w,b) =\frac{1}{2n} || Xw + b - \hat{y} ||^{2} \]则将损失函数化为具体矩阵
\[Loss(w,b) = \frac{1}{2n} ( \left[ \begin{matrix} x_{1}^{(1)} & x_{2}^{(1)} & x_{3}^{(1)}\\ x_{1}^{(2)} & x_{2}^{(2)} & x_{3}^{(2)}\\ x_{1}^{(3)} & x_{2}^{(3)} & x_{3}^{(3)}\\ x_{1}^{(4)} & x_{2}^{(4)} & x_{3}^{(4)}\\ \end{matrix} \right] \left[ \begin{matrix} w_{1} \\ w_{2} \\ w_{3} \\ \end{matrix} \right] + b - \left[ \begin{matrix} y^{(1)} \\ y^{(2)} \\ y^{(3)} \\ y^{(4)} \\ \end{matrix} \right] )^{向量内积} \]将\(b\)放入矩阵,简化公式
\[Loss(w,b) = \frac{1}{2n} ( \left[ \begin{matrix} x_{1}^{(1)} & x_{2}^{(1)} & x_{3}^{(1)} & 1\\ x_{1}^{(2)} & x_{2}^{(2)} & x_{3}^{(2)} & 1\\ x_{1}^{(3)} & x_{2}^{(3)} & x_{3}^{(3)} & 1\\ x_{1}^{(4)} & x_{2}^{(4)} & x_{3}^{(4)} & 1\\ \end{matrix} \right] \left[ \begin{matrix} w_{1} \\ w_{2} \\ w_{3} \\ b \end{matrix} \right] - \left[ \begin{matrix} y^{(1)} \\ y^{(2)} \\ y^{(3)} \\ y^{(4)} \\ \end{matrix} \right] )^{向量内积} \]则令
\[X = \left[ \begin{matrix} x_{1}^{(1)} & x_{2}^{(1)} & x_{3}^{(1)} & 1\\ x_{1}^{(2)} & x_{2}^{(2)} & x_{3}^{(2)} & 1\\ x_{1}^{(3)} & x_{2}^{(3)} & x_{3}^{(3)} & 1\\ x_{1}^{(4)} & x_{2}^{(4)} & x_{3}^{(4)} & 1\\ \end{matrix} \right] \space \space \space \space \space w = \left[ \begin{matrix} w_{1} \\ w_{2} \\ w_{3} \\ b \end{matrix} \right] \]则公式化简为
\[Loss(w) =\frac{1}{2n} (Xw - \hat{y})^{向量内积} =\frac{1}{2n} (Xw - \hat{y})^{T}(Xw - \hat{y}) \]则\(Loss(w)\)对\(w\)求导
\[\frac{\partial Loss(w)}{\partial w} = \frac{1}{2n} \space \frac{\partial }{\partial w}(Xw - \hat{y})^{T}(Xw - \hat{y}) \tag{1} \]根据标量对向量求导公式
\[\frac{\partial \mathrm{y}}{\partial x} = \frac{\partial x^{T}x}{x}=2x^{T} \]因此,公式(1)根据链式求导规则化简为
\[\frac{\partial Loss(w)}{\partial w} = \frac{1}{n} \space (Xw - \hat{y})^{T} \space \frac{\partial (Xw-\hat{y})}{\partial {w}} \\ =\frac{1}{n} (Xw-\hat{y})^{T} X \]主要还是捋清楚标量对向量求导后的维数,参照这个图