單層神經網路
為了更熟悉神經網路,先從簡單的函式近似開始最有幫助。
你將訓練一個神經網路,去近似輸入 x 與輸出 y 之間的對應關係。兩者由平方根函式相連,也就是 $y = \sqrt{x}$。
輸入向量 x 已提供給你。你會先用 Numpy 的 sqrt() 函式計算 x 的平方根,產生輸出序列 y。接著你會建立一個簡單的神經網路,並在 x 序列上訓練這個網路。
訓練完成後,你會將 y 序列與神經網路的輸出一起繪圖,比較網路對平方根函式的近似程度。
Keras 函式庫中的 Sequential 與 Dense 物件已可在你的工作區中使用。
本練習屬於課程
Python 量化風險管理
練習說明
- 使用 Numpy 的
sqrt()函式建立輸出的訓練值。 - 建立一個具有 1 個隱藏層(16 個神經元)、1 個輸入值與 1 個輸出值的神經網路。
- 使用訓練值對神經網路進行 compile 與 fit,訓練 100 個 epochs。
- 繪製訓練值(藍色)與神經網路的預測值,以進行比較。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create the training values from the square root function
y = np.____(x)
# Create the neural network
model = Sequential()
model.____(Dense(16, input_dim=1, activation='relu'))
model.____(____(1))
# Train the network
model.____(loss='mean_squared_error', optimizer='rmsprop')
model.____(x, y, epochs=100)
## Plot the resulting approximation and the training values
plt.plot(x, y, x, model.____(x))
plt.show()