Training with Keras

Introduction to 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
Introduction to 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'))
Introduction to TensorFlow in Python

How to train a model

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

The fit() operation

  • Required arguments
    • features
    • labels
  • Many optional arguments
    • batch_size
    • epochs
    • validation_split
Introduction to 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.

Introduction to TensorFlow in Python

Performing validation

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

Introduction to TensorFlow in Python

Performing validation

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

Performing validation

The image shows 10 epochs of training and validation results.

Introduction to 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)
Introduction to TensorFlow in Python

Changing the metric

The image shows 10 epochs of training and validation results.

Introduction to 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)
Introduction to TensorFlow in Python

Let's practice!

Introduction to TensorFlow in Python

Preparing Video For Download...