隨機梯度算法 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()  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章