開始使用免費開始

使用自訂損失函式來訓練神經網路

現在我們要使用剛剛建立的自訂損失函式。這能讓我們依照問題需求改變模型的行為——我們會嘗試讓模型至少能正確預測價格變動的方向。你只需要在 .compile() 中把 loss 參數設為我們的函式名稱 sign_penalty。接著再次檢視訓練損失,確認它已經趨於平坦。

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

  • 將第一層神經網路的 input_dim 設為 scaled_train_features 的欄數,也就是 .shape[1]
  • 使用自訂的 sign_penalty 損失函式來 .compile() 我們的 model_2
  • 繪製訓練過程的損失,可從 history 物件取得,位置在 history.history['loss']

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create the model
model_2 = Sequential()
model_2.add(Dense(100, input_dim=____, activation='relu'))
model_2.add(Dense(20, activation='relu'))
model_2.add(Dense(1, activation='linear'))

# Fit the model with our custom 'sign_penalty' loss function
model_2.compile(optimizer='adam', loss=____)
history = model_2.fit(scaled_train_features, train_targets, epochs=25)
plt.plot(____)
plt.title('loss:' + str(round(history.history['loss'][-1], 6)))
plt.show()
編輯並執行程式碼