随机梯度算法 python

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

##产生训练数据
x=np.arange(0.,10.,0.2)
m=len(x)
x0=np.full(m,1.0)
input_data=np.vstack([x0,x]).T
target_data=2*input_data[:,1]+5*input_data[:,0]+np.random.randn(m)
##设置最大循环次数以及模型误差范围
loop_max=10000
epsilon=1e-3
##训练模型权重初始化
np.random.seed(0)
theta=np.random.randn(2)

alpha=0.001#训练速度
diff=0.       
error=np.zeros(2)
count=0#统计训练次数
finish=0#训练截止标志

while count<loop_max:
    count+=1
    
    for i in range(m):
        k=np.random.randint(0,49)#随机选取训练样本更新权重
        diff= np.dot(theta,input_data[k])-target_data[k]
        
        theta=theta-alpha*diff*input_data[k]
    
    if np.linalg.norm(theta-error)<epsilon:
        finish=1
        break
    else:
        error=theta
print('loop count=%d' %count,'\tw:',theta)
    
slope, intercept, r_value,p_value,slope_std_error=stats.linregress(x,target_data)#模型与python自带线性拟合模型对比
print('intercept=%s slope=%s' %(intercept,slope))

plt.plot(x,target_data,'g*')
plt.plot(x,theta[1]*x+theta[0],'r')
plt.show()  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值