为网络添加层
您已经学习了如何尝试更"宽"的网络。在本练习中,您将尝试更"深"的网络(更多隐藏层)。
同样地,您有一个基线模型 model_1 作为起点。它只有 1 个隐藏层,具有 10 个单元。您可以看到该模型结构的摘要。接下来,您将创建一个类似的网络,但包含 3 个隐藏层(每层仍保持 10 个单元)。
拟合两个模型仍需要一点时间,所以在运行代码后,您需要等待几秒钟才能看到结果。
本练习是课程的一部分
Python 深度学习入门
练习说明
- 指定一个名为
model_2的模型,使其与model_1类似,但包含 3 个具有 10 个单元的隐藏层,而不是仅 1 个隐藏层。- 在第一个隐藏层中使用
input_shape指定输入形状。 - 对 3 个隐藏层使用
'relu'激活函数,对输出层使用'softmax',输出层应有 2 个单元。
- 在第一个隐藏层中使用
- 按照之前模型的方式编译
model_2:optimizer使用'adam',loss使用'categorical_crossentropy',并设置metrics=['accuracy']。 - 点击 "Submit Answer" 来拟合两个模型,并可视化哪个模型效果更好!
交互式实操练习
通过完成这段示例代码来试试这个练习。
# The input shape to use in the first hidden layer
input_shape = (n_cols,)
# Create the new model: model_2
model_2 = ____
# Add the first, second, and third hidden layers
____
____
____
# Add the output layer
____
# Compile model_2
____
# Fit model 1
model_1_training = model_1.fit(predictors, target, epochs=15, validation_split=0.4, verbose=False)
# Fit model 2
model_2_training = model_2.fit(predictors, target, epochs=15, validation_split=0.4, verbose=False)
# Create the plot
plt.plot(model_1_training.history['val_loss'], 'r', model_2_training.history['val_loss'], 'b')
plt.xlabel('Epochs')
plt.ylabel('Validation score')
plt.show()