首页 > 解决方案 > Keras LSTM 类型错误消息

问题描述

我正在尝试了解如何使用 keras 进行供应链预测,但我不断收到在其他地方找不到帮助的错误。我试过做类似的教程;太阳黑子预测教程、污染多元教程等,但我仍然不了解 input_shape 参数的工作原理或如何组织我的数据以使其被 keras 接受。

我的数据集是一个时间序列,描述了我们每个月销售的产品数量。我把那个单一的时间序列,107 个月,变成了一个 30 行,77 列的数据集。我从中创建了一个训练集和测试集。

但无论我做什么,即使只是创建一个没有某种错误的模型,我也无法过去。

Keras v#:1.2.0

C:\Users\Ryan.B>python -c "import keras; print(keras.version ) "

使用 TensorFlow 后端。

1.2.0

Python版本:3.5.4

这是我得到的代码和相应的错误。

model = Sequential()
model.add(LSTM(units=64, input_shape=(77, 1), output_dim=1))

C:\Python35\lib\site-packages\keras\backend\tensorflow_backend.py in concatenate(tensors, axis)
   1219         try:
-> 1220             return tf.concat_v2([to_dense(x) for x in tensors], axis)
   1221         except AttributeError:

AttributeError: module 'tensorflow' has no attribute 'concat_v2'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-21-94f09519ff46> in <module>()
      1 model = Sequential()
----> 2 model.add(LSTM(input_shape=(77, 1), output_dim = 1))
      3 #model.add(Dense(10, activation = 'relu'))
      4 #model.add(Dense(1, activation = 'softmax'))

C:\Python35\lib\site-packages\keras\models.py in add(self, layer)
    292                 else:
    293                     input_dtype = None
--> 294                 layer.create_input_layer(batch_input_shape, input_dtype)
    295 
    296             if len(layer.inbound_nodes) != 1:

C:\Python35\lib\site-packages\keras\engine\topology.py in create_input_layer(self, batch_input_shape, input_dtype, name)
    396         # and create the node connecting the current layer
    397         # to the input layer we just created.
--> 398         self(x)
    399 
    400     def add_weight(self, shape, initializer, name=None,

C:\Python35\lib\site-packages\keras\engine\topology.py in __call__(self, x, mask)
    541                                      '`layer.build(batch_input_shape)`')
    542             if len(input_shapes) == 1:
--> 543                 self.build(input_shapes[0])
    544             else:
    545                 self.build(input_shapes)

C:\Python35\lib\site-packages\keras\layers\recurrent.py in build(self, input_shape)
    761                                       self.W_f, self.U_f, self.b_f,
    762                                       self.W_o, self.U_o, self.b_o]
--> 763             self.W = K.concatenate([self.W_i, self.W_f, self.W_c, self.W_o])
    764             self.U = K.concatenate([self.U_i, self.U_f, self.U_c, self.U_o])
    765             self.b = K.concatenate([self.b_i, self.b_f, self.b_c, self.b_o])

C:\Python35\lib\site-packages\keras\backend\tensorflow_backend.py in concatenate(tensors, axis)
   1220             return tf.concat_v2([to_dense(x) for x in tensors], axis)
   1221         except AttributeError:
-> 1222             return tf.concat(axis, [to_dense(x) for x in tensors])
   1223 
   1224 

C:\Python35\lib\site-packages\tensorflow\python\ops\array_ops.py in concat(values, axis, name)
   1041       ops.convert_to_tensor(axis,
   1042                             name="concat_dim",
-> 1043                             dtype=dtypes.int32).get_shape(
   1044                             ).assert_is_compatible_with(tensor_shape.scalar())
   1045       return identity(values[0], name=scope)

C:\Python35\lib\site-packages\tensorflow\python\framework\ops.py in convert_to_tensor(value, dtype, name, preferred_dtype)
    674       name=name,
    675       preferred_dtype=preferred_dtype,
--> 676       as_ref=False)
    677 
    678 

C:\Python35\lib\site-packages\tensorflow\python\framework\ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype)
    739 
    740         if ret is None:
--> 741           ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
    742 
    743         if ret is NotImplemented:

C:\Python35\lib\site-packages\tensorflow\python\framework\constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref)
    111                                          as_ref=False):
    112   _ = as_ref
--> 113   return constant(v, dtype=dtype, name=name)
    114 
    115 

C:\Python35\lib\site-packages\tensorflow\python\framework\constant_op.py in constant(value, dtype, shape, name, verify_shape)
    100   tensor_value = attr_value_pb2.AttrValue()
    101   tensor_value.tensor.CopyFrom(
--> 102       tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape))
    103   dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)
    104   const_tensor = g.create_op(

C:\Python35\lib\site-packages\tensorflow\python\framework\tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape)
    372       nparray = np.empty(shape, dtype=np_dt)
    373     else:
--> 374       _AssertCompatible(values, dtype)
    375       nparray = np.array(values, dtype=np_dt)
    376       # check to them.

C:\Python35\lib\site-packages\tensorflow\python\framework\tensor_util.py in _AssertCompatible(values, dtype)
    300     else:
    301       raise TypeError("Expected %s, got %s of type '%s' instead." %
--> 302                       (dtype.name, repr(mismatch), type(mismatch).__name__))
    303 
    304 

TypeError: Expected int32, got "<"tf.Variable 'lstm_3_W_i:0' shape=(1, 1) dtype=float32_ref">" of type 'Variable' instead.

任何帮助解决这些错误,并了解 input_shape 和 output_dim 如何工作将不胜感激!

最终,我想开始使用诸如每月营销预算/指标和销售团队指标之类的东西作为多变量预测的外部回归量,但一次一步。感谢您的时间和投入!

标签: pythonmachine-learningkerasneural-networklstm

解决方案


真的应该升级到 Keras 2;在 Keras 1.x 中,units甚至不是一个有效的参数,因此您的错误:

import keras
from keras.models import Sequential
from keras.layers import LSTM
keras.__version__
# '2.2.4'

您的案例在 Keras 2 中仍然出现错误,尽管是不同的:

model = Sequential()
model.add(LSTM(units=64, input_shape=(77, 1), output_dim=1))
[...]
TypeError: For the `units` argument, the layer received both the legacy keyword argument `output_dim` and the Keras 2 keyword argument `units`. Stick to the latter!

正如消息所建议的那样,省略了 legacyoutput_dim参数,我们让它工作:

model = Sequential()
model.add(LSTM(units=64, input_shape=(77, 1)))

model.summary()
# result:
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
lstm_1 (LSTM)                (None, 64)                16896     
=================================================================
Total params: 16,896
Trainable params: 16,896
Non-trainable params: 0
_________________________________________________________________

所以,我认真地建议你升级到 Keras 2(我非常怀疑 Keras 1.x 是否可以与 Tensorflow 1.2 一起工作),如果你仍然有问题,请提出一个新问题......


推荐阅读