使用自定义损失函数训练神经网络
现在我们将使用刚刚创建的自定义损失函数。这能让我们根据具体问题以更有用的方式调整模型行为——它会促使模型至少学会正确预测价格变动的方向。接下来只需在 .compile() 函数中将 loss 参数设置为我们的函数名 sign_penalty。我们会再次查看训练损失,确认它已经变得平稳。
本练习是课程的一部分
Python 金融机器学习
练习说明
- 将第一层神经网络的
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()