Get startedGet started for free

Last steps in classification models

You'll now create a classification model using the titanic dataset, which has been pre-loaded into a DataFrame called df. You'll take information about the passengers and predict which ones survived.

The predictive variables are stored in a NumPy array predictors. The target to predict is in df.survived, though you'll have to manipulate it for Keras. The number of predictive features is stored in n_cols.

Here, you'll use the 'sgd' optimizer, which stands for Stochastic Gradient Descent. You'll learn more about this in the next chapter!

This exercise is part of the course

Introduction to Deep Learning in Python

View Course

Exercise instructions

  • Convert df.survived to a categorical variable using the to_categorical() function.
  • Specify a Sequential model called model.
  • Add a Dense layer with 32 nodes. Use 'relu' as the activation and (n_cols,) as the input_shape.
  • Add the Dense output layer. Because there are two outcomes, it should have 2 units, and because it is a classification model, the activation should be 'softmax'.
  • Compile the model, using 'sgd' as the optimizer, 'categorical_crossentropy' as the loss function, and metrics=['accuracy'] to see the accuracy (what fraction of predictions were correct) at the end of each epoch.
  • Fit the model using the predictors and the target.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# 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
____
Edit and Run Code