python - Kfold 如何在 tensorflow 中与管道交叉验证?
问题描述
我在 TensorFlow 中创建了一个管道,例如:
from glob import glob
import random
IMG_SIZE=224
def make_dataset(path,batch_size):
def parse_image(filename):
image= tf.io.read_file(filename)
image=tf.image.decode_jpeg(image,channels=3)
image=tf.image.resize(image, [IMG_SIZE,IMG_SIZE])
image=tf.cast(image, tf.float32) / 255.0
return image
def configure_for_performance(ds):
ds=ds.shuffle(buffer_size=5000)
ds=ds.batch(batch_size)
ds=ds.repeat()
ds=ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
return ds
classes= os.listdir(path)
filenames=glob(path+'/*/*')
random.shuffle(filenames)
labels= [classes.index(name.split('/')[-2])for name in
filenames]
filenames_ds= tf.data.Dataset.from_tensor_slices(filenames)
images_ds= filenames_ds.map(parse_image,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
labels_ds= tf.data.Dataset.from_tensor_slices(labels)
ds= tf.data.Dataset.zip((images_ds,labels_ds))
ds= configure_for_performance(ds)
return ds
我想进行交叉验证,如何使用我的新数据集执行此操作?我想要类似的东西:
dataset=make_dataset(path,32)
kfold = KFold(n_splits=num_folds, shuffle=True)
fold_no = 1
for train, test in kfold.split(dataset):
model = Sequential()
...... # some Keras layers
model.complie("sth is here")
history = model.fit(train,
epochs=3)
scores = model.evaluate(test, verbose=0)
但是此代码不起作用,并且错误与如何拆分数据集以进行训练和测试有关。我该如何解决这个问题?