开始使用免费开始使用

分类模型的最后步骤

现在,您将使用已预加载为 DataFrame df 的泰坦尼克号数据集来创建一个分类模型。您将根据乘客信息预测哪些人幸存。

预测变量已存储在 NumPy 数组 predictors 中。需要预测的目标在 df.survived 中,不过为了适配 Keras,您需要先对其做一些处理。预测特征的数量存储在 n_cols 中。

这里,您将使用 'sgd' 优化器,即 Stochastic Gradient Descent 的缩写。您将在下一章进一步学习它!

本练习是课程的一部分

Python 深度学习入门

查看课程

练习说明

  • 使用 to_categorical()df.survived 转换为分类变量。
  • 指定一个名为 modelSequential 模型。
  • 添加一个具有 32 个节点的 Dense 层。将 activation 设为 'relu',并将 input_shape 设为 (n_cols,)
  • 添加 Dense 输出层。因为有两个结果,它应有 2 个单元;由于这是分类模型,activation 应为 'softmax'
  • 编译模型,optimizer 使用 'sgd',损失函数使用 'categorical_crossentropy',并设置 metrics=['accuracy'],以便在每个 epoch 结束时查看准确率(正确预测所占比例)。
  • 使用 predictorstarget 来拟合模型。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import necessary modules
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.utils import to_categorical

# Convert the target to categorical: target
target = ____

# Set up the model
model = ____

# Add the first layer
____

# Add the output layer
____

# Compile the model
____

# Fit the model
____
编辑并运行代码