python梯度下降算法的实现
本文实例为大家分享了python实现梯度下降算法的具体代码,供大家参考,具体内容如下
简介
本文使用python实现了梯度下降算法,支持y=Wx+b的线性回归
目前支持批量梯度算法和随机梯度下降算法(bs=1)
也支持输入特征向量的x维度小于3的图像可视化
代码要求python版本>3.4
代码
'''
梯度下降算法
BatchGradientDescent
StochasticGradientDescentSGD
'''
__author__='epleone'
importnumpyasnp
importmatplotlib.pyplotasplt
frommpl_toolkits.mplot3dimportAxes3D
importsys
#使用随机数种子,让每次的随机数生成相同,方便调试
#np.random.seed(111111111)
classGradientDescent(object):
eps=1.0e-8
max_iter=1000000#暂时不需要
dim=1
func_args=[2.1,2.7]#[w_0,..,w_dim,b]
def__init__(self,func_arg=None,N=1000):
self.data_num=N
iffunc_argisnotNone:
self.FuncArgs=func_arg
self._getData()
def_getData(self):
x=20*(np.random.rand(self.data_num,self.dim)-0.5)
b_1=np.ones((self.data_num,1),dtype=np.float)
#x=np.concatenate((x,b_1),axis=1)
self.x=np.concatenate((x,b_1),axis=1)
deffunc(self,x):
#noise太大的话,梯度下降法失去作用
noise=0.01*np.random.randn(self.data_num)+0
w=np.array(self.func_args)
#y1=w*self.x[0,]#直接相乘
y=np.dot(self.x,w)#矩阵乘法
y+=noise
returny
@property
defFuncArgs(self):
returnself.func_args
@FuncArgs.setter
defFuncArgs(self,args):
ifnotisinstance(args,list):
raiseException(
'argsisnotlist,itshouldbelike[w_0,...,w_dim,b]')
iflen(args)==0:
raiseException('argsisemptylist!!')
iflen(args)==1:
args.append(0.0)
self.func_args=args
self.dim=len(args)-1
self._getData()
@property
defEPS(self):
returnself.eps
@EPS.setter
defEPS(self,value):
ifnotisinstance(value,float)andnotisinstance(value,int):
raiseException("Thetypeofepsshouldbeanfloatnumber")
self.eps=value
defplotFunc(self):
#一维画图
ifself.dim==1:
#x=np.sort(self.x,axis=0)
x=self.x
y=self.func(x)
fig,ax=plt.subplots()
ax.plot(x,y,'o')
ax.set(xlabel='x',ylabel='y',title='LossCurve')
ax.grid()
plt.show()
#二维画图
ifself.dim==2:
#x=np.sort(self.x,axis=0)
x=self.x
y=self.func(x)
xs=x[:,0]
ys=x[:,1]
zs=y
fig=plt.figure()
ax=fig.add_subplot(111,projection='3d')
ax.scatter(xs,ys,zs,c='r',marker='o')
ax.set_xlabel('XLabel')
ax.set_ylabel('YLabel')
ax.set_zlabel('ZLabel')
plt.show()
else:
#plt.axis('off')
plt.text(
0.5,
0.5,
"Thedimension(x.dim>2)\nistoohightodraw",
size=17,
rotation=0.,
ha="center",
va="center",
bbox=dict(
boxstyle="round",
ec=(1.,0.5,0.5),
fc=(1.,0.8,0.8),))
plt.draw()
plt.show()
#print('Thedimension(x.dim>2)istoohightodraw')
#梯度下降法只能求解凸函数
def_gradient_descent(self,bs,lr,epoch):
x=self.x
#shuffle数据集没有必要
#np.random.shuffle(x)
y=self.func(x)
w=np.ones((self.dim+1,1),dtype=float)
foreinrange(epoch):
print('epoch:'+str(e),end=',')
#批量梯度下降,bs为1时等价单样本梯度下降
foriinrange(0,self.data_num,bs):
y_=np.dot(x[i:i+bs],w)
loss=y_-y[i:i+bs].reshape(-1,1)
d=loss*x[i:i+bs]
d=d.sum(axis=0)/bs
d=lr*d
d.shape=(-1,1)
w=w-d
y_=np.dot(self.x,w)
loss_=abs((y_-y).sum())
print('\tLoss='+str(loss_))
print('拟合的结果为:',end=',')
print(sum(w.tolist(),[]))
print()
ifloss_
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。