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

时间:2018-10-02 19:11:04

标签: tensorflow scikit-learn neural-network keras roc

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

  1. function' object has not attribute 'keys'中,错误为y_pred = classifier.predict(X_test)
  2. name 'classifier' is not defined中,错误为plt.plot(history.history['acc'])
  3. 'History' object is not subscriptable中,错误为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()

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

<p>

应该添加什么功能?

1 个答案:

答案 0 :(得分:0)

在以下几行中将history更改为classifier(实际上History是在fit对象上调用的Model方法的返回值),如下所示:

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

不要将fit方法的返回值与模型混淆。顾名思义,History对象仅包含训练的历史记录。但是,您的模型是classifierit is the one that has methods,例如fit()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()