首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >keras: TypeError:预期的int32,获取包含类型为'_Message‘的张量的列表

keras: TypeError:预期的int32,获取包含类型为'_Message‘的张量的列表
EN

Stack Overflow用户
提问于 2017-07-23 15:18:13
回答 1查看 1.4K关注 0票数 0

我正在学习使用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

代码为:

代码语言:javascript
运行
AI代码解释
复制
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)

这里我遇到了一个错误:

代码语言:javascript
运行
AI代码解释
复制
---------------------------------------------------------------------------
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语法:

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

从…

代码语言:javascript
运行
AI代码解释
复制
y = tf.reshape(y, tf.concat([tf.shape(y), [1] * (diff)], axis=0))

代码语言:javascript
运行
AI代码解释
复制
y = tf.reshape(y, tf.concat(values = [tf.shape(y), [1] * (diff)], axis=0))

错误仍然是相同的:

代码语言:javascript
运行
AI代码解释
复制
---------------------------------------------------------------------------
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.

有没有人能帮我编一下正确的代码?然后解释我做错了什么?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-24 19:32:23

生成此错误是因为您的TF太旧。0.12是很久以前发布的。您应该将其更新到最新版本,尤其是在使用Keras 2.0.x时

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45266707

复制
相关文章
Wikipedia pageview数据获取(bigquery)
维基百科pageview数据是Wikimedia技术团队所维护的访问量数据集。该数据集自2015年五月启用,其具体的pageview定义为对某个网页内容的请求,会对爬虫和人类的访问量进行区分,粒度为小时级别,如下图:
千灵域
2022/06/17
3K0
Wikipedia pageview数据获取(bigquery)
如何在 React 中获取点击元素的 ID?
在 React 应用中,我们经常需要根据用户的点击事件来执行相应的操作。在某些情况下,我们需要获取用户点击元素的唯一标识符(ID),以便进行进一步的处理。本文将详细介绍如何在 React 中获取点击元素的 ID,并提供示例代码帮助你理解和应用这个功能。
网络技术联盟站
2023/06/07
7.2K0
获取HTML网页中option标签元素的值
在进行表单元素的操作时,难免会遇到对option元素的挑选,下面的示例代码能够很好的获取到你option元素选择的值,如果要传递给后端,可通过ajax或者其他方式传递即可。 示例代码
呆呆
2021/10/09
9K0
pythonic实践之获取dict中的元素值
但是大部分情况下,在真实的环境中,这个key有可能不存在。 如果使用下标的方法,那么需要捕捉KeyError错误或者先用if判断key是否存在。这样代码写起来非常的ugly。
有福
2018/08/28
3.4K0
如何在 WPF 中获取所有已经显式赋过值的依赖项属性
获取 WPF 的依赖项属性的值时,会依照优先级去各个级别获取。这样,无论你什么时候去获取依赖项属性,都至少是有一个有效值的。有什么方法可以获取哪些属性被显式赋值过呢?如果是 CLR 属性,我们可以自己写判断条件,然而依赖项属性没有自己写判断条件的地方。
walterlv
2023/10/22
2.2K0
js、jQuery 获取文档、窗口、元素的各种值
浏览器当前窗口文档body的宽度: document.body.clientWidth;(仅仅是body的width) 浏览器当前窗口文档body的高度: document.body.clientHeight;(仅仅是body的height)
Krry
2018/09/10
15.9K0
如何在YouTube Api限额的情况下获取更多视频
谷歌限制了YouTube api v3的请求量,一天10000配额,这里不是10000次请求,每次请求根据不同参数消耗不同配额。为了摆脱这种限制而获得更多的新发布视频,做了以下内容的方案。
一滴水的眼泪
2020/09/24
3.2K0
如何在保留原本所有样式/绑定和用户设置值的情况下,设置和还原 WPF 依赖项属性的值
WPF 备份某控件的一些属性,做一些神奇的操作,然后再还原这些属性。多么司空见惯的操作呀!然而怎么备份却是值得研究的问题。直接赋值?那一定是因为你没踩到一些坑。
walterlv
2023/10/22
9120
【DB笔试面试599】在Oracle中,如何在不执行SQL的情况下获取执行计划?
♣ 题目部分 在Oracle中,如何在不执行SQL的情况下获取执行计划? ♣ 答案部分 1、“EXPLAIN PLAN FOR SQL”不实际执行SQL语句,生成的计划未必是真实执行的计划。但是,必
AiDBA宝典
2019/09/29
3.5K0
Spring在无RedirectAttributes的情况下(如Interceptor中)使用Flash scope
判断逻辑很简单,但是重定向的时候需要前台有消息提示,如果是在Controller中,可以在方法上注入RedirectAttributes参数,但是Interceptor中默认没有这个参数,那么我们如何实现RedirectAttributes的flashMessage功能呢?
飞奔去旅行
2019/06/13
7.4K0
Python - 字典中的值求和
Python 编程语言是一种高级的通用编程语言,广泛用于各种目的。该软件由网页设计、数据分析和人工智能组成。人们之所以意识到这一点,是因为它的简单性、易读性和可用性的便利性。Python 提供了各种预定义的数据结构,包括列表、元组、映射、集合、堆和阵容。这些组件在每种编程语言中都至关重要。在这篇文章中,我们将专注于用于保存关键信息对的词典。
很酷的站长
2023/08/11
1.7K0
Python - 字典中的值求和
图片不变形,宽高不超出父元素的情况下旋转图片
如题,具体的效果见这里 。做这样的效果的难点在于,计算没旋转前图片的宽,高和旋转后的宽高。
前端GoGoGo
2018/08/24
2.3K0
WdatePicker 如何在js里获取到选中的值
<input id="executeDateTime" class="txtbox_normal1 form-control Wdate"  onclick="WdatePicker({el:'executeDateTime',dateFmt:'yyyy-MM-dd HH:mm:ss',onpicked:pickedFunc})" tabindex="3" />
爱明依
2019/03/12
13.1K0
DevOps如何在不牺牲安全性的情况下迁移到云端
企业采用DevOps意味着开发进行将比以往任何时候都要快。那么如何确保一切都是安全的,尤其是将业务迁移到云端时? 调研机构Gartner公司预测, 2022年全球云计算服务市场规模和增长率几乎是整体I
CloudBest
2019/09/17
9090
DevOps如何在不牺牲安全性的情况下迁移到云端
JavaScript数组求和_js获取对象数组的第一个元素
您如何找到其元素的总和?好吧,解决方案是一个array.reduce()方法。Array.prototype.reduce()函数可用于遍历数组,将当前元素值添加到先前项目值的总和中。
全栈程序员站长
2022/11/10
7.9K0
删除线性表中所有值为x的数据元素
voide del_x_l(SqlList &L,Elemtype x){ int k=0;//记录值不等于x的元素个数 for(i=0;i<L.length;i++){ if(L.data[i]!=x){ L.data[k]=L.data[i]; k++;//不等于x的元素增1 } } L.length=k; } voide del_x_2(SqlList &L,Elemtype x){
week
2018/08/27
1.7K0
Excel公式技巧68:查找并获取所有匹配的值
在《Excel公式技巧67:按条件将数据分组标识》中,我们根据指定的条件采用数字标识将数据进行了分组。利用这列分组数据,我们能方便地查找并获取所有匹配的值。
fanjy
2020/12/08
11.8K0
Excel公式技巧68:查找并获取所有匹配的值
练习14—元素求和
题目 从键盘输入n (个数不限)个整形数字,放入数组PArray, 调用函数 int *Calc(int *PA,int Num); 计算数组中所有元素的和返回到 main 函数,输出计算结果。 解题步骤 (1)定义数组、变量; (2)接收设定值; (3)分配内存空间; (4)元素求和; (5)输出; C语言 #include <stdio.h> #include <stdlib.h> int *Calc(int *PA, int Num) { int sum = 0, i;
攻城狮杰森
2022/06/03
2260
点击加载更多

相似问题

等待UI更新后再删除UIActivityIndicator

20

等待Swing完成更新JProgressBar后再继续

25

立即显示子视图/等待视图可见后再继续

32

等待内部指令编译后再调用api函数

10

反应16.13: useState等待状态更新后再呈现

12
交个朋友
加入腾讯云官网粉丝站
蹲全网底价单品 享第一手活动信息
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档