Keras深度学习库包括三个独立的函数,可用于训练您自己的模型:
.fit
.fit_generator
.train_on_batch
.fit
训练与验证分离
network.fit(train_images, train_labels, epochs=5, batch_size=128)
test_loss, test_acc = network.evaluate(test_images, test_labels)
训练与验证并行
history = model.fit(partial_x_train, partial_y_train, epochs=4, batch_size=512, validation_data=(x_val, y_val))
predict
predict1=model.predict(x_val)
.fit_generator
history = model.fit_generator(
train_generator,
steps_per_epoch=100,
epochs=30,
validation_data=validation_generator,
validation_steps=50)
flow_from_directory
图片被放在以分类名命名的一个个子文件夹里
test_datagen = keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
validation_generator = test_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=20,
class_mode="binary")
flow_from_dataframe
当图片路径及分类名存在一个表格里。
train_datagen = keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_generator =train_datagen.flow_from_dataframe(dataframe =df,
#directory ="./ train /",
x_col ="PictureName",
y_col ="TagName",
subset ="training",
batch_size = 8,
seed = 42,
shuffle = True,
classes=categorys, #传了但没效果
class_mode ="categorical",#categorical sparse raw sparse
target_size =(width, height))
会自动按分类名排序记为分类序号。 传classes=["aa","cc","bb"] ,可以自己定义分类序号,但好像没用。
更新内容请参考:
https://blog.csdn.net/weixin_43346901/article/details/100095019
自定义generator
trainGen = csv_image_generator(df, BS,0,trainCount,
mode="train", aug=None)
testGen = csv_image_generator(df, BS,trainCount,len(df),
mode="train", aug=None)
.train_on_batch
model.train_on_batch(batchX, batchY)
异常处理
Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (500, 400, 3)
原: predict1=model.predict([x1])
改为:predict1=model.predict(np.array([x1]))