from keras.models import Sequential
from keras.layers import Dense
import numpy as np
from sklearn.model_selection import StratifiedKFold
seed = 7# 设定随机数种子
np.random.seed(seed)
dataset = np.loadtxt('D:\example\Keras\pima-indians-diabetes.csv', delimiter=',')# 导入数据
# 分割输入x和输出Y
x = dataset[:, 0 : 8]#取二维数组中第1(m)维到7维(第n-1维)的所有数据,相当于取第1(m)列到第七(n-1)列的所有数据
yTrain = dataset[:, 8]#取二维数组中第9维的所有数据,相当于取第9列的所有数据
kfold = StratifiedKFold(n_splits=10, random_state=seed, shuffle=True)
cvscores = []
for train, validation in kfold.split(x, yTrain):
model = Sequential() # 创建模型
model.add(Dense(12, input_dim=8, activation='relu'))#输入层8个,隐藏层12个,激活函数relu
model.add(Dense(8, activation='relu'))#隐藏层8个,激活函数relu
model.add(Dense(1, activation='sigmoid'))#输出层1个,激活函数sigmoid
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # 编译模型
model.fit(x=x[train],y=yTrain[train], epochs=15, batch_size=10, verbose=0) # 训练模型
scores = model.evaluate(x=x[validation], y=yTrain[validation], verbose=0) # 评估模型
print('%s: %.2f%%' % (model.metrics_names[1], scores[1] * 100)) # 输出评估结果
cvscores.append(scores[1] * 100)
# 输出均值和标准差
print('%.2f%% (+/- %.2f%%)' % (np.mean(cvscores), np.std(cvscores)))
'''
kfold 交叉验证,
n_splits=>分成10份
random_state 设置每次生成的随机数相同
shuffle 用户自定义数据集划分,True按顺序执行,False乱序
'''
来源:CSDN
作者:gamblerofdestinyR14
链接:https://blog.csdn.net/gamblerofdestinyR14/article/details/104106167