keras:TypeError:期望的int32,得到的列表包含' _Message'代替

时间:2017-07-23 15:18:13

标签: python tensorflow deep-learning keras lstm

我正在学习使用Keras实现的神经网络进行时间序列分析。这是指向数据集的链接:airline_passanger_dataset:

https://datamarket.com/data/set/22u3/international-airline-passengers-monthly-totals-in-thousands-jan-49-dec-60#!ds=22u3&display=line

代码是:

import numpy
import matplotlib.pyplot as plt
import pandas
import math
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error

# fix random seed for reproducibility
numpy.random.seed(7)

# load the dataset
dataframe = pandas.read_csv('C:/users/dell/downloads/international-airline-passengers.csv', usecols=[1], engine='python', skipfooter=3)
dataset = dataframe.values
dataset = dataset.astype('float32')

# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)

# split into train and test sets
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
print(len(train), len(test))

# convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1):
    dataX, dataY = [], []
    for i in range(len(dataset)-look_back-1):
        a = dataset[i:(i+look_back), 0]
        dataX.append(a)
        dataY.append(dataset[i + look_back, 0])
    return numpy.array(dataX), numpy.array(dataY)

# reshape into X=t and Y=t+1
look_back = 1
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)

# reshape input to be [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

# create and fit the LSTM network
model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)

这里我遇到了一个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-38b1a98ab6de> in <module>()
      1 # create and fit the LSTM network
      2 model = Sequential()
----> 3 model.add(LSTM(4, input_shape=(1, look_back)))
      4 model.add(Dense(1))
      5 model.compile(loss='mean_squared_error', optimizer='adam')

C:\Program Files\Anaconda3\lib\site-packages\keras\models.py in add(self, layer)
    434                 # and create the node connecting the current layer
    435                 # to the input layer we just created.
--> 436                 layer(x)
    437 
    438             if len(layer.inbound_nodes) != 1:

C:\Program Files\Anaconda3\lib\site-packages\keras\layers\recurrent.py in __call__(self, inputs, initial_state, **kwargs)
    260         # modify the input spec to include the state.
    261         if initial_state is None:
--> 262             return super(Recurrent, self).__call__(inputs, **kwargs)
    263 
    264         if not isinstance(initial_state, (list, tuple)):

C:\Program Files\Anaconda3\lib\site-packages\keras\engine\topology.py in __call__(self, inputs, **kwargs)
    567                                          '`layer.build(batch_input_shape)`')
    568                 if len(input_shapes) == 1:
--> 569                     self.build(input_shapes[0])
    570                 else:
    571                     self.build(input_shapes)

C:\Program Files\Anaconda3\lib\site-packages\keras\layers\recurrent.py in build(self, input_shape)
   1041                                         initializer=bias_initializer,
   1042                                         regularizer=self.bias_regularizer,
-> 1043                                         constraint=self.bias_constraint)
   1044         else:
   1045             self.bias = None

C:\Program Files\Anaconda3\lib\site-packages\keras\legacy\interfaces.py in wrapper(*args, **kwargs)
     85                 warnings.warn('Update your `' + object_name +
     86                               '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 87             return func(*args, **kwargs)
     88         wrapper._original_function = func
     89         return wrapper

C:\Program Files\Anaconda3\lib\site-packages\keras\engine\topology.py in add_weight(self, name, shape, dtype, initializer, regularizer, trainable, constraint)
    389         if dtype is None:
    390             dtype = K.floatx()
--> 391         weight = K.variable(initializer(shape), dtype=dtype, name=name)
    392         if regularizer is not None:
    393             self.add_loss(regularizer(weight))

C:\Program Files\Anaconda3\lib\site-packages\keras\layers\recurrent.py in bias_initializer(shape, *args, **kwargs)
   1033                         self.bias_initializer((self.units,), *args, **kwargs),
   1034                         initializers.Ones()((self.units,), *args, **kwargs),
-> 1035                         self.bias_initializer((self.units * 2,), *args, **kwargs),
   1036                     ])
   1037             else:

C:\Program Files\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py in concatenate(tensors, axis)
   1721         return tf.sparse_concat(axis, tensors)
   1722     else:
-> 1723         return tf.concat([to_dense(x) for x in tensors], axis)
   1724 
   1725 

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\ops\array_ops.py in concat(concat_dim, values, name)
   1073       ops.convert_to_tensor(concat_dim,
   1074                             name="concat_dim",
-> 1075                             dtype=dtypes.int32).get_shape(
   1076                             ).assert_is_compatible_with(tensor_shape.scalar())
   1077       return identity(values[0], name=scope)

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in convert_to_tensor(value, dtype, name, as_ref, preferred_dtype)
    667 
    668         if ret is None:
--> 669           ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
    670 
    671         if ret is NotImplemented:

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref)
    174                                          as_ref=False):
    175   _ = as_ref
--> 176   return constant(v, dtype=dtype, name=name)
    177 
    178 

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py in constant(value, dtype, shape, name, verify_shape)
    163   tensor_value = attr_value_pb2.AttrValue()
    164   tensor_value.tensor.CopyFrom(
--> 165       tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape))
    166   dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)
    167   const_tensor = g.create_op(

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\framework\tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape)
    365       nparray = np.empty(shape, dtype=np_dt)
    366     else:
--> 367       _AssertCompatible(values, dtype)
    368       nparray = np.array(values, dtype=np_dt)
    369       # check to them.

C:\Program Files\Anaconda3\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 list containing Tensors of type '_Message' instead.

我的python版本是3.5.2,tensorflow版本是0.12.0,keras版本是2.0.6。

我尝试更新tensorflow_backend.py中的tf.concat语法 (https://github.com/fchollet/keras/blob/master/keras/backend/tensorflow_backend.py)在此链接上的第1039和1042行:

Tensorflow Slim: TypeError: Expected int32, got list containing Tensors of type '_Message' instead

来自

y = tf.reshape(y, tf.concat([tf.shape(y), [1] * (diff)], axis=0))

y = tf.reshape(y, tf.concat(values = [tf.shape(y), [1] * (diff)], axis=0))

错误仍然相同:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-48-38b1a98ab6de> in <module>()
      1 # create and fit the LSTM network
      2 model = Sequential()
----> 3 model.add(LSTM(4, input_shape=(1, look_back)))
      4 model.add(Dense(1))
      5 model.compile(loss='mean_squared_error', optimizer='adam')

C:\Program Files\Anaconda3\lib\site-packages\keras\models.py in add(self, layer)
    434                 # and create the node connecting the current layer
    435                 # to the input layer we just created.
--> 436                 layer(x)
    437 
    438             if len(layer.inbound_nodes) != 1:

C:\Program Files\Anaconda3\lib\site-packages\keras\layers\recurrent.py in __call__(self, inputs, initial_state, **kwargs)
    260         # modify the input spec to include the state.
    261         if initial_state is None:
--> 262             return super(Recurrent, self).__call__(inputs, **kwargs)
    263 
    264         if not isinstance(initial_state, (list, tuple)):

C:\Program Files\Anaconda3\lib\site-packages\keras\engine\topology.py in __call__(self, inputs, **kwargs)
    567                                          '`layer.build(batch_input_shape)`')
    568                 if len(input_shapes) == 1:
--> 569                     self.build(input_shapes[0])
    570                 else:
    571                     self.build(input_shapes)

C:\Program Files\Anaconda3\lib\site-packages\keras\layers\recurrent.py in build(self, input_shape)
   1041                                         initializer=bias_initializer,
   1042                                         regularizer=self.bias_regularizer,
-> 1043                                         constraint=self.bias_constraint)
   1044         else:
   1045             self.bias = None

C:\Program Files\Anaconda3\lib\site-packages\keras\legacy\interfaces.py in wrapper(*args, **kwargs)
     85                 warnings.warn('Update your `' + object_name +
     86                               '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 87             return func(*args, **kwargs)
     88         wrapper._original_function = func
     89         return wrapper

C:\Program Files\Anaconda3\lib\site-packages\keras\engine\topology.py in add_weight(self, name, shape, dtype, initializer, regularizer, trainable, constraint)
    389         if dtype is None:
    390             dtype = K.floatx()
--> 391         weight = K.variable(initializer(shape), dtype=dtype, name=name)
    392         if regularizer is not None:
    393             self.add_loss(regularizer(weight))

C:\Program Files\Anaconda3\lib\site-packages\keras\layers\recurrent.py in bias_initializer(shape, *args, **kwargs)
   1033                         self.bias_initializer((self.units,), *args, **kwargs),
   1034                         initializers.Ones()((self.units,), *args, **kwargs),
-> 1035                         self.bias_initializer((self.units * 2,), *args, **kwargs),
   1036                     ])
   1037             else:

C:\Program Files\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py in concatenate(tensors, axis)
   1721         return tf.sparse_concat(axis, tensors)
   1722     else:
-> 1723         return tf.concat([to_dense(x) for x in tensors], axis)
   1724 
   1725 

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\ops\array_ops.py in concat(concat_dim, values, name)
   1073       ops.convert_to_tensor(concat_dim,
   1074                             name="concat_dim",
-> 1075                             dtype=dtypes.int32).get_shape(
   1076                             ).assert_is_compatible_with(tensor_shape.scalar())
   1077       return identity(values[0], name=scope)

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in convert_to_tensor(value, dtype, name, as_ref, preferred_dtype)
    667 
    668         if ret is None:
--> 669           ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
    670 
    671         if ret is NotImplemented:

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref)
    174                                          as_ref=False):
    175   _ = as_ref
--> 176   return constant(v, dtype=dtype, name=name)
    177 
    178 

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\framework\constant_op.py in constant(value, dtype, shape, name, verify_shape)
    163   tensor_value = attr_value_pb2.AttrValue()
    164   tensor_value.tensor.CopyFrom(
--> 165       tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape))
    166   dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)
    167   const_tensor = g.create_op(

C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\framework\tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape)
    365       nparray = np.empty(shape, dtype=np_dt)
    366     else:
--> 367       _AssertCompatible(values, dtype)
    368       nparray = np.array(values, dtype=np_dt)
    369       # check to them.

C:\Program Files\Anaconda3\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 list containing Tensors of type '_Message' instead.

有人可以用正确的代码帮我吗?并解释我做错了什么?谢谢。

1 个答案:

答案 0 :(得分:0)

因为您的TF太旧而产生此错误。 0.12很久以前就被释放了。您应该将其更新到最新版本,特别是在使用Keras 2.0.x时