keras 绘制损失和 MSE

数据挖掘 Python 深度学习 喀拉斯 回归 matplotlib
2022-03-03 17:48:45

有人可以给我一个关于如何合并 MSE 和损失图的提示吗?我一直在关注一些机器学习掌握的帖子来绘制这个,但应用程序是分类,我正在尝试回归。另外,我的脚本的不同之处在于我通过调用函数来定义模型,所以我很好奇我的脚本是否可以在没有def wider_model()定义模型的函数的情况下重新编写。

除了底部注释掉的plt情节之外,下面的这个脚本有效。在 machinelearningmastery 帖子中,有人确实问过这个问题如何进行回归,据说如果您打印print(history.history.keys())两个值,则返回dict_keys([‘mean_absolute_error’, ‘loss’])...

任何提示都有帮助,这里没有很多智慧......谢谢

import numpy
import pandas
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import matplotlib.pyplot as plt
import math



# load dataset
dataset = pandas.read_csv("prepdSPdata.csv", index_col='Date', parse_dates=True)

# shuffle dataset
dataset = dataset.sample(frac=1.0)


# split into input (X) and output (Y) variables
X = numpy.array(dataset.drop(['Demand'],1))
Y = numpy.array(dataset['Demand'])

print(dataset.shape)
print(dataset.dtypes)
print(dataset.columns)


def wider_model():
    # create model
    model = Sequential()
    model.add(Dense(20, input_dim=11, kernel_initializer='normal', activation='relu'))
    model.add(Dense(10, kernel_initializer='normal', activation='relu'))
    model.add(Dense(1, kernel_initializer='normal'))
    # Compile model
    model.compile(loss='mean_squared_error', optimizer='adam')
    return model


# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
estimators = []
estimators.append(('standardize', StandardScaler()))
estimators.append(('mlp', KerasRegressor(build_fn=wider_model, epochs=1, batch_size=5, verbose=0)))
pipeline = Pipeline(estimators)
kfold = KFold(n_splits=10, random_state=seed)
results = cross_val_score(pipeline, X, Y, cv=kfold)
print("Wider: %.2f (%.2f) MSE" % (results.mean(), results.std()))
print("RMSE", math.sqrt(results.std()))



# list all data in history
#print(wider_model.wider_model.keys())

# summarize history for MSE
#plt.plot(history.history['acc'])
#plt.plot(history.history['val_acc'])
#plt.title('model MSE')
#plt.ylabel('MSE')
#plt.xlabel('epoch')
#plt.legend(['train', '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()
2个回答

cross_val_score不返回训练的历史。您可以fit改用:

history = model.fit( ...

请参阅此示例

正如您所提到的,该history对象包含每个时期的训练结果。

这是相关的位:

history = model.fit(X, X, epochs=500, batch_size=len(X), verbose=2)
pyplot.plot(history.history['mean_squared_error'])
pyplot.plot(history.history['mean_absolute_error'])
pyplot.plot(history.history['mean_absolute_percentage_error'])
pyplot.plot(history.history['cosine_proximity'])
pyplot.show()

我实际上正在研究您昨天引用的同一个示例。我认为它很难理解,因为它引入了许多函数和概念:估计器StandardScalerKerasRegressorPipelineKFoldcross_val_score

但是,我确实喜欢创建和测试模型的方法,并且交叉验证会产生更强大的模型。

你只训练你的模型 1 个 epoch,所以你只给它一个数据点来工作。如果你想绘制一条损失线或准确度线,你需要训练更多的时期。