【问题标题】:TensorFlow embedding_rnn_decoder 'Tensor' object is not iterableTensorFlow embedding_rnn_decoder 'Tensor' 对象不可迭代
【发布时间】:2017-08-16 22:18:26
【问题描述】:

我正在尝试为我的 ML Engine 包构建一个自定义估算器,但我似乎无法以正确的格式正确构建我的解码器输入序列。考虑以下情况,其中 label1、label2 应该是标签序列。

label1, label2 = tf.decode_csv(rows, record_defaults=[[""], [""]])
labels = tf.stack([label1, label2], axis=1)
label_index = tf.contrib.lookup.index_table_from_file(
    vocabulary_file = label_file)
label_idx = label_index.lookup(labels)
features = dict(zip(['decoder_input'], [label_idx]))

这些“特征”然后作为解码器输入传递,如下所示。当我使用decoder_input 作为我的自定义估计器的输入时,我遇到了一个错误'TypeError:'Tensor' object is not iterable。这里:

outputs, state = tf.contrib.legacy_seq2seq.embedding_rnn_decoder(
    decoder_inputs = features['decoder_input'],
    initial_state = curr_layer,
    cell = tf.contrib.rnn.GRUCell(hidden_units),
    num_symbols = n_labels,
    embedding_size = embedding_dims, # should not be hard-coded
    feed_previous = False)

完整的堆栈跟踪(如下)表明导致问题的代码部分是针对'for i in decoder_inputs' from line 296 的,所以我很清楚问题在于我如何在 input_fn() 中构造我的解码器输入。但是,我似乎无法弄清楚如何使张量对象成为可迭代的序列列表。

堆栈跟踪:

File "/Users/user/anaconda/envs/tensorflow-

  cloud/lib/python2.7/sitepackages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 296, in embedding_rnn_decoder
    for i in decoder_inputs)
  File "/Users/user/anaconda/envs/tensorflow-cloud/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 541, in __iter__
    raise TypeError("'Tensor' object is not iterable.")
TypeError: 'Tensor' object is not iterable.

谁能帮助找出我应该如何正确格式化我的标签,以便它们可以迭代?文档说 decoder_inputs 应该是“一维批量 int32 张量(解码器输入)的列表”。所以我想通过 sta 有没有比 tf.stack() 更合适的方式来生成标签序列?

【问题讨论】:

  • 似乎期待 features['decoder_input'] 成为一个列表。你的情况是什么?
  • 是的,它正在寻找一维张量的列表。我相信我提交的只是一个形状为 [2] 的一维张量,它或多或少是从 tf.stack([label1, label2], axis=1) 生成的——我想我的问题更具体地说是如何创建一维张量列表。是不是像 [label1, label2] 而不是 tf.stack([label1, label2]) 这么简单?
  • 它想要它作为一个列表。如果其中只有一两个项目,那么没有太多理由使用 RNN。如果您想让 RNN 使用单个输入,只需将其包裹在方括号中,以便将其视为张量列表。
  • 项目明显多于 2 个,我只是想为这篇文章创建一个简单的示例。
  • 啊,然后使用 tf.unstack 函数将张量拆分为张量列表。

标签: python tensorflow google-cloud-ml-engine


【解决方案1】:

label_idx 值不是一个列表,因此您面临这个问题:

下面的例子应该更清楚:

label_idx = 1

features = dict(zip(['decoder_input'], [label_idx]))

features['decoder_input']

# 1 output

好像我将 label_idx 更改为列表:

label_idx = [1]

features = dict(zip(['decoder_input'], [label_idx]))

features['decoder_input']

# [1] output

您还可以简化创建字典的方式:

features = {'decoder_input': [label_idx]} # if label_idx is a value
features = {'decoder_input': label_idx} # if label_idx is a list

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 2019-02-10
    • 2020-02-26
    • 2018-10-25
    • 2017-03-20
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多