浪子归家|求解线性回归应使用哪些方法?( 三 )

h = lambda theta_0, theta_1, x: theta_0 + np.dot(x,theta_1) #equation of straight lines# the cost function (for the whole batch. for comparison later)def J(x, y, theta_0, theta_1):m = len(x)returnValue = http://kandian.youth.cn/index/0for i in range(m):returnValue += (h(theta_0, theta_1, x[i]) - y[i])**2returnValue = returnValue/(2*m)return returnValue# finding the gradient per each training exampledef grad_J(x, y, theta_0, theta_1):returnValue = np.array([0., 0.])returnValue[0] += (h(theta_0, theta_1, x) - y)returnValue[1] += (h(theta_0, theta_1, x) - y)*xreturn returnValueclass AdamOptimizer:def __init__(self, weights, alpha=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8):self.alpha = alphaself.beta1 = beta1self.beta2 = beta2self.epsilon = epsilonself.m = 0self.v = 0self.t = 0self.theta = weightsdef backward_pass(self, gradient):self.t = self.t + 1self.m = self.beta1*self.m + (1 - self.beta1)*gradientself.v = self.beta2*self.v + (1 - self.beta2)*(gradient**2)m_hat = self.m/(1 - self.beta1**self.t)v_hat = self.v/(1 - self.beta2**self.t)self.theta = self.theta - self.alpha*(m_hat/(np.sqrt(v_hat) - self.epsilon))return self.theta在这里 , 我们使用面向对象的方法和一些辅助函数来实现上述伪代码中提到的所有方程式 。
现在让我们为模型设置超参数 。
epochs = 1500print_interval = 100m = len(x)initial_theta = np.array([0., 0.]) # initial value of theta, before gradient descentinitial_cost = J(x, y, initial_theta[0], initial_theta[1])theta = initial_thetaadam_optimizer = AdamOptimizer(theta, alpha=0.001)adam_history = [] # to plot out path of descentadam_history.append(dict({'theta': theta, 'cost': initial_cost})#to check theta and cost function最后是训练过程 。
【浪子归家|求解线性回归应使用哪些方法?】for j in range(epochs):for i in range(m):gradients = grad_J(x[i], y[i], theta[0], theta[1])theta = adam_optimizer.backward_pass(gradients)if ((j+1)%print_interval == 0 or j==0):cost = J(x, y, theta[0], theta[1])print ('After {} epochs, Cost = {}, theta = {}'.format(j+1, cost, theta))adam_history.append(dict({'theta': theta, 'cost': cost}))print ('\nFinal theta = {}'.format(theta))
浪子归家|求解线性回归应使用哪些方法?现在 , 如果将 Final theta 值与先前使用scipy.stats.mstat.linregress计算的斜率和截距值进行 比较 , 则它们几乎相等 , 并且可以通过调整超参数来达到100%相等 。
最后 , 让我们绘制它 。
b = theta yhat = b [0] + x.dot(b [1])pyplot.figure(figsize =(15,8))pyplot.scatter(x , y , color ='red')pyplot.plot(x, yhat , color ='blue')pyplot.show()
浪子归家|求解线性回归应使用哪些方法?我们可以看到我们的绘图类似于使用sns.regplot获得的 绘图
优点: