训练准确率随训练损失降低而下降

我编写了这个非常简单的代码

model = keras.models.Sequential()model.add(layers.Dense(13000, input_dim=X_train.shape[1], activation='relu', trainable=False))model.add(layers.Dense(1, input_dim=13000, activation='linear'))model.compile(loss="binary_crossentropy", optimizer='adam', metrics=["accuracy"])model.fit(X_train, y_train, batch_size=X_train.shape[0], epochs=1000000, verbose=1)

数据是MNIST,但只包含数字’0’和’1’。我遇到一个非常奇怪的问题,损失值如预期那样单调递减至零,但准确率不仅没有增加,反而也在下降。

这是一个样本输出

12665/12665 [==============================] - 0s 11us/step - loss: 0.0107 - accuracy: 0.2355Epoch 181/100000012665/12665 [==============================] - 0s 11us/step - loss: 0.0114 - accuracy: 0.2568Epoch 182/100000012665/12665 [==============================] - 0s 11us/step - loss: 0.0128 - accuracy: 0.2726Epoch 183/100000012665/12665 [==============================] - 0s 11us/step - loss: 0.0133 - accuracy: 0.2839Epoch 184/100000012665/12665 [==============================] - 0s 11us/step - loss: 0.0134 - accuracy: 0.2887Epoch 185/100000012665/12665 [==============================] - 0s 11us/step - loss: 0.0110 - accuracy: 0.2842Epoch 186/100000012665/12665 [==============================] - 0s 11us/step - loss: 0.0101 - accuracy: 0.2722Epoch 187/100000012665/12665 [==============================] - 0s 11us/step - loss: 0.0094 - accuracy: 0.2583

由于我们只有两个类别,最低可能的准确率基准应该是0.5,而且我们是在训练集上监测准确率,所以它应该会上升到100%,我预期会过拟合,并且根据损失函数来看,确实是过拟合了。

在最后一个周期,情况是这样的

12665/12665 [==============================] - 0s 11us/step - loss: 9.9710e-06 - accuracy: 0.0758

准确率只有7%,而如果随机猜测,最差的理论可能性是50%。这绝不是偶然的,这里肯定有什么问题。

有人能看出问题所在吗?

完整代码

from tensorflow import kerasimport numpy as npfrom matplotlib import pyplot as pltimport kerasfrom keras.callbacks import Callbackfrom keras import layersimport warningsclass EarlyStoppingByLossVal(Callback):    def __init__(self, monitor='val_loss', value=0.00001, verbose=0):        super(Callback, self).__init__()        self.monitor = monitor        self.value = value        self.verbose = verbose    def on_epoch_end(self, epoch, logs={}):        current = logs.get(self.monitor)        if current is None:            warnings.warn("Early stopping requires %s available!" % self.monitor, RuntimeWarning)        if current < self.value:            if self.verbose > 0:                print("Epoch %05d: early stopping THR" % epoch)            self.model.stop_training = Truedef load_mnist():    mnist = keras.datasets.mnist    (train_images, train_labels), (test_images, test_labels) = mnist.load_data()    train_images = np.reshape(train_images, (train_images.shape[0], train_images.shape[1] * train_images.shape[2]))    test_images = np.reshape(test_images, (test_images.shape[0], test_images.shape[1] * test_images.shape[2]))    train_labels = np.reshape(train_labels, (train_labels.shape[0],))    test_labels = np.reshape(test_labels, (test_labels.shape[0],))    train_images = train_images[(train_labels == 0) | (train_labels == 1)]    test_images = test_images[(test_labels == 0) | (test_labels == 1)]    train_labels = train_labels[(train_labels == 0) | (train_labels == 1)]    test_labels = test_labels[(test_labels == 0) | (test_labels == 1)]    train_images, test_images = train_images / 255, test_images / 255    return train_images, train_labels, test_images, test_labelsX_train, y_train, X_test, y_test = load_mnist()train_acc = []train_errors = []test_acc = []test_errors = []width_list = [13000]for width in width_list:    print(width)    model = keras.models.Sequential()    model.add(layers.Dense(width, input_dim=X_train.shape[1], activation='relu', trainable=False))    model.add(layers.Dense(1, input_dim=width, activation='linear'))    model.compile(loss="binary_crossentropy", optimizer='adam', metrics=["accuracy"])    callbacks = [EarlyStoppingByLossVal(monitor='loss', value=0.00001, verbose=1)]    model.fit(X_train, y_train, batch_size=X_train.shape[0], epochs=1000000, verbose=1, callbacks=callbacks)    train_errors.append(model.evaluate(X_train, y_train)[0])    test_errors.append(model.evaluate(X_test, y_test)[0])    train_acc.append(model.evaluate(X_train, y_train)[1])    test_acc.append(model.evaluate(X_test, y_test)[1])plt.plot(width_list, train_errors, marker='D')plt.xlabel("width")plt.ylabel("train loss")plt.show()plt.plot(width_list, test_errors, marker='D')plt.xlabel("width")plt.ylabel("test loss")plt.show()plt.plot(width_list, train_acc, marker='D')plt.xlabel("width")plt.ylabel("train acc")plt.show()plt.plot(width_list, test_acc, marker='D')plt.xlabel("width")plt.ylabel("test acc")plt.show()

回答:

在二分类问题中,最后一层的线性激活是无意义的;请将最后一层改为:

model.add(layers.Dense(1, input_dim=width, activation='sigmoid'))

线性激活函数适用于回归问题,而不是分类问题。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注