首页 > 解决方案 > 尝试使用 Keras 模型中的新数据进行预测时出错

问题描述

我得到了一个由 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)

在此处输入图像描述

标签: pythontensorflowmachine-learningkerasdeep-learning

解决方案


也许尝试为您的数据样本添加一个维度,然后将您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)

推荐阅读