因此,我理解归一化对训练神经网络很重要。
我也理解我必须使用训练集中的参数对验证和测试集进行标准化(参见例如此讨论:https://stats.stackexchange.com/questions/77350/perform-feature-normalization-before-or-within-model-validation)
我的问题是:我如何在Keras做到这一点?
我目前正在做的是:
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)
但是在这里,我首先规范化数据w.r.t.整个数据集和然后分割验证集,根据上述讨论,这是错误的。
保存训练集的平均值和标准偏差(training_mean和training_std)并不是一件大事,但是如何分别使用training_mean和training_std对验证集进行规范化?
答案 0 :(得分:2)
以下代码完全符合您的要求:
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
然后你可以像这样使用keras:
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)
Wilmar的回答是不正确的。
答案 1 :(得分:0)
在使用sklearn.model_selection.train_test_split
拟合模型之前,您可以手动将数据拆分为训练和测试数据集。然后,分别规范化训练和测试数据,并使用model.fit
参数调用validation_data
。
代码示例
import numpy as np
from sklearn.model_selection import train_test_split
data = np.random.randint(0,100,200).reshape(20,10)
target = np.random.randint(0,1,20)
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2)
X_train = Normalize(X_train)
X_test = Normalize(X_test)
model.fit(X_train, y_train, validation_data=(X_test,y_test), batch_size=15, callbacks=[early_stopping], verbose=1)