Module 20 · Deep learning and neural networks · Lesson 66 of 66

Project: spot fake bank notes

Train a neural network on measurements of bank note images, then check it against a random forest.

In this lesson · about 25 minutes

  • Scale features and split data for a neural network
  • Train a deeper network and read its report
  • Compare it with a random forest

This data set from the UCI Machine Learning Repository measures photos of 1,372 bank notes, some real and some forged. Each photo was turned into four numbers that describe its texture (Image.Var, Image.Skew, Image.Curt and Entropy). Class is the answer: 0 for real, 1 for fake.

Exercise

1. How many of each?

Draw a count plot of Class with Seaborn.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('bank_note_data.csv')

2. All the features at once

A pair plot colored by class. Image.Var alone already separates most real notes from fakes.

Exercise

3. Scale the features

Create a StandardScaler called scaler, fit it to every column except Class, and put the scaled values in a DataFrame called df_feat with the same column names (df.columns[:-1]). End with df_feat.head().

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('bank_note_data.csv')

Exercise

4. Train and test sets

Make X, the scaled features df_feat, and y, the Class column of df. Split them into X_train, X_test, y_train and y_test with test_size=0.3 and random_state=101.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('bank_note_data.csv')
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(df.drop('Class', axis=1))
df_feat = pd.DataFrame(scaler.transform(df.drop('Class', axis=1)), columns=df.columns[:-1])

Exercise

5. A deeper network

Create MLPClassifier(hidden_layer_sizes=(10, 20, 10), max_iter=1000, random_state=101) called mlp: three hidden layers of 10, 20 and 10 neurons. Fit it on the training data, predict the test data as predictions, and print the confusion matrix and the classification report.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('bank_note_data.csv')
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(df.drop('Class', axis=1))
df_feat = pd.DataFrame(scaler.transform(df.drop('Class', axis=1)), columns=df.columns[:-1])
from sklearn.model_selection import train_test_split
X = df_feat
y = df['Class']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)
from sklearn.metrics import classification_report, confusion_matrix

A perfect score: every one of the 412 test notes is classified correctly. In Keras, the same network ends with one sigmoid neuron that gives the chance a note is fake:

model = tf.keras.Sequential([
    tf.keras.Input(shape=(4,)),
    tf.keras.layers.Dense(10, activation='relu'),
    tf.keras.layers.Dense(20, activation='relu'),
    tf.keras.layers.Dense(10, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid'),
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=50, batch_size=20)
predictions = (model.predict(X_test) > 0.5).astype(int)

Exercise

6. A reality check

Is a neural network needed here? Train RandomForestClassifier(n_estimators=100, random_state=101) called rfc on the same training data, predict the test data as rfc_pred, and print its confusion matrix and classification report.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('bank_note_data.csv')
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(df.drop('Class', axis=1))
df_feat = pd.DataFrame(scaler.transform(df.drop('Class', axis=1)), columns=df.columns[:-1])
from sklearn.model_selection import train_test_split
X = df_feat
y = df['Class']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)
from sklearn.metrics import classification_report, confusion_matrix

The forest does almost as well, with only 4 mistakes, and it trains faster with no scaling needed. That's a good habit to keep: deep learning shines on images, sound and text, where there are thousands of raw inputs. For a handful of tidy columns, try a simpler model first.

Check your understanding0 of 3 correct

Question 1

1.What does ReLU return for −3?

Question 2

2.What is an epoch?

Question 3

3.Why scale features before training a neural network?

Quiz score: 0 of 3

Exercises solved: 0 of 5

Tip: answer every quiz question correctly first.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.