新建
模板
Fly
Time: 2017-4-14
众所周知,keras目前没有提供交叉验证的功能,我们要向使用交叉验证,就需要与sklearn结合。keras也提供了这样的包装接口。keras.wrappers.scikit_learn
通过这个包里面的KerasClassifier或者KerasRegressor就可以结合。闲话少叙,上代码。
#!/usr/bin/python
# encoding: utf-8
"""
@version: 1.0
@author: Fly Lu
@license: Apache Licence
@contact: luyfuyu@gmail.com
@site: https://www.flyuuu.cn
@software: PyCharm
@file: sklearn_keras.py
@time: 2017-04-09 9:23
@description: 描述sklearn使用keras
"""
from keras.wrappers.scikit_learn import KerasClassifier
from keras.models import Sequential
from keras.layers import Dense
from sklearn.cross_validation import StratifiedKFold, cross_val_score
import numpy as np
def create_model():
model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu'))
model.add(Dense(8, kernel_initializer='uniform', activation='relu'))
model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# 为了让每次的结果都相同
seed = 7
np.random.seed(seed)
# 加载数据
dataset = np.loadtxt('./data/pima-indians-diabetes.csv', delimiter=',')
X = dataset[:, 0:8]
Y = dataset[:, 8]
model = KerasClassifier(build_fn=create_model, epochs=150, batch_size=10)
kfold = StratifiedKFold(Y, n_folds=10, shuffle=True, random_state=seed)
results = cross_val_score(model, X, Y, cv=kfold)
print(np.average(results))
手机扫一扫
移动阅读更方便
你可能感兴趣的文章