2017-07-23 75 views
1
import numpy as np 

np.random.seed(0) 
a = np.random.randint(1,100, size= 1000).reshape(1000,1) 
b = np.random.randint(0,2, size=1000).reshape(1000,1) 

y = np.where(b==0,a*2, a*3) 

X = np.hstack((a,b)) 
y = y 

from sklearn.preprocessing import StandardScaler 

sx = StandardScaler() 
X = sx.fit_transform(X) 

sy = StandardScaler() 
y = sy.fit_transform(y) 

w0 = np.random.normal(size=(2,1), scale=0.1) 



for i in range(100): 
    input_layer = X 
    output_layer = X.dot(w0) 

    error = y - output_layer 
    square_error = np.sqrt(np.mean(error**2)) 

    print(square_error) 



    w0+= input_layer.T.dot(error) 

如果我理解正確,線性激活函數總是f(x)= x。我的線性迴歸神經網絡有什麼問題

如果你檢查這段代碼,你會發現正方形誤差正在增長並且在增長,我不知道如何用NN解決這個簡單的線性問題。我知道還有其他的模型和圖書館,但我試圖這樣做。

回答

1

您沒有將學習率(請參閱here和更正式的討論here)合併到您的模型中。當你訓練你的網絡時,你也需要選擇一個學習速率參數,它對你的損失是否會減少以及它收斂的速度有很大的影響。

通過設置

w0+= input_layer.T.dot(error) 

您選擇的學習率是1,這竟然是太大。相反,如果你設置

w0+= 0.0005*input_layer.T.dot(error) 

(即選擇學習率0.0005)的損失將減少:

1.0017425183 
0.521060951473 
0.303777564629 
0.21993949808 
0.193933601196 
0.18700323975 
0.185262617455 
0.184832603515 
0.184726763539 
. 
. 
. 

它不會收斂於0,雖然,因爲你的模型是不是線性的。最後,你得到的重量w0

array([[ 0.92486712], 
     [ 0.318241 ]]) 
+0

嘿米里亞姆,再次,非常感謝你。你是最棒的! – Makaroniiii

+0

謝謝,很高興幫助:) –