1、Dense在線性迴歸時候不需要指定激活函數
Dense就是全連接層的意思,就是y=Wx+b的形式,做線性迴歸不需要在Dense中添加激活函數,如果加了就是 y=F(Wx+b)的形式了,這一點不要搞錯了
2、model.layers[0].get_weights()函數獲取W,b參數
3、測試數據與噪聲要適當選取,噪聲太大可能會不收斂
import keras
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy as np
x=np.random.rand(50)10
noise=np.random.normal(0,0.1,50)5
y=x3+2+noise
plt.ion()
plt.scatter(x,y)
plt.show()
model=keras.Sequential()
model.add(Dense(1,input_dim=1,activation=“relu”))#Wx+b的形式
#adam=keras.optimizers.Adam(lr=0.0001)
model.compile(optimizer=“sgd”,loss=“mse”)#指定優化器爲Adam,也可以是“sgd”
#model.fit(x,y,epochs=100,verbose=2)
for i in range(3000):
cost=model.train_on_batch(x,y)
if i%1000==0:
print(cost)
py=model.predict(x)
W,b=model.layers[0].get_weights()#獲取兩個參數 w,b
print(W,b)
plt.plot(x,py)
plt.show()