介绍
用python实现梯度下降算法的方式是什么?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!
python版本选择
这里选的python版本是2.7,因为我之前用python3试了几次,发现在画三维图的时候会报错,所以改用了2.7 .
(推荐教程:python入门教程)
数据集选择
数据集我选了一个包含两个变量,三个参数的数据集,这样可以画出三维图形对结果进行验证。
部分函数总结()
符号函数:首先要安装sympy库才可以使用。用法:
在祝辞祝辞,x1 =,符号(& # 39;x2 # 39;) 在祝辞祝辞,x1 + 1 x2 +, 1
在这个例子中,x1和x2是不一样的,x2代表的是一个函数的变量,而x1代表的是python中的一个变量,它可以表示函数的变量,也可以表示其他的任何量,它替代x2进行函数的计算。实际使用的时候我们可以将x1, x2都命名为x,但是我们要知道他们俩的区别。
再看看这个例子:
在祝辞祝辞,x =,符号(& # 39;x # 39;) 在祝辞祝辞,expr =, x + 1 在祝辞祝辞x =, 2 在祝辞祝辞,打印(expr) x +, 1
作为python变量的x被2这个数值覆盖了,所以它现在不再表示函数变量x,而expr依然是函数变量x + 1的别名,所以结果依然是x + 1。
潜艇()函数:既然普通的方法无法为函数变量赋值,那就肯定有函数来实现这个功能,用法:
在祝辞祝辞,(1,+,* * y) .subs (x,,π)#一个参数时的用法 π* y + 1 在祝辞祝辞,(1,+,* * y) .subs ({x:π,,y: 2}) #多个参数时的用法 1,+,2π*
diff()函数:求偏导数,用法:结果=diff(有趣,x),这个就是求乐趣函数对x变量的偏导数,结果结果也是一个变量,需要赋值才能得到准确结果。
代码实现:
得到__future__ import 部门 得到sympy import 符号,diff,,扩大 import numpy  as np import matplotlib.pyplot  as plt 得到mpl_toolkits.mplot3d import  Axes3D data =, {& # 39; x1 # 39;:,(100年,50岁,100年,100年,50岁,80,75,65,90,90]。 ,,,,,,,& # 39;x2 # 39;:, (4,, 3,, 4,, 2,, 2,, 2,, 3,, 4,, 3,, 2), ,,,,,,,& # 39;y # 39;:,(9.3, 4.8, 8.9, 6.5, 4.2, 6.2, 7.4, 6.0, 7.6, 6.1]} #初始化数据集 theta0,θ?,theta2 =,符号(& # 39;theta0  theta1 θ# 39;,,真正的=True),, #, y=theta0 +θ?* x1 +θ* x2,定义参数 costfuc =, 0, * theta0 for 小姐:拷贝范围(10): ,,,costfuc +=,(时间+ theta0 theta1 *,数据(& # 39;x1 # 39;][我],+,theta2 *,数据(& # 39;x2 # 39;][我],安康;数据(& # 39;y # 39;][我]),* *,2 costfuc /=, 20 #初始化代价函数 时间=dtheta0 diff (costfuc, theta0) 时间=dtheta1 diff (costfuc,θ? 时间=dtheta2 diff (costfuc,θ) rtheta0 =1 rtheta1 =1 rtheta2 =, 1 #为参数赋初始值 时间=costvalue costfuc.subs ({theta0: rtheta0,,θ?:,rtheta1,,θ:,rtheta2}) 时间=newcostvalue 0 #用成本的值的变化程度来判断是否已经到最小值了 count =0 alpha =, 0.0001 #设置学习率,一定要设置的比较小,否则无法到达最小值 while (costvalue 安康;newcostvalue 祝辞,0.00001,趁机newcostvalue 作用;costvalue 祝辞,0.00001),以及count & lt;, 1000: ,,,count +=1 ,,,costvalue =newcostvalue ,,,rtheta0 =, rtheta0 作用;alpha *, dtheta0.subs ({theta0: rtheta0,,θ?:,rtheta1,,θ:,rtheta2}) ,,,rtheta1 =, rtheta1 作用;alpha *, dtheta1.subs ({theta0: rtheta0,,θ?:,rtheta1,,θ:,rtheta2}) ,,,rtheta2 =, rtheta2 作用;alpha *, dtheta2.subs ({theta0: rtheta0,,θ?:,rtheta1,,θ:,rtheta2}) ,,,newcostvalue =, costfuc.subs ({theta0: rtheta0,,θ?:,rtheta1,,θ:,rtheta2}) 时间=rtheta0 圆(rtheta0, 4) 时间=rtheta1 圆(rtheta1, 4) 时间=rtheta2 圆(rtheta2, 4) #给结果保留4位小数,防止数值溢出 打印(rtheta0, rtheta1, rtheta2) 时间=fig plt.figure () 时间=ax Axes3D(图) ax.scatter(数据(& # 39;x1 # 39;],,数据(& # 39;x2 # 39;],,数据(& # 39;y # 39;]),, #,绘制散点图 xx =, np.arange(20日,100年,1) 时间=yy np.arange (1,, 5, 0.05) 时间=X,, Y np.meshgrid (xx, yy) 时间=Z X *, rtheta1 +, Y *, rtheta2 + rtheta0 ax.plot_surface (X, Y,, Z, rstride=1, cstride=1,提出=plt.get_cmap(& # 39;彩虹# 39;)) plt.show() #绘制3 d图进行验证用python实现梯度下降算法的方式是什么