首页 > 解决方案 > LSTM - 进行预测时输入中的 Matmul 错误

问题描述

我正在尝试使用 Keras 训练单步 LSTM 模型。但是,当我调用 predict 函数时,出现以下错误:

InvalidArgumentError: cannot compute MatMul as input #0 was expected to be a float tensor but is a double tensor [Op:MatMul] name: lstm_5/MatMul/

我的输入形状是 (250, 7, 3)

下面是模型的配置和总结:

single_step_model = tf.keras.models.Sequential()
single_step_model.add(tf.keras.layers.LSTM(7,
                                           input_shape=x_train_single.shape[-2:]))
single_step_model.add(tf.keras.layers.Dense(1))

single_step_model.compile(loss='mae', optimizer=tf.train.RMSPropOptimizer(learning_rate=0.001), metrics=['accuracy'])

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
lstm_5 (LSTM)                (None, 7)                 308       
_________________________________________________________________
dense_5 (Dense)              (None, 1)                 8         
=================================================================
Total params: 316
Trainable params: 316
Non-trainable params: 0
_________________________________________________________________

请帮助我

标签: python-3.xtensorflowkeraslstmrecurrent-neural-network

解决方案


为了社区的利益,即使它出现在评论部分中,也要在此(答案)部分中提及解决方案。

问题是input. 默认情况下,tensorflow keras模型需要float32,但您传递的是double.

您可以更改模型的 dtype,如下面的代码所示:

def make_model():
    net = tf.keras.Sequential()
    net.add(tf.keras.layers.Dense(4, activation='relu', dtype='float32'))
    net.add(tf.keras.layers.Dense(4, activation='relu'))
    net.add(tf.keras.layers.Dense(1))
    return net

或将输入更改为float32。要更改inputX = X.astype('float32')


推荐阅读