matplotlib 如何从保存的模型打印我的训练和测试(准确性、验证准确性)?

5f0d552i  于 2023-04-06  发布在  其他
关注(0)|答案(1)|浏览(118)

我是深度学习的新手,我想得到我的模型的训练(accuracy,瓦尔_accuracy)和测试(accuracy,val_accuracy),我还想知道如何使用混淆矩阵打印精度,召回率和f1得分值。
这是我的模型的一些细节

vgg_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
for layer in vgg_model.layers:
       layer.trainable = False
my_vgg_model = Sequential()
my_vgg_model.add(vgg_model)
my_vgg_model.add(Flatten())
my_vgg_model.add(Dense(256, activation='relu'))
my_vgg_model.add(Dense(128, activation='relu'))
my_vgg_model.add(Dense(2, activation='softmax'))
my_vgg_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
hist = my_vgg_model.fit(x_train, y_train, 
                    batch_size=32, 
                    epochs=1, 
                    verbose=1, 
                    validation_data=(x_test, y_test),
                    callbacks=[cp_callback])

我没有尝试过任何东西,因为我无法分别获得这些训练和测试的准确性:(

yxyvkwin

yxyvkwin1#

训练后,训练集和测试集的损失和准确率存储在hist变量中。您可以通过调用hist.history来访问它们作为字典。
对于其他指标,您可以使用sklearn.metrics,如下所示:

from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix

# model
vgg_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
for layer in vgg_model.layers:
       layer.trainable = False
my_vgg_model = Sequential()
my_vgg_model.add(vgg_model)
my_vgg_model.add(Flatten())
my_vgg_model.add(Dense(256, activation='relu'))
my_vgg_model.add(Dense(128, activation='relu'))
my_vgg_model.add(Dense(2, activation='softmax'))
my_vgg_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# training
hist = my_vgg_model.fit(x_train, y_train, 
                    batch_size=32, 
                    epochs=1, 
                    verbose=1, 
                    validation_data=(x_test, y_test),
                    callbacks=[cp_callback])

# accuracy
accuracy_train = hist.history['accuracy']
accuracy_test = hist.history['val_accuracy']

# predict with model to get other metrics
y_train_pred = my_vgg_model.predict(x_train)
y_test_pred = my_vgg_model.predict(x_test)

# other metrics
f1_train = f1_score(y_train, y_train_pred)
precision_train = precision_score(y_train, y_train_pred)
recall_train = recall_score(y_train, y_train_pred)
confusion_train = confusion_matrix(y_train, y_train_pred)

f1_test = f1_score(y_test, y_test_pred)
precision_test = precision_score(y_test, y_test_pred)
recall_test = recall_score(y_test, y_test_pred)
confusion_test = confusion_matrix(y_test, y_test_pred)

相关问题