Get startedGet started for free

Specifying a model

Now you'll get to work with your first model in Keras, and will immediately be able to run more complex neural network models on larger datasets compared to the first two chapters.

To start, you'll take the skeleton of a neural network and add a hidden layer and an output layer. You'll then fit that model and see Keras do the optimization so your model continually gets better.

As a start, you'll predict workers wages based on characteristics like their industry, education and level of experience. You can find the dataset in a pandas DataFrame called df. For convenience, everything in df except for the target has been converted to a NumPy array called predictors. The target, wage_per_hour, is available as a NumPy array called target.

For all exercises in this chapter, we've imported the Sequential model constructor, the Dense layer constructor, and pandas.

This exercise is part of the course

Introduction to Deep Learning in Python

View Course

Exercise instructions

  • Store the number of columns in the predictors data to n_cols. This has been done for you.
  • Start by creating a Sequential model called model.
  • Use the .add() method on model to add a Dense layer.
    • Add 50 units, specify activation='relu', and the input_shape parameter to be the tuple (n_cols,) which means it has n_cols items in each row of data, and any number of rows of data are acceptable as inputs.
  • Add another Dense layer. This should have 32 units and a 'relu' activation.
  • Finally, add an output layer, which is a Dense layer with a single node. Don't use any activation function here.

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

# Save the number of columns in predictors: n_cols
n_cols = predictors.shape[1]

# Set up the model: model
model = ____

# Add the first layer
____.____(____(____, ____=____, ____=(____)))

# Add the second layer
____

# Add the output layer
____
Edit and Run Code