线性回归初步理解 章节 1线性回归算法简单线性回归线性回归是一种经典的有监督学习算法用于研究因变量目标变量和一个或多个自变量影响因素之间的线性关系。简单线性回归关注单一自变量对目标变量的影响而多元线性回归则处理多个自变量的情况。目标变量y是需要预测的值可以是连续值自变量X是影响目标变量的因素可以是连续值或离散值。简单线性回归模型公式为 y a bx其中a是截距b是斜率。看一个美国人发火箭的例子Actual value真实值即已知的 yPredicted value预测值是把已知的 x 带入到公式里面和猜出来的参数 a,b 计算得到的Error误差预测值和真实值的差距最优解尽可能的找到一个模型使得整体的误差最小整体的误差通常叫做损失 LossLoss整体的误差loss 通过损失函数 loss function 计算得到最优解是通过最小化整体误差损失来找到最佳模型。真实值Actual value、预测值Predicted value和误差Error的关系用于评估模型效果。多元线性回归现实生活中往往有多个因素影响结果y。这时自变量的数量从X1变为Xn简单线性回归的公式不再适用。多元线性回归公式为 y XW ε其中W是特征的权值向量ε是误差向量。举例训练一个模型预测一个人有多漂亮历史数据包含人的一些指标和已知得分。在多元线性回归中W 是一维向量代表的是 W0 到 Wn我们也可以用线性代数的方式去 表达公式这时算法要求解的就是这个向量如果维度很多我们当然需要计算机帮助我们来求解了。章节2 从代码理解线性回归通过anaconda环境打开jupyter notebook正规方程处理线性回归# 支持python2和3from __future__ import division, print_function, unicode_literals# 导入必要的库import numpy as npimport os# 设置随机数种子让每一次用相同的数据进行训练时输出的结果一致np.random.seed(42)# 设置可视化的参数%matplotlib inlineimport matplotlib as mplimport matplotlib.pyplot as pltmpl.rc(axes, labelsize14)mpl.rc(xtick, labelsize12)mpl.rc(ytick, labelsize12)# 设置文件保存路径PROJECT_ROOT_DIR .CHAPTER_ID training_linear_models# 无视一些不重要的警告import warningswarnings.filterwarnings(actionignore, message^internal gelsd)用y43xy43x高斯噪声来生成数据点x0x0为1import numpy as npX 2 * np.random.rand(100, 1) #X中所有点的范围在0-2之间y 4 3 * X np.random.randn(100, 1)# 绘制定义好的方程plt.plot(X, y, b.)plt.xlabel($x_1$, fontsize18)plt.ylabel($y$, rotation0, fontsize18)plt.axis([0, 2, 0, 15])# save_fig(generated_data_plot)plt.show()通过求解MSE的最小值^θ(XT⋅X)−1⋅XT⋅yθ^(XT⋅X)−1⋅XT⋅y 求解θθ值这就是一个模型的训练过程X_bnp.c_[np.ones((100, 1)), X]# add x0 1 to each instancetheta_bestnp.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y) theta_bestarray([[4.21509616], [2.77011339]])把x01x01带入可计算出y值这里面因为有X_new是二维的所以x0也是二维的这里X_new是两个数据点X_newnp.array([[0], [2]]) X_new_bnp.c_[np.ones((2, 1)), X_new]# add x0 1 to each instancey_predictX_new_b.dot(theta_best) y_predictarray([[4.21509616], [9.75532293]])plt.plot(X_new, y_predict, r-, linewidth2, labelPredictions) plt.plot(X, y, b.) plt.xlabel($x_1$, fontsize18) plt.ylabel($y$, rotation0, fontsize18) plt.legend(locupper left, fontsize14) plt.axis([0, 2, 0, 15]) plt.show()LinearRegression是基于最小二乘方法的线性模型训练过程使用正规方程求解fromsklearn.linear_modelimportLinearRegression lin_regLinearRegression() lin_reg.fit(X, y) lin_reg.intercept_, lin_reg.coef_(array([4.21509616]), array([[2.77011339]]))lin_reg.predict(X_new)array([[4.21509616], [9.75532293]])梯度下降训练线性回归eta0.1 n_iterations1000 m100 thetanp.random.randn(2,1)foriterationinrange(n_iterations): gradients2/m*X_b.T.dot(X_b.dot(theta)-y) thetatheta-eta*gradientsthetaarray([[4.21509616], [2.77011339]])预测X_new_b.dot(theta)array([[4.21509616], [9.75532293]])绘制不同学习率下的学习过程theta_path_bgd[] # 函数 绘制不同学习率下的学习过程defplot_gradient_descent(theta, eta, theta_pathNone): mlen(X_b) plt.plot(X, y, b.) n_iterations1000foriterationinrange(n_iterations):ifiteration10: y_predictX_new_b.dot(theta) styleb-ifiteration0elser-- plt.plot(X_new, y_predict, style) gradients2/m*X_b.T.dot(X_b.dot(theta)-y) thetatheta-eta*gradientsiftheta_pathisnotNone: theta_path.append(theta) plt.xlabel($x_1$, fontsize18) plt.axis([0, 2, 0, 15]) plt.title(r$\eta {}$.format(eta), fontsize16)np.random.seed(42) thetanp.random.randn(2,1)# random initializationplt.figure(figsize(10,4)) plt.subplot(131); plot_gradient_descent(theta, eta0.02) plt.ylabel($y$, rotation0, fontsize18) plt.subplot(132); plot_gradient_descent(theta, eta0.1, theta_paththeta_path_bgd) plt.subplot(133); plot_gradient_descent(theta, eta0.5) plt.show()这里面绘制了前10次迭代的情况可以看到第一幅图由于学习率很小梯度下降进展很慢。第二幅图可以看到当学习率适中时梯度下降可以快速开始寻找最优解。第三幅图当学习率比较大时梯度下降很可能永远找不到最优解。随机梯度下降每次用所有样本来梯度下降依然很慢可以每次只用其中一个值尽管会引入一些不规律性算法也没法收敛到最优解但通常最后的参数还不错另外也可以帮助跳出局部最优解。一个优化的方法是逐渐的减小学习率这个过程称为模拟退火。theta_path_sgd[] mlen(X_b) np.random.seed(42) n_epochs50 t0, t15, 50# learning schedule hyperparametersdeflearning_schedule(t):returnt0/(tt1) thetanp.random.randn(2,1)# random initializationforepochinrange(n_epochs):foriinrange(m):ifepoch0andi20:# not shown in the booky_predictX_new_b.dot(theta)# not shownstyleb-ifi0elser--# not shownplt.plot(X_new, y_predict, style)# not shownrandom_indexnp.random.randint(m) xiX_b[random_index:random_index1] yiy[random_index:random_index1] gradients2*xi.T.dot(xi.dot(theta)-yi) etalearning_schedule(epoch*mi) thetatheta-eta*gradients theta_path_sgd.append(theta)# not shownplt.plot(X, y, b.)# not shownplt.xlabel($x_1$, fontsize18)# not shownplt.ylabel($y$, rotation0, fontsize18)# not shownplt.axis([0, 2, 0, 15])# not shownplt.show()thetaarray([[4.21076011], [2.74856079]])sklearn库中可以使用函数实现随机梯度下降SGDRegressor()fromsklearn.linear_modelimportSGDRegressor sgd_regSGDRegressor(max_iter50, tol-np.infty, penaltyNone, eta00.1, random_state42) sgd_reg.fit(X, y.ravel())SGDRegressor(eta00.1, max_iter50, penaltyNone, random_state42, tol-inf)sgd_reg.intercept_, sgd_reg.coef_(array([4.16782089]), array([2.72603052]))小批量梯度下降在迭代的每一步批量梯度使用整个训练集随机梯度使用仅仅一个实例在小批量梯度下降中它则使用一个随机的小型实例集。它比随机梯度的主要优点在于你可以通过矩阵运算的硬件优化得到一个较好的训练表现尤其当你使用GPU进行运算的时候。theta_path_mgd[] n_iterations50 minibatch_size20 np.random.seed(42) thetanp.random.randn(2,1)# random initializationt0, t1200, 1000deflearning_schedule(t):returnt0/(tt1) t0forepochinrange(n_iterations): shuffled_indicesnp.random.permutation(m) X_b_shuffledX_b[shuffled_indices] y_shuffledy[shuffled_indices]foriinrange(0, m, minibatch_size): t1 xiX_b_shuffled[i:iminibatch_size] yiy_shuffled[i:iminibatch_size] gradients2/minibatch_size*xi.T.dot(xi.dot(theta)-yi) etalearning_schedule(t) thetatheta-eta*gradients theta_path_mgd.append(theta)thetaarray([[4.25214635], [2.7896408 ]])三个方法的训练过程数据theta_path_bgdnp.array(theta_path_bgd) theta_path_sgdnp.array(theta_path_sgd) theta_path_mgdnp.array(theta_path_mgd)# 可视化 三个方法的训练过程数据 plt.figure(figsize(7,4)) plt.plot(theta_path_sgd[:, 0], theta_path_sgd[:, 1], r-s, linewidth1, labelStochastic) plt.plot(theta_path_mgd[:, 0], theta_path_mgd[:, 1], g-, linewidth2, labelMini-batch) plt.plot(theta_path_bgd[:, 0], theta_path_bgd[:, 1], b-o, linewidth3, labelBatch) plt.legend(locupper left, fontsize16) plt.xlabel(r$\theta_0$, fontsize20) plt.ylabel(r$\theta_1$ , fontsize20, rotation0) plt.axis([2.5, 4.5, 2.3, 3.9]) plt.show()从图中可以看出随机梯度下降法的稳定性较差波动较大批量梯度下降法虽然整体性能最优但是训练过程的时耗最大小批量梯度下降法则是两者的折中在大多数任务下的使用率最高。