In this practical we build an Artificial Neural Network that predicts whether a bank customer will leave the bank (churn). We prepare the data with pandas and scikit-learn, build the network with Keras, and evaluate it with a confusion matrix.
What You Will Learn
- How to encode categorical columns (Geography, Gender)
- Why feature scaling is required for neural networks
- How to build an ANN with Keras
SequentialandDenselayers - What optimizer, loss, batch size and epochs mean
- How to evaluate predictions with a confusion matrix
Prerequisites
ANN – Plan of Attack, Pandas and train/test split.
Where Is This Used?
Banks, telecom companies and subscription businesses use churn models to find customers who are likely to leave, so they can offer them something before they go.
Install
pip install tensorflow scikit-learn pandas numpy
The Dataset
The file bank.csv (also known as Churn_Modelling.csv) has 10,000 customers. The target column Exited is 1 if the customer left.
| Columns | Use |
|---|---|
| RowNumber, CustomerId, Surname | Identifiers – not useful for prediction, so we drop them |
| CreditScore, Age, Tenure, Balance, NumOfProducts, HasCrCard, IsActiveMember, EstimatedSalary | Numeric features |
| Geography (France, Spain, Germany), Gender | Categorical features – must be encoded |
| Exited | Target (0 = stayed, 1 = left) |
Step 1: Import Libraries and Load Data
import numpy as np
import pandas as pd
dataset = pd.read_csv('../datasets/bank.csv')
X = dataset.iloc[:, 3:13] # CreditScore ... EstimatedSalary
y = dataset.iloc[:, 13].values # Exited
print(X.shape)
X.head(3)
Explanation: iloc[:, 3:13] takes columns 3 to 12, which skips the three identifier columns. The target Exited is column 13.
(10000, 10) CreditScore Geography Gender Age Tenure Balance NumOfProducts HasCrCard IsActiveMember EstimatedSalary 0 619 France Female 42 2 0.00 1 1 1 101348.88 1 608 Spain Female 41 1 83807.86 1 0 1 112542.58 2 502 France Female 42 8 159660.80 3 1 0 113931.57
Step 2: Encode Categorical Data
Neural networks only work with numbers. Gender has two values, so 0/1 is enough. Geography has three values with no order, so we use one-hot encoding (one 0/1 column per country).
X['Gender'] = (X['Gender'] == 'Male').astype(int) # Female=0, Male=1
X = pd.get_dummies(X, columns=['Geography'], dtype=int) # 3 new columns
print(X.columns.tolist())
X = X.values
Explanation: pd.get_dummies replaces Geography with Geography_France, Geography_Germany and Geography_Spain. We now have 12 input features.
['CreditScore', 'Gender', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard', 'IsActiveMember', 'EstimatedSalary', 'Geography_France', 'Geography_Germany', 'Geography_Spain']
LabelEncoder, OneHotEncoder, np.hstack and np.delete. That gives the same 12 features but is harder to read; get_dummies does it in one line.Step 3: Split and Scale
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
print(X_train.shape, X_test.shape)
Explanation: 80% of the rows are used for training and 20% for testing. Scaling is essential: Balance is in the tens of thousands while HasCrCard is 0 or 1, and large values would dominate the weights. We fit the scaler only on training data and reuse it for the test data.
(8000, 12) (2000, 12)
Step 4: Build the ANN
from keras.models import Sequential
from keras.layers import Input, Dense
classifier = Sequential([
Input(shape=(12,)),
Dense(6, kernel_initializer='uniform', activation='relu'), # hidden layer 1
Dense(6, kernel_initializer='uniform', activation='relu'), # hidden layer 2
Dense(1, kernel_initializer='uniform', activation='sigmoid') # output
])
classifier.summary()
| Parameter | Meaning |
|---|---|
Input(shape=(12,)) |
12 input features. (Newer Keras prefers this over input_dim=12, which gives a warning.) |
6 units |
Neurons in the hidden layer. A common rule of thumb: (inputs + outputs) / 2 ≈ 6 |
kernel_initializer |
How the starting weights are chosen |
relu |
Rectifier activation for hidden layers |
sigmoid |
Gives a probability between 0 and 1 for the output |
Model: "sequential" Layer (type) Output Shape Param # dense (Dense) (None, 6) 78 dense_1 (Dense) (None, 6) 42 dense_2 (Dense) (None, 1) 7 Total params: 127
Explanation: Layer 1 has 12 × 6 weights + 6 biases = 78 parameters; layer 2 has 6 × 6 + 6 = 42; the output has 6 + 1 = 7.
Step 5: Compile and Train
classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
classifier.fit(X_train, y_train, batch_size=10, epochs=100)
| Setting | Why |
|---|---|
adam |
An optimizer that adapts the learning rate for each weight; a good default |
binary_crossentropy |
The right loss for a 0/1 target (use categorical_crossentropy for more than two classes) |
batch_size=10 |
Weights are updated after every 10 rows |
epochs=100 |
The whole training set is passed through 100 times |
Epoch 1/100 800/800 ━━━━━━━━━━━━━━━━━━━━ 5s 3ms/step - accuracy: 0.7890 - loss: 0.5594 Epoch 2/100 800/800 ━━━━━━━━━━━━━━━━━━━━ 2s 3ms/step - accuracy: 0.8005 - loss: 0.4292 ... Epoch 100/100 800/800 ━━━━━━━━━━━━━━━━━━━━ 2s 3ms/step - accuracy: 0.84 - loss: 0.39
Explanation: 800 steps per epoch = 8000 rows ÷ batch size 10. Accuracy rises from about 79% to about 84%.
Step 6: Predict and Evaluate
from sklearn.metrics import confusion_matrix
y_prob = classifier.predict(X_test)
y_pred = (y_prob > 0.5) # probability → True/False
cm = confusion_matrix(y_test, y_pred)
print(cm)
loss, acc = classifier.evaluate(X_test, y_test, verbose=0)
print('Test loss:', round(loss, 3))
print('Test accuracy:', round(acc, 3))
Explanation: The network outputs a probability of leaving. Anything above the threshold is treated as “will leave”. The confusion matrix shows correct and wrong predictions for each class.
[[1565 30] [ 290 115]] Test loss: 0.393 Test accuracy: 0.842
keras.utils.set_random_seed(0) at the top for repeatable results.Reading the matrix: 1565 customers who stayed were predicted correctly and 115 who left were caught, but 290 leavers were missed. Lowering the threshold catches more leavers at the cost of more false alarms – see Precision and Recall.
Complete Code
import numpy as np, pandas as pd, keras
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
from keras.models import Sequential
from keras.layers import Input, Dense
keras.utils.set_random_seed(0)
dataset = pd.read_csv('../datasets/bank.csv')
X = dataset.iloc[:, 3:13].copy()
y = dataset.iloc[:, 13].values
X['Gender'] = (X['Gender'] == 'Male').astype(int)
X = pd.get_dummies(X, columns=['Geography'], dtype=int).values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
sc = StandardScaler()
X_train, X_test = sc.fit_transform(X_train), sc.transform(X_test)
model = Sequential([Input(shape=(12,)),
Dense(6, activation='relu'),
Dense(6, activation='relu'),
Dense(1, activation='sigmoid')])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=10, epochs=100, verbose=0)
y_pred = model.predict(X_test) > 0.5
print(confusion_matrix(y_test, y_pred))
print('Accuracy:', model.evaluate(X_test, y_test, verbose=0)[1])
Common Errors
| Problem | Cause and fix |
|---|---|
ValueError: could not convert string to float |
A text column (Geography or Gender) was not encoded. Run Step 2 before training. |
UserWarning about input_dim |
Use an Input(shape=...) layer first, as shown. |
| Accuracy stuck at about 0.80 | The model is predicting “stayed” for everyone. Check that you scaled the data and used sigmoid + binary_crossentropy. |
FileNotFoundError |
Fix the path to bank.csv. |
Series
Deep Learning series: Introduction to Deep Learning · AI vs ML vs DL · Introduction to ANN · ANN – Plan of Attack · ANN Practical · Introduction to CNN · CNN Steps · CNN Practically · Introduction to RNN · RNN Steps · RNN Practically
Interview Questions
Q: Why must we scale data for an ANN?
Gradient descent converges much faster and more reliably when all features are on a similar scale.
Q: Why sigmoid in the output layer?
The target is binary, and sigmoid gives a probability between 0 and 1.
Q: What would you change for 3 output classes?
Use 3 output units with softmax and categorical_crossentropy (or sparse_categorical_crossentropy).
Practice Exercises
- Add a third hidden layer and compare the test accuracy.
- Try thresholds 0.3, 0.5 and 0.6 and note how the confusion matrix changes.
- Predict for one customer: France, 600 credit score, Male, 40 years, tenure 3, balance 60000, 2 products, has card, active, salary 50000. (Remember to encode and scale the same way.)
Summary
We encoded the categories, scaled the features, built a 12-6-6-1 ANN with Keras, trained it with Adam and binary cross-entropy, and reached about 84% accuracy on unseen customers.
Next: Introduction to CNN
Machine Learning Tutorials, Courses and Certifications