gpt4 book ai didi

tensorflow - 如何在 Keras 中绘制 MLP 模型的训练损失和准确度曲线?

转载 作者:行者123 更新时间:2023-12-05 08:32:14 27 4
gpt4 key购买 nike

我正在使用 Keras 对神经网络建模,并尝试使用 accval_acc 的图表对其进行评估。我在以下代码行中有 3 个错误:

  1. print(history.keys()) 中,错误是 function' object has not attribute 'keys'
  2. y_pred = classifier.predict(X_test) 错误是 name 'classifier' is not defined
  3. plt.plot(history.history['acc'])中错误是'History' object is not subscriptable

我也在尝试绘制 ROC 曲线图,我该怎么做?

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import Dense
from sklearn import cross_validation
from matplotlib import pyplot
from keras.utils import plot_model

dataset = pd.read_csv('Data_BP.csv')
X = dataset.iloc[:, 0:11].values
y = dataset.iloc[:, -1].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size = 0.2, random_state = 0)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

def Model():
classifier = Sequential()
classifier.add(Dense(units = 12, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
classifier.add(Dense(units = 8, kernel_initializer = 'uniform', activation = 'relu'))
classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'mean_squared_error', metrics = ['mse', 'acc'])
return classifier

classifier = Model()
history = classifier.fit(X_train, y_train, validation_split=0.25, batch_size = 10, epochs = 5)

print('\n', history.history.keys())

y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)

from sklearn.metrics import recall_score, classification_report, auc, roc_curve
cm = confusion_matrix(y_test, y_pred)
print(cm)


plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()

应该增加什么功能?

最佳答案

history改成classifier(实际上History对象是fit方法的返回值像这样调用 Model 对象):

classifier = Model()
history = classifier.fit(...)

不要将 fit 方法的返回值与您的模型混淆。 History 对象,顾名思义,只包含训练历史。但是,您的模型是 classifierit is the one that has methodsfit(), predict(), evaluate(), compile()

另外,History 对象有一个名为 history 的属性,它是一个字典,包含训练期间的损失值和指标。因此,您需要改用 print(history.history.keys())

现在,如果您想在训练期间绘制损失曲线(即每个时期结束时的损失),您可以这样做:

loss_values = history.history['loss']
epochs = range(1, len(loss_values)+1)

plt.plot(epochs, loss_values, label='Training Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()

plt.show()

关于tensorflow - 如何在 Keras 中绘制 MLP 模型的训练损失和准确度曲线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52614922/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com