写在前面:
? ? ? ? 在此声明:博客的本意是供自己存档实验报告,同时便于同学之间相互交流遇到的问题。欢迎大家评论和私信自己遇到的问题和解决方案,让我们共同进步。
pets_cnn.h5模型文件及pets数据集下载地址(无需积分,直接下载,如遇404说明文件在审核中,csdn资源审核时间为2-10个工作日): https://download.csdn.net/download/qq_43554335/33138606
下面都是一些版本问题产生的Warning(可修改可不改):
UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.warnings.warn('`Model.fit_generator` is deprecated and '
history=model.fit(train_generator, epochs=6, steps_per_epoch=steps_per_epoch, verbose=2, validation_data=test_generator, validation_steps=validation_steps)
UserWarning: `Model.evaluate_generator` is deprecated and will be removed in a future version. Please use `Model.evaluate`, which supports generators. warnings.warn('`Model.evaluate_generator` is deprecated and '
score = model.evaluate(test_generator, steps=validation_steps)
E tensorflow/core/platform/windows/subprocess.cc:287] Call to CreateProcess failed. Error code: 2
需修正的代码:
?需要用到的包:
from keras.models import Sequential,load_model
from keras.layers import Dense, Flatten, Dropout
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import matplotlib.pyplot as plt
完整代码(来源实验指导书,非本人所写,仅供存档)
datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)
train_generator = datagen.flow_from_directory('../sources/pets', target_size=(64, 64), batch_size=128, subset='training', class_mode='binary', seed=123)
test_generator = datagen.flow_from_directory('../sources/pets', target_size=(64, 64), batch_size=128, subset='validation', class_mode='binary', seed=123)
labels = {y:x for x,y in train_generator.class_indices.items()}
print(labels)
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(3, 3), padding='same', input_shape=(64, 64, 3), activation='relu'))
model.add(Conv2D(filters=32, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.summary()
model.compile(loss='binary_crossentropy', optimizer='RMSprop', metrics=['accuracy'])
steps_per_epoch = 20000 // 128 + 1
validation_steps = 5000 // 128 + 1
history=model.fit_generator(train_generator, epochs=6, steps_per_epoch=steps_per_epoch, verbose=2, validation_data=test_generator, validation_steps=validation_steps)
score = model.evaluate(test_generator, steps=validation_steps)
print("Test loss: ",score[0])
print("Test accuracy: ",score[1])
plt.figure()
plt.plot(history.history['accuracy'], color='b', linestyle='-', label='training')
plt.plot(history.history['val_accuracy'], color='r', linestyle='--', label='validation')
plt.title("Model accuracy")
plt.ylabel("accuracy")
plt.xlabel("epoch")
plt.legend(loc="upper left")
plt.show()
plt.figure()
plt.plot(history.history['loss'], color='b', linestyle='-', label='training')
plt.plot(history.history['val_loss'], color='r', linestyle='--', label='validation')
plt.title("Model loss")
plt.ylabel("loss")
plt.xlabel("epoch")
plt.legend(loc="upper right")
plt.show()
model.save("../models/pets_cnn.h5")
model = load_model("../models/pets_cnn.h5")
x_test, y_test = test_generator.next()
y_pred = model.predict(x_test, batch_size=128, verbose = 0)
y_pred = np.argmax(y_pred,axis=1)
misclassified = np.where(y_pred!=y_test)[0]
print(misclassified)
plt.figure()
for i in range(min(4,len(misclassified))):
plt.subplot(221 + i)
plt.title('predicted: ' + labels[y_pred[misclassified[i]]] + ', true: ' + labels[y_test[misclassified[i]]])
plt.imshow(x_test[misclassified[i]])
plt.axis('off')
plt.show()
?训练过程及精度、损失值、错误序号:
?绘制4个预测错误的样本:
?
?
|