浪子归家|求解线性回归应使用哪些方法?( 三 )
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获得的 绘图 。
优点:
- 直接实施 。
- 计算效率高 。
- 很少的内存需求 。
- 梯度的对角线重标不变 。
推荐阅读
- 逍遥浪子龙|汽车“栽进窗”,太危险!女子停车忘拉手刹
- 泰国|泰国曼谷再次爆发大规模抗议,要求解散国会王室改革
- [婚外情]我结婚了但爱上了别人,心存愧疚,我想回归家庭该怎么做
- 大城市|求解大城市“一床难求” “十三五”中央财政投资养老超134亿元
- 穿搭|穿花花毛衣来看花花世界,怎么才能把毛衣穿的年轻一点!求解
- 足坛最前线|却被国米球迷永远拉黑,布尔迪索:潘帕斯浪子中后卫
- 土土女排|进攻实力将大幅提升,回归家乡!女排世界冠军有望加盟辽宁
- 钱江晚报|老人凌晨买菜…夜班公交司机汤小连:我见过杭城隐秘风景,年轻人半夜归家
- 科技浪子|非蠢即坏,手机欠费超3月上征信?网友:不知道哪个B出的主意
- 科技浪子 非蠢即坏,手机欠费超3月上征信?网友:不知道哪个B出的主意
