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
Exercise instructions
- Convert
df.survived
to a categorical variable using theto_categorical()
function. - Specify a
Sequential
model calledmodel
. - Add a
Dense
layer with32
nodes. Use'relu'
as theactivation
and(n_cols,)
as theinput_shape
. - Add the
Dense
output layer. Because there are two outcomes, it should have 2 units, and because it is a classification model, theactivation
should be'softmax'
. - Compile the model, using
'sgd'
as theoptimizer
,'categorical_crossentropy'
as the loss function, andmetrics=['accuracy']
to see the accuracy (what fraction of predictions were correct) at the end of each epoch. - Fit the model using the
predictors
and thetarget
.
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
____