Learn Keras by Example – How to do Neural Network Early Stopping

Neural Network Early Stopping

Preliminaries


/* Load libraries */
import numpy as np
from keras.datasets import imdb
from keras.preprocessing.text import Tokenizer
from keras import models
from keras import layers
from keras.callbacks import EarlyStopping, ModelCheckpoint

/* Set random seed */
np.random.seed(0)
Using TensorFlow backend.

Load Movie Review Text Data


/* Set the number of features we want */
number_of_features = 1000

/* Load data and target vector from movie review data */
(train_data, train_target), (test_data, test_target) = imdb.load_data(num_words=number_of_features)

/* Convert movie review data to a one-hot encoded feature matrix */
tokenizer = Tokenizer(num_words=number_of_features)
train_features = tokenizer.sequences_to_matrix(train_data, mode='binary')
test_features = tokenizer.sequences_to_matrix(test_data, mode='binary')

Create Neural Network Architecture


/* Start neural network */
network = models.Sequential()

/* Add fully connected layer with a ReLU activation function */
network.add(layers.Dense(units=16, activation='relu', input_shape=(number_of_features,)))

/* Add fully connected layer with a ReLU activation function */
network.add(layers.Dense(units=16, activation='relu'))

/* Add fully connected layer with a sigmoid activation function */
network.add(layers.Dense(units=1, activation='sigmoid'))

Compile Neural Network


/* Compile neural network */
network.compile(loss='binary_crossentropy', # Cross-entropy
                optimizer='rmsprop', # Root Mean Square Propagation
                metrics=['accuracy']) # Accuracy performance metric

Setup Early Stopping

In Keras, we can implement early stopping as a callback function. Callbacks are functions that can be applied at certain stages of the training process, such as at the end of each epoch. Specifically, in our solution, we included EarlyStopping(monitor='val_loss', patience=2) to define that we wanted to monitor the test (validation) loss at each epoch and after the test loss has not improved after two epochs, training is interrupted. However, since we set patience=2, we won’t get the best model, but the model two epochs after the best model. Therefore, optionally, we can include a second operation, ModelCheckpoint which saves the model to a file after every checkpoint (which can be useful in case a multi-day training session is interrupted for some reason. Helpful for us, if we set save_best_only=True then ModelCheckpoint will only save the best model.

*/ Set callback functions to early stop training and save the best model so far */
callbacks = [EarlyStopping(monitor='val_loss', patience=2),
             ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)]

Train Neural Network


/* Train neural network */
history = network.fit(train_features, # Features
                      train_target, # Target vector
                      epochs=20, # Number of epochs
                      callbacks=callbacks, # Early stopping
                      verbose=0, # Print description after each epoch
                      batch_size=100, # Number of observations per batch
                      validation_data=(test_features, test_target)) # Data for evaluation

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.  

Google –> SETScholars

A list of Python, R and SQL Codes for Applied Machine Learning and Data  Science at https://setscholars.net/Learn by Coding Categories:

  1. Classification: https://setscholars.net/category/classification/
  2. Data Analytics: https://setscholars.net/category/data-analytics/
  3. Data Science: https://setscholars.net/category/data-science/
  4. Data Visualisation: https://setscholars.net/category/data-visualisation/
  5. Machine Learning Recipe: https://setscholars.net/category/machine-learning-recipe/
  6. Pandas: https://setscholars.net/category/pandas/
  7. Python: https://setscholars.net/category/python/
  8. SKLEARN: https://setscholars.net/category/sklearn/
  9. Supervised Learning: https://setscholars.net/category/supervised-learning/
  10. Tabular Data Analytics: https://setscholars.net/category/tabular-data-analytics/
  11. End-to-End Data Science Recipes: https://setscholars.net/category/a-star-data-science-recipe/
  12. Applied Statistics: https://setscholars.net/category/applied-statistics/
  13. Bagging Ensemble: https://setscholars.net/category/bagging-ensemble/
  14. Boosting Ensemble: https://setscholars.net/category/boosting-ensemble/
  15. CatBoost: https://setscholars.net/category/catboost/
  16. Clustering: https://setscholars.net/category/clustering/
  17. Data Analytics: https://setscholars.net/category/data-analytics/
  18. Data Science: https://setscholars.net/category/data-science/
  19. Data Visualisation: https://setscholars.net/category/data-visualisation/
  20. Decision Tree: https://setscholars.net/category/decision-tree/
  21. LightGBM: https://setscholars.net/category/lightgbm/
  22. Machine Learning Recipe: https://setscholars.net/category/machine-learning-recipe/
  23. Multi-Class Classification: https://setscholars.net/category/multi-class-classification/
  24. Neural Networks: https://setscholars.net/category/neural-networks/
  25. Python Machine Learning: https://setscholars.net/category/python-machine-learning/
  26. Python Machine Learning Crash Course: https://setscholars.net/category/python-machine-learning-crash-course/
  27. R Classification: https://setscholars.net/category/r-classification/
  28. R for Beginners: https://setscholars.net/category/r-for-beginners/
  29. R for Business Analytics: https://setscholars.net/category/r-for-business-analytics/
  30. R for Data Science: https://setscholars.net/category/r-for-data-science/
  31. R for Data Visualisation: https://setscholars.net/category/r-for-data-visualisation/
  32. R for Excel Users: https://setscholars.net/category/r-for-excel-users/
  33. R Machine Learning: https://setscholars.net/category/r-machine-learning/
  34. R Machine Learning Crash Course: https://setscholars.net/category/r-machine-learning-crash-course/
  35. R Regression: https://setscholars.net/category/r-regression/
  36. Regression: https://setscholars.net/category/regression/
  37. XGBOOST: https://setscholars.net/category/xgboost/
  38. Excel examples for beginners: https://setscholars.net/category/excel-examples-for-beginners/
  39. C Programming tutorials & examples: https://setscholars.net/category/c-programming-tutorials/
  40. Javascript tutorials & examples: https://setscholars.net/category/javascript-tutorials-and-examples/
  41. Python tutorials & examples: https://setscholars.net/category/python-tutorials/
  42. R tutorials & examples: https://setscholars.net/category/r-for-beginners/
  43. SQL tutorials & examples: https://setscholars.net/category/sql-tutorials-for-business-analyst/

 

( FREE downloadable Mathematics Worksheet for Kids )