Python文集程序员ML/DL

K重交叉验证 和 网格搜索验证

2018-05-03  本文已影响385人  SpikeKing

本文介绍Keras一些常见的验证和调参技巧,快速地验证模型和调节超参。

小技巧:

验证与调参:

欢迎Follow我的GitHubhttps://github.com/SpikeKing

Keras

CSV数据文件加载

使用NumPy的 loadtxt() 方法加载CSV数据文件

dataset = np.loadtxt(raw_path, delimiter=',', skiprows=1)

Dense初始化警告

Dense初始化参数的警告:

UserWarning: Update your `Dense` call to the Keras 2 API
`Dense(units=12, activation="relu", kernel_initializer="uniform")`
output = Dense(units=12, init='uniform', activation='relu')(main_input)

将init参数替换为kernel_initializer参数即可。


模型验证

fit()自动划分验证集:

通过设置参数validation_split的值(0~1)确定验证集的比例。

实现:

history = self.model.fit(
    self.data[0], self.data[1],
    epochs=self.config.num_epochs,
    verbose=1,
    batch_size=self.config.batch_size,
    validation_split=0.33,
)

fit()手动划分验证集:

train_test_split来源sklearn.model_selection:

通过参数validation_data添加验证数据,格式是 数据+标签 的元组。

实现:

X_train, X_test, y_train, y_test = \
    train_test_split(self.data[0], self.data[1], test_size=0.33, random_state=47)

history = self.model.fit(
    X_train, y_train,
    validation_data=(X_test, y_test),
    epochs=self.config.num_epochs,
    batch_size=self.config.batch_size,
    verbose=1,
)

交叉验证

K重交叉验证(K-fold Cross-Validation)是常见的模型评估统计。

人工模式

交叉验证函数 StratifiedKFold() 来源于sklearn.model_selection:

cvscores用于统计K重交叉验证的结果,计算均值和方差。

实现:

X = self.data[0]  # 数据
y = self.data[1]  # 标签
skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=47)
cvscores = []  # 交叉验证结果
for train_index, test_index in skf.split(X, y):  # 索引值
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

    history = self.model.fit(
        X_train, y_train,
        epochs=self.config.num_epochs,
        batch_size=self.config.batch_size,
        verbose=0,
    )
    self.loss.extend(history.history['loss'])
    self.acc.extend(history.history['acc'])

    # scores的第一维是loss,第二维是acc
    scores = self.model.evaluate(X_test, y_test)
    print('[INFO] %s: %.2f%%' % (self.model.metrics_names[1], scores[1] * 100))
    cvscores.append(scores[1] * 100)
cvscores = np.asarray(cvscores)
print('[INFO] %.2f%% (+/- %.2f%%)' % (np.mean(cvscores), np.std(cvscores)))

输出:

[INFO] acc: 79.22%
[INFO] acc: 70.13%
[INFO] acc: 75.32%
[INFO] acc: 75.32%
[INFO] acc: 80.52%
[INFO] acc: 81.82%
[INFO] acc: 75.32%
[INFO] acc: 85.71%
[INFO] acc: 75.00%
[INFO] acc: 76.32%
[INFO] 77.47% (+/- 4.18%)

Wrapper模式

通过 cross_val_score() 函数集成模型和交叉验证逻辑。

cross_val_score的输入是模型wrapper、数据X、标签Y、交叉验证cv;输出是每次验证的结果,再计算均值和方差。

实现:

X = self.data[0]  # 数据
Y = self.data[1]  # 标签

model_wrapper = KerasClassifier(
    build_fn=create_model,
    epochs=self.config.num_epochs,
    batch_size=self.config.batch_size,
    verbose=0
)  # keras wrapper

kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=47)
results = cross_val_score(model_wrapper, X, Y, cv=kfold)
print('[INFO] %.2f%% (+/- %.2f%%)' % (np.mean(results) * 100.0, np.std(results) * 100.0))

输出:

[INFO] 74.74% (+/- 4.37%)

网格搜索验证

网格搜索验证(Grid Search Cross-Validation)用于选择模型的最优超参值。

交叉验证函数 GridSearchCV() 来源于sklearn.model_selection:

实现:

X = self.data[0]  # 数据
Y = self.data[1]  # 标签

model_wrapper = KerasClassifier(
    build_fn=create_model,
    verbose=0
)  # 模型

optimizers = ['rmsprop', 'adam']  # 优化器
init_modes = ['glorot_uniform', 'normal', 'uniform']  # 初始化模式
epochs = np.array([50, 100, 150])  # Epoch数
batches = np.array([5, 10, 20])  # 批次数

# 网格字典optimizer和init_mode是模型的参数,epochs和batch_size是wrapper的参数
param_grid = dict(optimizer=optimizers, epochs=epochs, batch_size=batches, init_mode=init_modes)
grid = GridSearchCV(estimator=model_wrapper, param_grid=param_grid, n_jobs=4)
grid_result = grid.fit(X, Y)

print('[INFO] Best: %f using %s' % (grid_result.best_score_, grid_result.best_params_))

for params, mean_score, scores in grid_result.grid_scores_:
    print('[INFO] %f (%f) with %r' % (scores.mean(), scores.std(), params))

输出:

[INFO] Best: 0.721354 using {'epochs': 100, 'init_mode': 'uniform', 'optimizer': 'adam', 'batch_size': 20}
[INFO] 0.697917 (0.025976) with {'epochs': 50, 'init_mode': 'normal', 'optimizer': 'rmsprop', 'batch_size': 10}
[INFO] 0.700521 (0.006639) with {'epochs': 50, 'init_mode': 'normal', 'optimizer': 'adam', 'batch_size': 10}
[INFO] 0.697917 (0.018414) with {'epochs': 50, 'init_mode': 'uniform', 'optimizer': 'rmsprop', 'batch_size': 10}
[INFO] 0.701823 (0.030314) with {'epochs': 50, 'init_mode': 'uniform', 'optimizer': 'adam', 'batch_size': 10}
[INFO] 0.632813 (0.059069) with {'epochs': 100, 'init_mode': 'normal', 'optimizer': 'rmsprop', 'batch_size': 10}
...

欢迎Follow我的GitHubhttps://github.com/SpikeKing

By C. L. Wang

OK, that's all! Enjoy it!

上一篇下一篇

猜你喜欢

热点阅读