Normalize the Validation Set for a Neural Network in Keras

Viewed 3863

So, I understand that normalization is important to train a neural network.

I also understand that I have to normalize validation- and test-set with the parameters from the training set (see e.g. this discussion: https://stats.stackexchange.com/questions/77350/perform-feature-normalization-before-or-within-model-validation)

My question is: How do I do this in Keras?

What I'm currently doing is:

import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import EarlyStopping

def Normalize(data):
    mean_data = np.mean(data)
    std_data = np.std(data)
    norm_data = (data-mean_data)/std_data
    return norm_data

input_data, targets = np.loadtxt(fname='data', delimiter=';')
norm_input = Normalize(input_data)

model = Sequential()
model.add(Dense(25, input_dim=20, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

early_stopping = EarlyStopping(monitor='val_acc', patience=50) 
model.fit(norm_input, targets, validation_split=0.2, batch_size=15, callbacks=[early_stopping], verbose=1)

But here, I first normalize the data w.r.t. the whole data set and then split up the validation set, which is wrong according to the above mentioned discussion.

It wouldn't be a big deal to save the mean and standard deviation from the training set(training_mean and training_std), but how can I apply the normalization with the training_mean and training_std on the validation set separately?

2 Answers

Following code makes exactly what you want:

import numpy as np
def normalize(x_train, x_test):
    mu = np.mean(x_train, axis=0)
    std = np.std(x_train, axis=0)
    x_train_normalized = (x_train - mu) / std
    x_test_normalized = (x_test - mu) / std
    return x_train_normalized, x_test_normalized

Then you can use it with keras like this:

from keras.datasets import boston_housing
(x_train, y_train), (x_test, y_test) = boston_housing.load_data()
x_train, x_test = normalize(x_train, x_test)

The Wilmar's answer is not correct.

Related