使用jupyter先進行了線性回歸的入門
到第二節課非線性回歸就不行了???
train_on_batch(x, y) 那一行會報錯:
0 successful operations.
0 derived errors ignored.
解決辦法:
将之前的第一個線性回歸案例在jupyter中點選中斷服務
再運作第二個案例就可以了
後來發現又不行了
直接重新開機jupyter notebook
總結:隻有重新開機jupyter notebook才能完美解決這個問題
import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential # 順序構成的模型
from keras.layers import Dense # 全連接配接層
#
x = np.linspace(-0.5, 0.5, 200)
noise = np.random.normal(0, 0.02, x.shape)
y = np.square(x) + noise
# 顯示随機點
plt.scatter(x, y)
plt.show()
# 建構順序模型
model = Sequential()
# 在模型中添加一個全連接配接層
model.add(Dense(units=1, input_dim=1))
model.compile(optimizer='sgd', loss='mse') # sgd随機梯度下降 mse均方誤差
# 訓練
for step in range(1000):
cost = model.train_on_batch(x, y)
if step % 100 == 0:
print('cost:', cost)
# 列印權值和偏置
w, b = model.layers[0].get_weights()
print('w:', w, '\nb:', b)
# 得到預測值
y_pred = model.predict(x)
# 顯示随機點
plt.scatter(x, y)
# 顯示預測結果
plt.plot(x, y_pred, 'r', lw=3)
plt.show()