【问题标题】:Error when trying to predict with new data in Keras model尝试使用 Keras 模型中的新数据进行预测时出错
【发布时间】:2021-10-17 19:48:06
【问题描述】:

我得到了一个由 432 批每批 24 个点组成的数据集。整个数据集的形状:(432, 24)

举个例子,这将是一批:

array([917,  15, 829,  87, 693,  71, 627, 359, 770, 303, 667, 367, 754,
       359, 532,  39, 683, 407, 333, 551, 516,  31, 675,  39])

形状为 (24,)

我正在为 Keras 模型提供此信息。没有问题。 当我尝试使用具有相同形状 (24,) 的新数据进行预测时:

array([176,  71, 152,  63, 200,  71, 120,  87, 128,  87, 216, 103, 248,
       126, 144, 150, 128, 206, 192, 206, 112, 277, 216, 269])

我的模特:

  model = keras.Sequential([
        keras.layers.Flatten(batch_input_shape=(None,24)),
        keras.layers.Dense(64, activation=tf.nn.relu),

        keras.layers.Dense(2, activation=tf.nn.sigmoid),
    ])

  model.compile(optimizer='adam',
                loss=tf.losses.categorical_crossentropy,
                metrics=['accuracy'])

引发的错误:

ValueError: Input 0 of layer dense_24 is incompatible with the layer: expected axis -1 of input shape to have value 24 but received input with shape (None, 1)

【问题讨论】:

  • 请在您实际调用模型以预测数据的位置显示您的代码。没有这个,任何人都无法提供帮助。
  • 注意,如果使用分类交叉熵损失,必须在模型的最后一层使用激活函数 tf.nn.softmax 而不是 tf.nn.sigmoid。或者,您可以在最后一层不放置激活函数,并在 model.compile() 中使用 loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True)。

标签: python tensorflow machine-learning keras deep-learning


【解决方案1】:

也许可以尝试为您的数据样本添加一个维度,然后将您的 new_data 输入您的模型以进行预测:

import numpy as np


new_data= np.array([176,  71, 152,  63, 200,  71, 120,  87, 128,  87, 216, 103, 248,
       126, 144, 150, 128, 206, 192, 206, 112, 277, 216, 269])

new_data= np.expand_dims(new_data, axis=0)

prediction = model.predict(new_data)
print(prediction)

【讨论】:

  • 谢谢它的工作!
猜你喜欢
  • 2018-07-24
  • 1970-01-01
  • 1970-01-01
  • 2018-05-30
  • 2021-05-18
  • 2014-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多