python线性回归实例 python一元线性回归分析代码( 四 )


让我们构建一个函数来绘制成本函数:
def plot_cost_function(self):if self.bgd == True:plt.plot(range((self.n_iterations)),self.cost_history)plt.xlabel('No. of iterations')plt.ylabel('Cost Function')plt.title('Gradient Descent Cost Function Line Plot')plt.show()else:print('Batch Gradient Descent was not used!')最后一种预测未标记实例的方法:
def predict(self,X_test):self.X_test = X_test.copy()self.X_test = self.add_intercept_term(self.X_test)self.X_test = self.feature_scale(self.X_test)predictions = np.dot(self.X_test,self.thetas.T)return predictions现在,让我们看看哪个优化产生了更好的结果 。首先,让我们试试梯度下降:
lin_reg_bgd = LinReg(X_train,y_train)lin_reg_bgd.fit(bgd=True)mse(y_test,lin_reg_bgd.predict(X_test))OUT:28.824024414708344让我们画出我们的函数,看看成本函数是如何减少的:
所以我们可以看到,在大约1000次迭代时,它开始收敛 。
现在的标准方程是:
lin_reg_normal = LinReg(X_train,y_train)lin_reg_normal.fit()mse(y_test,lin_reg_normal.predict(X_test))OUT:22.151417764247284所以我们可以看到,标准方程的性能略优于梯度下降法 。这可能是因为数据集很小,而且我们没有为学习率选择最佳参数 。

推荐阅读