Keras预测准确率与fit结果不匹配

我正在尝试使用TensorFlow 2.0 + Keras构建一个二分类模型。每个目标有5个特征,我希望这个模型能够预测输入数据是否属于a类。

然而,fit()predict()之间的准确率完全不同。最奇怪的是,我将训练数据提供给模型进行预测,但模型并未返回1。

构建训练数据:(a的特征标记为1,其他标记为0

num_train = 50data = {  # the content is fake, just for understanding the format  'a': [(1, 2, 3, 4, 5), (2, 3, 4, 5, 6), ...],  'b': [(10, 20, 30, 40, 50), (20, 30, 40, 50, 60), ...],  ...}train_x = []train_y = []for name, features in data.items():  for f in features[:num_train]:    train_x.append(f)    train_y.append(1 if name == 'a' else 0)train_x = np.array(train_x)train_y = np.array(train_y)

以下是模型代码:

model = Sequential()model.add(Dense(1, activation='sigmoid', input_dim=5))model.compile(optimizer='sgd', loss='mse', metrics=['accuracy'])

调用model.fit()

model.fit(x=train_x, y=train_y, validation_split=0.2, batch_size=10, epochs=50)

第50个epoch之后:

Epoch 50/50653/653 [==============================] - 0s 80us/sample - loss: 0.0745 - accuracy: 0.9234 - val_loss: 0.0192 - val_accuracy: 1.0000

最后,我使用每个类别的前3个样本进行预测:

for name, features in data.items():  test_x = features[:3]  print(name, np.around(model.predict(test_x), decimals=2))

输出结果:

a [[0.14] [0.14] [0.14]]b [[0.14] [0.13] [0.13]]c [[0.14] [0.14] [0.13]]...

完整的数据和源代码已上传到Google Drive,请查看链接


回答:

在检查了您的源代码后,发现了一些实现问题:

  1. 训练数据和验证数据由Keras随机分配

在您的训练过程中,20%的数据被抽样作为验证数据,但您无法确定抽样的数据是否平衡(即训练和验证数据中的类别比例相同)。在您的案例中,由于数据不平衡,很可能是训练数据主要来自类别0,因此您的模型没有学到任何有用的东西(因此所有样本的输出都是相同的0.13)。

更好的方法是在训练前以分层方式拆分数据:

from sklearn.model_selection import train_test_splitnum_train = 50train_x = []train_y = []for name, features in data.items():    for f in features[:num_train]:        train_x.append(f)        train_y.append(1 if name == 'a' else 0)train_x = np.array(train_x)train_y = np.array(train_y)# Split your data, and stratify according to the target label `train_y`# Set a random_state, so that the train-test split is reproduciblex_train, x_test, y_train, y_test = train_test_split(train_x, train_y, test_size=0.2, stratify=train_y, random_state=123)

在训练时,您应指定validation_data而不是使用validation_split

model = Sequential()model.add(Dense(1, activation='sigmoid', input_dim=5))model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])model.fit(x=x_train, y=y_train,           validation_data=(x_test, y_test), # Use this instead          class_weight={0:1,1:17},  # See explanation in 2. Imbalanced class          batch_size=10, epochs=500)
  1. 高度不平衡的类别 – 类别1的频率是类别0的17倍

您的类别1 a 的数量是类别0的17倍(由剩余的类别组成)。如果您不调整类别权重,模型会将所有样本视为平等,简单地将所有样本分类为类别0会让模型的准确率达到94.4%(剩余的5.6%全部来自类别1,并且都被这个简单的模型错误分类)。

为了解决类别不平衡问题,一种方法是为少数类别设置更高的损失。在这个例子中,我将类别1的权重设置为类别0的17倍:

class_weight={0:1,1:17}

这样做,您是在告诉模型,每个错误预测的类别1样本会带来比错误分类类别0样本高17倍的惩罚。因此,模型被迫更加关注类别1,尽管它是少数类别。

  1. 未对原始预测结果应用阈值处理

训练后(请注意,我将epochs增加到500,模型在大约200个epoch后收敛),对您之前获得的测试集进行预测:

preds = model.predict(x_test)

您会得到类似这样的结果:

[[0.33624142] [0.58196825] [0.5549609 ] [0.38138568] [0.45235538] [0.32419187] [0.37660158] [0.37013668] [0.5794893 ] [0.5611163 ] ......]

这是神经网络的原始输出,范围在[0,1]之间,因为最后一层激活函数是sigmoid,将输出压缩到这个范围。为了将输出转换为您需要的类别预测(类别0或1),需要应用一个阈值。通常,这个阈值设置为0.5,即输出大于0.5的预测表示样本可能属于类别1,输出小于0.5的预测则表示属于类别0。

因此,您需要使用阈值处理输出:

threshold_output = np.where(preds > 0.5, 1, 0)

您将得到实际的类别预测:

[[0] [1] [1] [0] [0] [0] [0] [0] [1] [1] ...]

获取训练和测试准确率

现在,为了检查训练和测试准确率,您可以直接使用sklearn.metric,这省去了手动计算的麻烦:

from sklearn.metrics import accuracy_scoretrain_preds = np.where(model.predict(x_train) > 0.5, 1, 0)test_preds = np.where(model.predict(x_test) > 0.5, 1, 0)train_accuracy = accuracy_score(y_train, train_preds)test_accuracy = accuracy_score(y_test, test_preds)print(f'训练准确率 : {train_accuracy:.4f}')print(f'测试准确率  : {test_accuracy:.4f}')

这将为您提供:

训练准确率 : 0.7443测试准确率  : 0.7073

希望这能回答您的问题!

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中创建了一个多类分类项目。该项目可以对…

发表回复

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