2017-07-23 86 views
0

我正在學習使用由Keras實現的神經網絡的時間序列分析。這裏是鏈接到數據集:airline_passanger_dataset:keras:TypeError:預期的int32,得到包含'_Message'類型張量的列表而不是

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。

我試圖在線1039和1042更新tensorflow_backend.py (https://github.com/fchollet/keras/blob/master/keras/backend/tensorflow_backend.py)tf.concat語法來回此鏈接:從

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

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

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. 

有人可以幫我用正確的代碼嗎?並解釋我做錯了什麼?謝謝。

+0

你的TensorFlow太舊了,請升級它。 –

+0

你會推薦什麼python和tensorflow的組合?我有一個Windows系統。我只能用CPU版本炒作。我不得不嘗試不同的python版本和tensorflow版本才能安裝tensorflow軟件包,直到找到這個工作組合。 (py 3.5.2和tf r0.12)謝謝。 –

+0

我會建議你不要使用Windows :),所以你完全避免了這些問題 –

回答

0

產生此錯誤是因爲您的TF太舊。 0.12是很久以前發佈的。你應該更新它到最新版本,特別是當你使用Keras 2.0.x時

相關問題