【问题标题】:Loading val_acc and val_loss from a saved .h5 cnn saved model从保存的 .h5 cnn 保存模型中加载 val_acc 和 val_loss
【发布时间】:2020-02-22 03:40:36
【问题描述】:

我使用 Keras 构建了一个 CNN 分类器,绘制了 3 个 epoch 的验证准确率和验证损失的历史,然后使用分类器.save("name.h5:) 保存了模型。

我稍后成功地使用 .load() 命令加载了分类器。但是,我无法重新加载验证准确性和验证损失。有什么办法吗?

我尝试了评估()函数但没有用。

from keras.models import Sequential
from keras.layers import Conv2D,Activation,MaxPooling2D,Dense,Flatten,Dropout
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from IPython.display import display
import matplotlib.pyplot as plt
from PIL import Image
from keras.models import load_model
from sklearn.metrics import classification_report, confusion_matrix

classifier = Sequential()
classifier.add(Conv2D(32,(3,3),input_shape=(64,64,3)))
classifier.add(Activation('relu'))
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Conv2D(32,(3,3)))
classifier.add(Activation('relu'))
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Conv2D(64,(3,3)))
classifier.add(Activation('relu'))
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Flatten())
classifier.add(Dense(64))
classifier.add(Activation('relu'))
classifier.add(Dropout(0.5))
classifier.add(Dense(2))
classifier.add(Activation('softmax'))
classifier.summary()
classifier.compile(optimizer ='rmsprop',
                   loss ='categorical_crossentropy',
                   metrics =['accuracy'])
train_datagen = ImageDataGenerator(rescale =1./255,
                                   shear_range =0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip =True)
test_datagen = ImageDataGenerator(rescale = 1./255)

batchsize=60
training_set = train_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/dogs-vs-cats/train/',
                                                target_size=(64,64),
                                                batch_size= batchsize,
                                                class_mode='categorical')

test_set = test_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/dogs-vs-cats/test/',
                                           target_size = (64,64),
                                           batch_size = batchsize,
                       shuffle=False,
                                           class_mode ='categorical')
history=classifier.fit_generator(training_set,
                        steps_per_epoch =9000 // batchsize,
                        epochs = 3,
                        validation_data =test_set,
                        validation_steps = 4500 // batchsize)

classifier.save('my_model3.h5')
Y_pred = classifier.predict_generator(test_set, steps=4500 // batchsize)
y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
print(confusion_matrix(test_set.classes, y_pred))
print('Classification Report')
target_names = test_set.classes
class_labels = list(test_set.class_indices.keys()) 
target_names = ['cats', 'dogs'] 
report = classification_report(test_set.classes, y_pred, target_names=class_labels)
print(report) 

# summarize history for accuracy
#plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

【问题讨论】:

    标签: python python-3.x tensorflow keras


    【解决方案1】:

    恐怕不是,History 是一个对象,它作为 fit() 函数的乘积返回。 模型本身不保留此信息,因此不会保存。

    唯一可以取回历史记录的方法是专门保存它。

    否则,如果您在第一次训练模型时设置了随机种子,您也可能会得到相同的结果(历史记录)。然后你可以用相同的种子重复这个过程并得到相同的结果。

    【讨论】:

    • 既然我保存了模型,我可以加载它并为同一个火车调用 fit_generator() 并验证数据并获得相同的结果吗?
    • 不是真的,这样做会继续改变你上次训练的权重。
    • @MaysaSarsour 所以你会接受答案,还是我应该提供更多信息?
    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多