Training with Keras

Introduzione a TensorFlow in Python

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

Overview of training and evaluation

  1. Load and clean data
  2. Define model
  3. Train and validate model
  4. Evaluate model
Introduzione a TensorFlow in Python

How to train a model

# Import tensorflow
import tensorflow as tf

# Define a sequential model
model = tf.keras.Sequential()
# Define the hidden layer
model.add(tf.keras.layers.Dense(16, activation='relu', input_shape=(784,)))
# Define the output layer
model.add(tf.keras.layers.Dense(4, activation='softmax'))
Introduzione a TensorFlow in Python

How to train a model

# Compile model
model.compile('adam', loss='categorical_crossentropy')
# Train model
model.fit(image_features, image_labels)
Introduzione a TensorFlow in Python

The fit() operation

  • Required arguments
    • features
    • labels
  • Many optional arguments
    • batch_size
    • epochs
    • validation_split
Introduzione a TensorFlow in Python

Batch size and epochs

The diagram illustrates how a dataset is divided into batches and the combination of those batches equals one epoch.

Introduzione a TensorFlow in Python

Performing validation

The image shows a dataset being split into a training and validation sample.

Introduzione a TensorFlow in Python

Performing validation

# Train model with validation split
model.fit(features, labels, epochs=10, validation_split=0.20)
Introduzione a TensorFlow in Python

Performing validation

The image shows 10 epochs of training and validation results.

Introduzione a TensorFlow in Python

Changing the metric

# Recomile the model with the accuracy metric
model.compile('adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Train model with validation split
model.fit(features, labels, epochs=10, validation_split=0.20)
Introduzione a TensorFlow in Python

Changing the metric

The image shows 10 epochs of training and validation results.

Introduzione a TensorFlow in Python

The evaluation() operation

The image shows a dataset being split into a training, validation, and test sample.

# Evaluate the test set
model.evaluate(test)
Introduzione a TensorFlow in Python

Let's practice!

Introduzione a TensorFlow in Python

Preparing Video For Download...