from sklearn.model_selection import KFold
from sklearn.model_selection import StratifiedKFold
seed = 7
np.random.seed(seed)
kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
cvscores = []
for train, test in kfold.split(x_train, y_train):
# create model
densenet=keras.applications.densenet.DenseNet121(include_top=False,
weights='imagenet', input_shape=(32,32,3))
for layer in densenet.layers:
layer.trainable=False
classes = 18
x = GlobalAveragePooling2D()(densenet.output)
x = Dropout(0.25)(x)
x = BatchNormalization(axis=-1)(x)
x = Dense(classes, name='fc6',activation='sigmoid')(x)
#create graph of your new model
model = Model(inputs = densenet.input, outputs = x)
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=
['accuracy'])
# Fit the model
model.fit(x_train[train], y_train[train], epochs=150, batch_size=10,
verbose=0)
# evaluate the model
scores = model.evaluate(x_test[test], y_test[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("%.2f%% (+/- %.2f%%)" % (numpy.mean(cvscores), numpy.std(cvscores)))
对于多标签分类,我必须在keras中进行k折交叉验证。上面的代码不起作用,因为y_train是矩阵而不是向量。在多标签分类的情况下,如何执行k折交叉验证?