Tensorflow: ValueError:尝试以不同于第一次使用的变量范围重用 RNNCell。

创建于 2017-03-08  ·  102评论  ·  资料来源: tensorflow/tensorflow

我不确定我是否是第一个遇到以下错误的人:

ValueError:尝试重用RNNCell与第一次使用不同的变量范围。 第一次使用单元格是在范围 'rnn/multi_rnn_cell/cell_0/basic_lstm_cell' 中,这次尝试是在范围 'rnn/multi_rnn_cell/cell_1/basic_lstm_cell' 中。 如果您希望它使用一组不同的权重,请创建一个新的单元实例。 如果在使用之前:MultiRNNCell([BasicLSTMCell(...)] * num_layers),请更改为:MultiRNNCell([BasicLSTMCell(...) for _ in range(num_layers)])。 如果在您使用相同的单元实例作为双向 RNN 的正向和反向单元之前,只需创建两个实例(一个用于正向,一个用于反向)。 在 2017 年 5 月,我们将开始将此单元格的行为转换为使用现有存储的权重(如果有),当它以 scope=None 调用时(这可能导致静默模型退化,因此此错误将一直存在到那时。)

使用代码片段:

  import tensorflow as tf
  from tensorflow.contrib import rnn

  hidden_size = 100
  batch_size  = 100
  num_steps   = 100
  num_layers  = 100
  is_training = True
  keep_prob   = 0.4

  input_data = tf.placeholder(tf.float32, [batch_size, num_steps])
  lstm_cell = rnn.BasicLSTMCell(hidden_size, forget_bias=0.0, state_is_tuple=True)

  if is_training and keep_prob < 1:
      lstm_cell = rnn.DropoutWrapper(lstm_cell)
  cell = rnn.MultiRNNCell([lstm_cell for _ in range(num_layers)], state_is_tuple=True)

  _initial_state = cell.zero_state(batch_size, tf.float32)

  iw = tf.get_variable("input_w", [1, hidden_size])
  ib = tf.get_variable("input_b", [hidden_size])
  inputs = [tf.nn.xw_plus_b(i_, iw, ib) for i_ in tf.split(input_data, num_steps, 1)]

  if is_training and keep_prob < 1:
      inputs = [tf.nn.dropout(input_, keep_prob) for input_ in inputs]

  outputs, states = rnn.static_rnn(cell, inputs, initial_state=_initial_state)

我用谷歌搜索了没有运气,有人能告诉我出路吗?

awaiting tensorflower

最有用的评论

我遇到了同样的问题。 如果大家都在 master 分支上使用编译版本,我相信我们是最近一次提交引起的同一个问题。 正如提交消息所说:

使 tf.contrib.rnn 中的所有 RNNCells 都像 tf.layers 层一样,但语义更严格
w:

  1. 首次使用 __call__ 时,使用的范围存储在单元格中。 RNNCell 尝试在该范围内创建权重,但如果已经设置了一些权重,则会引发错误,除非 RNNCell 是使用参数reuse=True 构造的。

  2. 对同一单元格实例的后续使用 __call__ 必须在同一范围内。
    如果不是,则会引发错误。

从我正在运行ptb tutorial的案例来看,解决方案只是在第 112 行添加一个以reuse命名的参数,如下所示:

def lstm_cell():
  return tf.contrib.rnn.BasicLSTMCell(
      size, forget_bias=0.0, state_is_tuple=True, reuse=tf.get_variable_scope().reuse)

然后它工作。

所有102条评论

我在尝试运行翻译示例时遇到同样的错误(即使在进行小型自测时),可以在此处找到: https ://github.com/tensorflow/models/tree/master/tutorials/rnn/translate

我遇到了同样的问题。 如果大家都在 master 分支上使用编译版本,我相信我们是最近一次提交引起的同一个问题。 正如提交消息所说:

使 tf.contrib.rnn 中的所有 RNNCells 都像 tf.layers 层一样,但语义更严格
w:

  1. 首次使用 __call__ 时,使用的范围存储在单元格中。 RNNCell 尝试在该范围内创建权重,但如果已经设置了一些权重,则会引发错误,除非 RNNCell 是使用参数reuse=True 构造的。

  2. 对同一单元格实例的后续使用 __call__ 必须在同一范围内。
    如果不是,则会引发错误。

从我正在运行ptb tutorial的案例来看,解决方案只是在第 112 行添加一个以reuse命名的参数,如下所示:

def lstm_cell():
  return tf.contrib.rnn.BasicLSTMCell(
      size, forget_bias=0.0, state_is_tuple=True, reuse=tf.get_variable_scope().reuse)

然后它工作。

@ebrevdo你能看看这个吗?

当我在Shakespeare RNN Repo上使用 Windows/GPU build 105 时,这个问题会重现。

使用 Win 1.0.0/GPU 版本运行代码时,没有问题。

该回购看起来像是针对 tf 1.0,而不是中间版本。

2017 年 3 月 8 日下午 3:56,“Tom Wanzek” [email protected]写道:

在莎士比亚上使用 Windows/GPU build 105 时,这个问题对我来说是重复的
RNN 回购https://github.com/martin-gorner/tensorflow-rnn-shakespeare

使用 Win 1.0.0/GPU 版本运行代码时,没有问题。


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-285209555
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtim5ansaL1KN51T4nCaqLnqw2QHN4Wks5rj0BBgaJpZM4MWl4f
.

@tongda ,我正在使用 Tensorflow 1.0 的发布版本,在 cpu 模式下在 MacOS 上工作。 我将切换到master分支,通过添加“reuse”参数来查看它是否有效,谢谢。

doncat99:如果你这样做,请确保你的代码查询 tensorflow 版本
如果版本低于主分支版本,则引发标志。
您可能需要检查:

从 tensorflow.core 导入版本
版本.GIT_VERSION

2017 年 3 月 8 日星期三下午 6:58,doncat99 [email protected]写道:

@tongda https://github.com/tongda ,我使用的是发行版
Tensorflow 1.0,在 cpu 模式下在 MacOS 上工作。 我要换师傅
通过添加“reuse”参数来查看它是否工作,谢谢。


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-285240438 ,
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtim66cU9e16lgD-2D0QLGcQCiHbV0zks5rj2rbgaJpZM4MWl4f
.

@ebrevdo那么建议对莎士比亚 RNN 进行哪些更改以使其能够与中间稳定版本一起使用?

这是代码的关键架构部分,现在由于 build#105 失败:

#
# the model (see FAQ in README.md)
#
lr = tf.placeholder(tf.float32, name='lr')  # learning rate
pkeep = tf.placeholder(tf.float32, name='pkeep')  # dropout parameter
batchsize = tf.placeholder(tf.int32, name='batchsize')

# inputs
X = tf.placeholder(tf.uint8, [None, None], name='X')    # [ BATCHSIZE, SEQLEN ]
Xo = tf.one_hot(X, ALPHASIZE, 1.0, 0.0)                 # [ BATCHSIZE, SEQLEN, ALPHASIZE ]
# expected outputs = same sequence shifted by 1 since we are trying to predict the next character
Y_ = tf.placeholder(tf.uint8, [None, None], name='Y_')  # [ BATCHSIZE, SEQLEN ]
Yo_ = tf.one_hot(Y_, ALPHASIZE, 1.0, 0.0)               # [ BATCHSIZE, SEQLEN, ALPHASIZE ]
# input state
Hin = tf.placeholder(tf.float32, [None, INTERNALSIZE*NLAYERS], name='Hin')  # [ BATCHSIZE, INTERNALSIZE * NLAYERS]

# using a NLAYERS=3 layers of GRU cells, unrolled SEQLEN=30 times
# dynamic_rnn infers SEQLEN from the size of the inputs Xo

onecell = rnn.GRUCell(INTERNALSIZE)
dropcell = rnn.DropoutWrapper(onecell, input_keep_prob=pkeep)
multicell = rnn.MultiRNNCell([dropcell for _ in range(NLAYERS)], state_is_tuple=False)
multicell = rnn.DropoutWrapper(multicell, output_keep_prob=pkeep)
Yr, H = tf.nn.dynamic_rnn(multicell, Xo, dtype=tf.float32, initial_state=Hin)
# Yr: [ BATCHSIZE, SEQLEN, INTERNALSIZE ]
# H:  [ BATCHSIZE, INTERNALSIZE*NLAYERS ] # this is the last state in the sequence

我似乎没有找到任何关于reuse标志的文档?

提前致谢。

利用:

multicell = rnn.MultiRNNCell([rnn.DropoutWrapper(rnn.GRUCell(INTERNALSIZE),
input_keep_prob=pkeep) for _ in range(NLAYERS)], state_is_tuple=False)

它为每一层创建一个单独的 grucell 对象。

2017 年 3 月 10 日上午 7:44,“Tom Wanzek” [email protected]写道:

@ebrevdo https://github.com/ebrevdo那么建议是什么
对莎士比亚 RNN 的更改以允许它与中间体一起工作
稳定发布?

这是代码的关键架构部分,现在失败了
构建#105:

模型(参见 README.md 中的常见问题解答)

lr = tf.placeholder(tf.float32, name='lr') # 学习率
pkeep = tf.placeholder(tf.float32, name='pkeep') # dropout 参数
batchsize = tf.placeholder(tf.int32, name='batchsize')

输入

X = tf.placeholder(tf.uint8, [None, None], name='X') # [ BATCHSIZE, SEQLEN ]
Xo = tf.one_hot(X, ALPHASIZE, 1.0, 0.0) # [ BATCHSIZE, SEQLEN, ALPHASIZE ]# 预期输出 = 相同的序列移动了 1,因为我们试图预测下一个字符
Y_ = tf.placeholder(tf.uint8, [None, None], name='Y_') # [ BATCHSIZE, SEQLEN ]
Yo_ = tf.one_hot(Y_, ALPHASIZE, 1.0, 0.0) # [ BATCHSIZE, SEQLEN, ALPHASIZE ]# 输入状态
Hin = tf.placeholder(tf.float32, [None, INTERNALSIZE*NLAYERS], name='Hin') # [ BATCHSIZE, INTERNALSIZE * NLAYERS]

使用 NLAYERS=3 层 GRU 单元,展开 SEQLEN=30 次# dynamic_rnn 从输入 Xo 的大小推断 SEQLEN

onecell = rnn.GRUCell(INTERNALSIZE)
dropcell = rnn.DropoutWrapper(onecell, input_keep_prob=pkeep)
multicell = rnn.MultiRNNCell([dropcell for _ in range(NLAYERS)], state_is_tuple=False)
multicell = rnn.DropoutWrapper(multicell, output_keep_prob=pkeep)
Yr, H = tf.nn.dynamic_rnn(multicell, Xo, dtype=tf.float32, initial_state=Hin)# Yr: [ BATCHSIZE, SEQLEN, INTERNALSIZE ]# H: [ BATCHSIZE, INTERNALSIZE*NLAYERS ] # 这是最后一个状态在序列中

我似乎没有找到任何关于重用标志的文档?

提前致谢。


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-285702372
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtim6MOOCbx3RJEJe8PQBDXGVIXTGPmks5rkW_jgaJpZM4MWl4f
.

我不明白为什么使用seq2seq 教程模型会出现此错误:

cell = tf.contrib.rnn.MultiRNNCell([single_cell() for _ in range(num_layers)])

来源

创建单元格的位置

def single_cell():
    return tf.contrib.rnn.GRUCell(size)

@ebrevdo感谢您回到这个问题。 不幸的是,建议的更改使事情保持原样,并出现上述错误。 鉴于上述关于seq2seq 教程的评论,我怀疑我们都在同一条船上?

你确定这是完全相同的错误吗? 请在此处复制并粘贴。

我的错,我只是再次(从头开始)完成了相关代码的更改过程并按照建议重新运行它。 错误确实已被消除,老吟游诗人现在幻觉就好了👍

所以,thx,不知道我昨天哪里出错了,但很明显是在我身上。

我在使用 Tensorflow 1.0 的发布版本并在 cpu 模式下在 MacOS 上工作时遇到了同样的问题。即使添加了“重用”参数

def cell():
    return tf.contrib.rnn.BasicLSTMCell(rnn_size,state_is_tuple=True,reuse=tf.get_variable_scope().reuse)

muticell = tf.contrib.rnn.MultiRNNCell([cell for _ in range(num_layers)], state_is_tuple=True)

您的多单元格看起来不对...您应该使用“cell() for _ in
范围(...)”

2017 年 3 月 16 日星期四晚上 8:29,cuiming [email protected]写道:

我在使用 Tensorflow 1.0 的发布版本时遇到了同样的问题
并在 cpu 模式下在 MacOS 上工作。即使添加“重用”参数

定义单元格():
return tf.contrib.rnn.BasicLSTMCell(rnn_size,state_is_tuple=True,reuse=tf.get_variable_scope().reuse)

muticell = tf.contrib.rnn.MultiRNNCell([cell for _ in range(num_layers)], state_is_tuple=True)


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-287257629 ,
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtim3A6JQr8ptRKrdiDW_kgNRIFkHGlks5rmf4WgaJpZM4MWl4f
.

我试图运行翻译示例:python2.7 translate.py --data_dir data/ --train_dir train/ --size=256 --num_layers=2 --steps_per_checkpoint=50

似乎使用 MultiRNNCell 的方式是正确的:
cell = tf.contrib.rnn.MultiRNNCell([single_cell() for _ in range(num_layers)])

但我得到了同样的错误:
ValueError:尝试重用RNNCell与第一次使用不同的变量范围。 首次使用单元格是范围为“embedding_attention_seq2seq/embedding_attention_decoder/attention_decoder/multi_rnn_cell/cell_0/gru_cell”,此尝试是范围为“embedding_attention_seq2seq/rnn/multi_rnn_cell/cell_0/gru_cell”。 如果您希望它使用一组不同的权重,请创建一个新的单元实例。 如果在使用之前:MultiRNNCell([GRUCell(...)] * num_layers),请更改为:MultiRNNCell([GRUCell(...) for _ in range(num_layers)])。 如果在您使用相同的单元实例作为双向 RNN 的正向和反向单元之前,只需创建两个实例(一个用于正向,一个用于反向)。 在 2017 年 5 月,我们将开始将此单元格的行为转换为使用现有存储的权重(如果有),当它以 scope=None 调用时(这可能导致静默模型退化,因此此错误将一直存在到那时。)

@bowu - 你有什么运气吗? 如果您还没有尝试过,请从最新源重新安装 tensorflow。 对一些 core_rnn 文件进行了一些更改,其中包括一些其他文件。 现在为我工作。

@robmsylvester我从最新源重新安装 tensorflow,仍然是同样的错误。 我在分支 master 上,最新的提交是commit 2a4811054a9e6b83e1f5a2705a92aab50e151b13 。 构建仓库时的最新提交是什么?

嗨,我正在使用使用源代码构建的 GPU 使用 Tensorflow r1.0。 我正在尝试遵循未修改的 Seq2Seq 翻译教程,但我遇到了同样的错误。 IE

ValueError:尝试重用RNNCell与第一次使用不同的变量范围。 单元格的第一次使用是范围'embedding_attention_seq2seq/embedding_attention_decoder/attention_decoder/multi_rnn_cell/cell_0/gru_cell',这次尝试是范围'embedding_attention_seq2seq/rnn/multi_rnn_cell/cell_0/gru_cell'.....

我的 seq2seq_model.py 中代码的相关部分是:

 # Create the internal multi-layer cell for our RNN.
    def single_cell():
      return tf.contrib.rnn.GRUCell(size)
    if use_lstm:
      def single_cell():
        return tf.contrib.rnn.BasicLSTMCell(size)
    cell = single_cell()
    if num_layers > 1:
      cell = tf.contrib.rnn.MultiRNNCell([single_cell() for _ in range(num_layers)])

我能做些什么来解决这个问题?

在创建 GRUCell 的调用中添加“reuse=tf.get_variable_scope().reuse”没有帮助。

万分感谢!

@prashantserai - 看看如果你从上面删除 MultiRNNCell 线会发生什么,有效地使你的网络只有一层。 那它行得通吗? 它可能是 MultiRNNCell 中的某个错误。 我最近在某个地方读到过,可能是堆栈溢出。

如果您自己实现堆叠的 lstm/gru,则不会出现此错误,并且您可以实现相同的功能(实际上更多,因为您可以自由地使用双向架构、奇怪的残差和跳过连接等做任何您想做的事情.)

@robmsylvester即使我尝试使用 num_layers=1 应该有效地跳过该行,同样的错误仍然存​​在。 还有其他想法吗? 感谢您的输入。

嗯。 对我来说突出的一件事是在引用的遗留 seq2seq 文件中:

encoder_cell = copy.deepcopy(cell)

似乎使用了这条线,因为在编码器和解码器端都使用了相同的架构。 他们复制单元格,然后将单元格参数传递给注意力解码器嵌入函数,然后传递给注意力解码器本身。

如果您在 seq2seq 模型文件中显式创建编码器单元和解码器单元并将两者传递给遗留库文件,对函数及其参数进行小幅调整,会发生什么?

@robmsylvester不应该对单元格的范围进行更改吗? 它也适用于其他两个示例。 在我看来,这将是一个非常丑陋的解决方法。 必须存在更清洁的解决方案; 也许我们错过了什么? (我在 seq2seq 教程上也遇到了同样的错误,尝试了上述所有解决方案)。

@iamgroot42 - 是的,这个“解决方案”无疑是非常丑陋的,但更重要的是试图找出问题所在。 我会在几个小时内玩它,看看我能不能找到什么东西。

事实上,copy.deepcopy 之所以存在,是因为这些是遗留功能,并且
我们没有资源来维护/更新它们。 如果你想
引入向后兼容的更改,允许用户提供
解码步骤的第二个单元格,如果它是 None 则回退到
deepcopy,那么我很乐意审查 PR。 请记住,它会
必须是向后兼容的更改。

2017 年 4 月 4 日星期二上午 11:38,Rob Sylvester [email protected]
写道:

@iamgroot42 https://github.com/iamgroot42 - 是的,那个“解决方案”是
诚然非常丑陋,但更重要的是试图找出问题所在
可能。 我会在几个小时内玩它,看看我能不能追踪到什么
向下。


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-291593289
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtim1QHTDhOC_zT6cKtmUFPOit5Yjn7ks5rso5CgaJpZM4MWl4f
.

@ebrevdo - 我会考虑的。 我确实有一个翻译器,它的工作原理与这个翻译器非常相似,但通过一个单独的类创建单元格,该类允许在你想要的地方插入双向层、在你想要的地方插入残差、将输入与 concat 与 sum 合并,以及其他一些事情。 我想我可以通过使用静态 RNN 很容易地将我的课程迁移到本教程。 我会告诉你。

@ebrevdo我在 Red Hat 上运行 Tensorflow r1.0 (tensorflow-1.0.1-cp36-cp36m-linux_x86_64) 并拥有来自 Github 的最新版本的翻译教程。你知道目前有什么方法可以使这项工作吗?

很遗憾,翻译教程不适用于 TF 1.0。 我们应该解决这个问题。 @lukaszkaiser你能看看吗? 我们正在编写一个新教程,但它还有几周的时间,并且需要一个夜间版本的 TensorFlow(或 TF 1.1 或 1.2)才能工作。

(lukasz;我很难从各种评论中确定本教程的哪一部分在 TF 1.0 中存在错误。你有没有机会找出这条线,我可以帮助它工作?)

@ebrevdo这是教程。 错误出现在组行中。 此处传递的单元格用于传统 seq2seq 模型的后向和前向阶段,由于相同的单元格用于不同的范围,因此会引发错误。

@iamgroot42你想进行 PR 并进行必要的更改吗? 那太好了,我目前没有自己的周期来做那件事。 谢谢!

我注意到如果从分支 remotes/origin/r1.0 上的源代码编译,TF 1.0 可以与最新版本的翻译教程一起正常工作

$ git clone https://github.com/tensorflow/tensorflow
$ cd tensorflow
$ git checkout remotes/origin/r1.0

然后构建并安装 TensorFlow,它工作正常。

在分支 remotes/origin/r1.1 上,它有“不同的变量范围”错误。
我按照@robmsylvester的建议修改了代码

如果您在 seq2seq 模型文件中显式创建编码器单元和解码器单元并将两者传递给遗留库文件,对函数及其参数进行小幅调整,会发生什么?

它现在对我有用。

@oxwsds我使用的 Tensorflow 是 1.0.1,所以可能有错误..

我实际上已经尝试过@robmsylvester建议的内容.. 培训已经开始(现在完成了 2 天 13 小时).. 它在解码过程中失败,但出现错误:

  File "/homes/3/serai/.conda/envs/tensorflow_r1.0_gpu/lib/python3.6/site-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 883, in embedding_attention_seq2seq
    initial_state_attention=initial_state_attention)
  File "/homes/3/serai/.conda/envs/tensorflow_r1.0_gpu/lib/python3.6/site-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 787, in embedding_attention_decoder
    initial_state_attention=initial_state_attention)
  File "/homes/3/serai/.conda/envs/tensorflow_r1.0_gpu/lib/python3.6/site-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 686, in attention_decoder
    cell_output, state = cell(x, state)
  File "/homes/3/serai/.conda/envs/tensorflow_r1.0_gpu/lib/python3.6/site-packages/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py", line 796, in __call__
    % (len(self.state_size), state))
ValueError: Expected state to be a tuple of length 3, but received: Tensor("model_with_buckets/embedding_attention_seq2seq/rnn/gru_cell_4/add:0", shape=(?, 1024), dtype=float32)

你试过解码吗?

@prashantserai不完全知道,但你遇到的似乎是另一个问题。

@prashantserai如果仅在您解码时失败,则可能与使用批量大小有关吗? 如果在训练期间将批量大小降低到 1,模型是否仍会训练?

@bowu这里有同样的错误。 Mac OX Sierra、TensorFlow 1.1.0-rc1、Python 2.7.10 和 Python 3.6.1。

@robmsylvester它确实以一个批量大小成功训练,但在以相同或类似方式解码时失败..这是一个完整的回溯..我认为这是一个连接错误的原因是因为参考seq2seq_f (这是修改后的函数之一)(我的代码中的 #prashant 注释表示修改的行是跟踪的一部分)

2017-04-10 11:32:27.447042: I tensorflow/core/common_runtime/gpu/gpu_device.cc:887] Found device 0 with properties: 
name: GeForce GTX 780 Ti
major: 3 minor: 5 memoryClockRate (GHz) 0.928
pciBusID 0000:42:00.0
Total memory: 2.95GiB
Free memory: 2.88GiB
2017-04-10 11:32:27.447094: I tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0 
2017-04-10 11:32:27.447102: I tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0:   Y 
2017-04-10 11:32:27.447118: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 780 Ti, pci bus id: 0000:42:00.0)
Traceback (most recent call last):
  File "translate.py", line 322, in <module>
    tf.app.run()
  File "/homes/3/serai/.conda/envs/tensorflow_r1.0_gpu/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "translate.py", line 317, in main
    decode()
  File "translate.py", line 248, in decode
    model = create_model(sess, True)
  File "translate.py", line 136, in create_model
    dtype=dtype)
  File "/data/data6/scratch/serai/models/tutorials/rnn/translate/seq2seq_model.py", line 168, in __init__
    softmax_loss_function=softmax_loss_function)
  File "/homes/3/serai/.conda/envs/tensorflow_r1.0_gpu/lib/python3.6/site-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 1203, in model_with_buckets
    decoder_inputs[:bucket[1]])
  File "/data/data6/scratch/serai/models/tutorials/rnn/translate/seq2seq_model.py", line 167, in <lambda>
    self.target_weights, buckets, lambda x, y: seq2seq_f(x, y, True),
  File "/data/data6/scratch/serai/models/tutorials/rnn/translate/seq2seq_model.py", line 144, in seq2seq_f
    dtype=dtype) #prashant
  File "/homes/3/serai/.conda/envs/tensorflow_r1.0_gpu/lib/python3.6/site-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 883, in embedding_attention_seq2seq
    initial_state_attention=initial_state_attention)
  File "/homes/3/serai/.conda/envs/tensorflow_r1.0_gpu/lib/python3.6/site-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 787, in embedding_attention_decoder
    initial_state_attention=initial_state_attention)
  File "/homes/3/serai/.conda/envs/tensorflow_r1.0_gpu/lib/python3.6/site-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 686, in attention_decoder
    cell_output, state = cell(x, state)
  File "/homes/3/serai/.conda/envs/tensorflow_r1.0_gpu/lib/python3.6/site-packages/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py", line 796, in __call__
    % (len(self.state_size), state))
ValueError: Expected state to be a tuple of length 3, but received: Tensor("model_with_buckets/embedding_attention_seq2seq/rnn/gru_cell_4/add:0", shape=(?, 1024), dtype=float32)

@oxwsds您的意见会根据上面的完整跟踪而改变吗?

@prashantserai我尝试解码,它工作正常。 我只是简单地将encoder_cell arg 添加到函数tf.contrib.legacy_seq2seq.embedding_attention_seq2seq并在translate/seq2seq_model.py创建单元格并将其传递给在函数seq2seq_f中调用的函数。 你是如何改变你的代码的?

@oxwsds @robmsylvester @ebrevdo
我终于有了现在可以工作的东西(我的意思是,我的单层 256 单元网络的结果有点令人震惊,但这可能只是因为网络重量超轻,而且我根本没有调整参数)
谢谢大家!谢谢...!!!!!

_这是我最后的想法:_

@oxwsds评论说,当从分支 remotes/origin/r1.0 为 TRUE 编译 Tensorflow 时,本教程(以当前形式)无需任何修改即可工作。 虽然,可悲的是,我需要在 Tensorflow 代码中修改的 Tensorflow 版本和 remotes/origin/r1.0 中的版本都被标记相同。

@robmsylvester在评论中的修复(复制如下)对我的 Tensorflow 版本有效,其中教程不能开箱即用(我猜也应该适用于 TF 1.1)。 实施起来有点混乱,但我可以做到,这就是说:-P
在此之前的最后两条评论中的错误是由于我的错误造成的。 像一个假人一样,我只在训练期间指定层和隐藏单元参数,我让代码在解码期间使用默认值。 (本教程的这一部分可能会稍微有点假证明:https://www.tensorflow.org/tutorials/seq2seq#lets_run_it)

嗯。 对我来说突出的一件事是在引用的遗留 seq2seq 文件中:

encoder_cell = copy.deepcopy(cell)

似乎使用了这条线,因为在编码器和解码器端都使用了相同的架构。 他们复制单元格,然后将单元格参数传递给注意力解码器嵌入函数,然后传递给注意力解码器本身。

如果您在 seq2seq 模型文件中显式创建编码器单元和解码器单元并将两者传递给遗留库文件,对函数及其参数进行小幅调整,会发生什么?

感谢您的反馈! 看来TF之间有什么不同
在 pypi 和那个标签上? 古汉,这可能吗?

2017 年 4 月 10 日星期一晚上 9:05,prashantserai [email protected]
写道:

@oxwsds https://github.com/oxwsds @robmsylvester
https://github.com/robmsylvester @ebrevdo https://github.com/ebrevdo
我终于有了现在可以工作的东西(我的意思是,我的单曲的结果
256 层单元网络有点骇人听闻,但这可能只是
因为网络是超轻量级的,我根本没有调整参数)

这是我的底线:

@oxwsds https://github.com/oxwsds评论本教程(在它的当前形式)在 Tensorflow 运行时无需任何修改即可工作从分支 remotes/origin/r1.0 编译为 TRUE 。 悲伤的一点
虽然是我修改过的 Tensorflow 版本
需要 Tensorflow 代码,版本在 remotes/origin/r1.0
两者的标签相同。

@robmsylvester https://github.com/robmsylvester在评论中的修复
(复制如下)对于我的 Tensorflow 版本有效,其中教程
没有开箱即用(我猜也应该适用于 TF 1.1)。 它是
实施起来有点混乱,但我可以做到,这就是说
:-P
在此之前的最后两条评论中的错误是由于我的错误造成的。 喜欢
一个假人,我只指定了层和隐藏单元参数
在训练期间,我让代码在解码期间使用默认值。 (这本教程的一部分可能是稍微更假的证明:https://www.tensorflow.org/tutorials/seq2seq#lets_run_ithttps://www.tensorflow.org/tutorials/seq2seq#lets_run_it

嗯。 对我来说突出的一件事是引用的遗留 seq2seq
文件:

encoder_cell = copy.deepcopy(cell)

似乎使用了这条线,因为两者都使用了相同的架构
编码器和解码器端。 他们制作了单元格的副本,然后通过
单元参数沿注意力解码器嵌入函数,然后
注意力解码器本身。

如果您显式创建编码器单元和解码器会发生什么
seq2seq 模型文件中的单元格并将它们传递给遗留库
文件,对函数及其参数进行小的调整?


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-293143828
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtimxvcfFnbWbpj7aUs3BUjwGEFj6p5ks5ruvvygaJpZM4MWl4f
.

有关信息,我在尝试堆叠 LSTM 单元时遇到了这个问题:
我的原始代码是:

    lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(hidden_size, forget_bias=0.0, state_is_tuple=True)
    if is_training and keep_prob < 1:
      lstm_cell = tf.nn.rnn_cell.DropoutWrapper(
          lstm_cell, output_keep_prob=keep_prob)
    cell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * num_layers, state_is_tuple=True)

然后,使用以下代码,创建模型是可以的,但我无法与另一个模型共享变量。 (例如,如果您创建一个应该共享张量的 train_model 和一个 valid_model,它将失败)

    lstm_creator = lambda: tf.contrib.rnn.BasicLSTMCell(
                                        hidden_size, 
                                        forget_bias=0.0, state_is_tuple=True)
    if is_training and keep_prob < 1:
      cell_creator = lambda:tf.contrib.rnn.DropoutWrapper(
          lstm_creator(), output_keep_prob=keep_prob)
    else:
      cell_creator = lstm_creator

    cell = tf.contrib.rnn.MultiRNNCell([cell_creator() for _ in range(num_layers)], state_is_tuple=True)

所以最后我用lstm_creator作为tensorflow/models/tutorials/rnn/ptb/ptb_word_lm.py#L112中的lstm_cell之类的函数。 我现在有:

def lstm_cell():
      # With the latest TensorFlow source code (as of Mar 27, 2017),
      # the BasicLSTMCell will need a reuse parameter which is unfortunately not
      # defined in TensorFlow 1.0. To maintain backwards compatibility, we add
      # an argument check here:
      if 'reuse' in inspect.getargspec(
          tf.contrib.rnn.BasicLSTMCell.__init__).args:
        return tf.contrib.rnn.BasicLSTMCell(
            size, forget_bias=0.0, state_is_tuple=True,
            reuse=tf.get_variable_scope().reuse)
      else:
        return tf.contrib.rnn.BasicLSTMCell(
            size, forget_bias=0.0, state_is_tuple=True)
    attn_cell = lstm_cell

    lstm_creator = lstm_cell
    if is_training and keep_prob < 1:
      cell_creator = lambda:tf.contrib.rnn.DropoutWrapper(
          lstm_creator(), output_keep_prob=keep_prob)
    else:
      cell_creator = lstm_creator

    cell = tf.contrib.rnn.MultiRNNCell([cell_creator() for _ in range(num_layers)], state_is_tuple=True)

它现在正在完全工作

试图让这个东西运行,这会导致同样的错误:

https://gist.github.com/danijar/c7ec9a30052127c7a1ad169eeb83f159#file -blog_tensorflow_sequence_classification-py-L38

@pltrdy的解决方案对我来说并不奇怪。 我越来越

ValueError: Variable rnn/multi_rnn_cell/cell_0/basic_lstm_cell/weights does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?

@aep你使用了我在帖子末尾提到的https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/ptb_word_lm.py#L112的功能(现在编辑得更清楚了)

cells=[]
for _ in range(15):
    cell = create_lstm_cell(config)
    cells.append(cell)
lsmt_layers = rnn.MultiRNNCell(cells)

它解决了我的问题

通过安装旧版本的 Tensorflow 设法解决了这个问题:
pip install -Iv tensorflow==1.0

执行 seq2seq 教程时收到错误消息

关于@ebrevdo所说的,我认为解决方案不是修复遗留的 seq2seq 代码,而是更新教程以使用contrib.seq2seq包,该包被积极维护。 当您运行的第一个 tensorflow 程序吐出一堆错误时,这是​​非常令人沮丧的。 如果我这周有时间,我会提交 PR。

我们正在开发一个新的 seq2seq 教程。 我们曾希望在年底前发布
上个月,但正在延迟。 它将使用新的 API。

2017 年 5 月 1 日上午 8:07,“Kyle Teague” [email protected]写道:

关于@ebrevdo https://github.com/ebrevdo所说的,我认为
解决方案不是修复遗留的 seq2seq 代码,而是更新
教程改为使用 contrib.seq2seq 包,这是积极的
保持。 当你第一次使用 tensorflow 程序时,这是非常令人沮丧的
曾经运行会吐出一堆错误。 如果我这周有时间,我会
提交 PR。


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-298350307
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtim587xZx9Gi4-yXmwccSum8_Trc1oks5r1fUogaJpZM4MWl4f
.

@ebrevdo我在 tensorflow1.1 网站上运行 sequence_to_sequence 模型时遇到了同样的错误。 而且我尝试使用“重用”参数但失败了。 你能告诉我新的 seq2seq 教程什么时候发布吗?

看起来与 tf 1.2 同时,因为我们将依赖一些新的
该版本的功能。

2017 年 5 月 4 日晚上 9:16,“njuzrs” [email protected]写道:

@ebrevdo https://github.com/ebrevdo我在运行时遇到同样的错误
tensorflow1.1 网站上的 sequence_to_sequence 模型。 我已经尝试过
使用“重用”参数但失败。 你能告诉我什么时候新的 seq2seq
教程会出吗?


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-299366774
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtim8_kFTM7-SsXQAA-Ar0dfhHMGT0Zks5r2qKngaJpZM4MWl4f
.

@ebrevdo我也面临同样的问题,无法继续使用 seq2seq。 如果您能让我们/我知道新教程的可能日期,那将非常有帮助。
非常感谢你的帮助。

使用pip install tensorflow==1.0 (Tensorflow 1.0)安装对我有用(翻译教程)。

我有版本 1.1.0-rc2。

TF1.2会解决这个问题吗? 请帮助我如何继续训练模型。 TF 1.0 可以工作,但没有用于多个 GPU 的 devicewrapper api。

张量流 1.1 有同样的问题。 仍在研究解决方案

我尝试了几件事,最后我能够使用 tensorflow 1.1 但必须进行这些更改:(基于上面的 Tshzzz)

删除这个:
multicell = rnn.MultiRNNCell([dropcell]*NLAYERS, state_is_tuple=False)

并添加:
细胞=[]
对于 _ 在范围内(NLAYERS):
细胞 = rnn.DropoutWrapper(tf.contrib.rnn.GRUCell(INTERNALSIZE), input_keep_prob=pkeep)
细胞。追加(细胞)
multicell = rnn.MultiRNNCell(cells, state_is_tuple=False)

@ebrevdo恭喜,TF 1.2 刚刚发布 - 新教程是否也在某个地方发布,还是很快就会发布?

谢谢

我们计划在发布时发布公告。 正在努力。

2017 年 5 月 19 日晚上 7:02,“prashantserai” [email protected]写道:

@ebrevdo https://github.com/ebrevdo恭喜,TF 1.2 刚刚获得
已发布 - 新教程是否也在某处发布或正在发布
很快就会发布?

谢谢


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-302844002
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtim0RWDzNCXk-bIjKSyHLvgFxUvq2lks5r7km7gaJpZM4MWl4f
.

对于使用 tensorflow-gpu==1.1.0 并收到此错误的任何人,通过 pip install tensorflow-gpu==1.0.0 切换到 1.0.0 并不能解决问题,至少对我不起作用。

我在 mac 和 ubuntu 上都遇到了这个问题,并且从源代码编译两次都有效。 所以:
点安装https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.0.0-cp34-cp34m-linux_x86_64.whl

@ajaanbaahu还在等待 tf1.2 新的 seq2seq 教程。

使用pip install tensorflow==1.0对我有用。

对于 tf r1.2,出现 deepcopy 错误。 按顺序列出模型错误 #1050

作为菜鸟,我提出一些我的看法。
下面的代码会使这个类似的错误发生:
(我的一段代码)

lstm_cell = self.LSTMCell(self.num_hidden)
lstm_entity = tf.contrib.rnn.DropoutWrapper(lstm_cell, output_keep_prob=0.5)
layer = tf.contrib.rnn.MultiRNNCell([lstm_entity] * self.num_layer)
__, _ = tf.nn.dynamic_rnn(layer, self.data, dtype=tf.float64)

错误转储如下:

Traceback (most recent call last):
  File "IntentNet.py", line 71, in <module>
    net = Net(data, target, 5, 1)
  File "IntentNet.py", line 45, in __init__
    __, _ = tf.nn.dynamic_rnn(layer, self.data, dtype=tf.float64)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.py", line 553, in dynamic_rnn
    dtype=dtype)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.py", line 720, in _dynamic_rnn_loop
    swap_memory=swap_memory)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 2623, in while_loop
    result = context.BuildLoop(cond, body, loop_vars, shape_invariants)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 2456, in BuildLoop
    pred, body, original_loop_vars, loop_vars, shape_invariants)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/control_flow_ops.py", line 2406, in _BuildLoop
    body_result = body(*packed_vars_for_body)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.py", line 705, in _time_step
    (output, new_state) = call_cell()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/rnn.py", line 691, in <lambda>
    call_cell = lambda: cell(input_t, state)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py", line 953, in __call__
    cur_inp, new_state = cell(cur_inp, cur_state)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py", line 713, in __call__
    output, new_state = self._cell(inputs, state, scope)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py", line 235, in __call__
    with _checked_scope(self, scope or "basic_lstm_cell", reuse=self._reuse):
  File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py", line 77, in _checked_scope
    type(cell).__name__))
ValueError: Attempt to reuse RNNCell <tensorflow.contrib.rnn.python.ops.core_rnn_cell_impl.BasicLSTMCell object at 0x7fe4fc7bd150> with a different variable scope than its first use.  First use of cell was with scope 'rnn/multi_rnn_cell/cell_0/basic_lstm_cell', this attempt is with scope 'rnn/multi_rnn_cell/cell_1/basic_lstm_cell'.  Please create a new instance of the cell if you would like it to use a different set of weights.  If before you were using: MultiRNNCell([BasicLSTMCell(...)] * num_layers), change to: MultiRNNCell([BasicLSTMCell(...) for _ in range(num_layers)]).  If before you were using the same cell instance as both the forward and reverse cell of a bidirectional RNN, simply create two instances (one for forward, one for reverse).  In May 2017, we will start transitioning this cell's behavior to use existing stored weights, if any, when it is called with scope=None (which can lead to silent model degradation, so this error will remain until then.)

但是在我修改之后,它可以工作。

"""
lstm_cell = self.LSTMCell(self.num_hidden)
lstm_entity = tf.contrib.rnn.DropoutWrapper(lstm_cell, output_keep_prob=0.5)
layer = tf.contrib.rnn.MultiRNNCell([lstm_entity] * self.num_layer)
"""
layer = []
for i in range(self.num_layer):
    lstm_cell = self.LSTMCell(self.num_hidden)
    lstm_entity = tf.contrib.rnn.DropoutWrapper(lstm_cell, output_keep_prob=0.5)
    layer.append(lstm_entity)
layer = tf.contrib.rnn.MultiRNNCell(layer)
__, _ = tf.nn.dynamic_rnn(layer, self.data, dtype=tf.float64)

这些变通方法都不适用于 Tensorflow 1.1

我正在使用带有MultiRNNCell单元的seq2seq模型。

我不得不退回到 1.0.1: pip3 install tensorflow==1.0

使用 legacy_seq2seq.rnn_decoder() 时有人遇到这些问题吗?

@oxwsds正如你所说,我将 tf.contrib.legacy_seq2seq.embedding_attention_seq2seq 的输入 args 单元更改为两个不同的单元 {encoder_cells,decoder_cells}。 最后,我得到了 seq2seq 模型。 在 73200 setps 之后,我得到 perplexity 5.54。
然后我运行解码部分,

美国总统是谁?
Qui est le président des États-Unis ?

问题解决了。 谢谢。

@doncat99
似乎 $ seq2seq.py copy.deepcopy(cell)
所以我将seq2seq_model.py中的相关部分更改为

if num_layers > 1:
      cell_enc = tf.contrib.rnn.MultiRNNCell([single_cell() for _ in range(num_layers)])
      cell_dec = tf.contrib.rnn.MultiRNNCell([single_cell() for _ in range(num_layers)])

    # The seq2seq function: we use embedding for the input and attention.
    def seq2seq_f(encoder_inputs, decoder_inputs, do_decode):
      return seq2seq.embedding_attention_seq2seq(
          encoder_inputs,
          decoder_inputs,
          cell_enc,
          cell_dec,
          num_encoder_symbols=source_vocab_size,
          num_decoder_symbols=target_vocab_size,
          embedding_size=size,
          output_projection=output_projection,
          feed_previous=do_decode,
          dtype=dtype)

@supermeatboy82 ,你能分享你的代码吗?

升级到 Tensorflow 1.2.0 并在循环中生成单元而不是列表乘法为我解决了这个问题。

运行 translate.py 时出现 TF1.2 错误,详细信息:
名称:GeForce GTX 1080 Ti
主要:6 次要:1 memoryClockRate (GHz) 1.582
pciBusID 0000:02:00.0
总内存:10.91GiB
可用内存:10.76GiB
2017-06-22 09:15:04.485252:我 tensorflow/core/common_runtime/gpu/gpu_device.cc:961] DMA:0
2017-06-22 09:15:04.485256: 我 tensorflow/core/common_runtime/gpu/gpu_device.cc:971] 0: Y
2017-06-22 09:15:04.485265: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] 创建 TensorFlow 设备 (/gpu:0) -> (设备: 0, 名称: GeForce GTX 1080 Ti, pci总线 ID:0000:02:00.0)
创建 3 层 1024 个单元。
回溯(最近一次通话最后):
文件“translate.py”,第 322 行,在
tf.app.run()
运行中的文件“/home/lscm/opt/anaconda2/lib/python2.7/site-packages/tensorflow/python/platform/app.py”,第 48 行
_sys.exit(main(_sys.argv[:1] + flags_passthrough))
文件“translate.py”,第 319 行,在 main
火车()
文件“translate.py”,第 178 行,在火车中
模型 = create_model(sess, False)
文件“translate.py”,第 136 行,在 create_model
dtype=dtype)
文件“/data/research/github/dl/tensorflow/tensorflow/models/tutorials/rnn/translate/seq2seq_model.py”,第 179 行,在 __init__
softmax_loss_function=softmax_loss_function)
文件“/home/lscm/opt/anaconda2/lib/python2.7/site-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py”,第 1206 行,在 model_with_buckets
解码器输入[:bucket[1]])
文件“/data/research/github/dl/tensorflow/tensorflow/models/tutorials/rnn/translate/seq2seq_model.py”,第 178 行,在
λx, y: seq2seq_f(x, y, False),
文件“/data/research/github/dl/tensorflow/tensorflow/models/tutorials/rnn/translate/seq2seq_model.py”,第 142 行,在 seq2seq_f
dtype=dtype)
文件“/home/lscm/opt/anaconda2/lib/python2.7/site-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py”,第 848 行,在 embedding_attention_seq2seq
encoder_cell = copy.deepcopy(cell)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 174 行,在 deepcopy
y = 复印机(备忘录)
文件“/home/lscm/opt/anaconda2/lib/python2.7/site-packages/tensorflow/python/layers/base.py”,第 476 行,在 __deepcopy__
setattr(result, k, copy.deepcopy(v, memo))
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_list 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 230 行
y.append(deepcopy(a, memo))
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 190 行,在 deepcopy 中
y = _reconstruct(x, rv, 1, memo)
_reconstruct 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 334 行
state = deepcopy(状态,备忘录)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_dict 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 257 行
y[deepcopy(key, memo)] = deepcopy(value, memo)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 190 行,在 deepcopy 中
y = _reconstruct(x, rv, 1, memo)
_reconstruct 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 334 行
state = deepcopy(状态,备忘录)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_dict 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 257 行
y[deepcopy(key, memo)] = deepcopy(value, memo)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 190 行,在 deepcopy 中
y = _reconstruct(x, rv, 1, memo)
_reconstruct 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 334 行
state = deepcopy(状态,备忘录)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_dict 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 257 行
y[deepcopy(key, memo)] = deepcopy(value, memo)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 190 行,在 deepcopy 中
y = _reconstruct(x, rv, 1, memo)
_reconstruct 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 334 行
state = deepcopy(状态,备忘录)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_dict 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 257 行
y[deepcopy(key, memo)] = deepcopy(value, memo)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_dict 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 257 行
y[deepcopy(key, memo)] = deepcopy(value, memo)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_list 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 230 行
y.append(deepcopy(a, memo))
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 190 行,在 deepcopy 中
y = _reconstruct(x, rv, 1, memo)
_reconstruct 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 334 行
state = deepcopy(状态,备忘录)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_dict 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 257 行
y[deepcopy(key, memo)] = deepcopy(value, memo)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 190 行,在 deepcopy 中
y = _reconstruct(x, rv, 1, memo)
_reconstruct 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 334 行
state = deepcopy(状态,备忘录)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_dict 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 257 行
y[deepcopy(key, memo)] = deepcopy(value, memo)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 190 行,在 deepcopy 中
y = _reconstruct(x, rv, 1, memo)
_reconstruct 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 334 行
state = deepcopy(状态,备忘录)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_dict 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 257 行
y[deepcopy(key, memo)] = deepcopy(value, memo)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_list 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 230 行
y.append(deepcopy(a, memo))
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_tuple 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 237 行
y.append(deepcopy(a, memo))
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_dict 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 257 行
y[deepcopy(key, memo)] = deepcopy(value, memo)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 190 行,在 deepcopy 中
y = _reconstruct(x, rv, 1, memo)
_reconstruct 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 334 行
state = deepcopy(状态,备忘录)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 163 行,在 deepcopy 中
y = 复印机(x,备忘录)
_deepcopy_dict 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 257 行
y[deepcopy(key, memo)] = deepcopy(value, memo)
文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 190 行,在 deepcopy 中
y = _reconstruct(x, rv, 1, memo)
_reconstruct 中的文件“/home/lscm/opt/anaconda2/lib/python2.7/copy.py”,第 343 行
y.__dict__.update(状态)
AttributeError:“NoneType”对象没有属性“更新”

在教程的翻译模型中运行self_test() embedding_attention_seq2seq() $ 中的copy.deepcopy(cell)导致的错误。
我尝试在 $ Seq2SeqModel $ 中更改seq2seq_f()中的代码,如下所示:

    def seq2seq_f(encoder_inputs, decoder_inputs, do_decode=False):
        tmp_cell = copy.deepcopy(cell) #new
        return tf.contrib.legacy_seq2seq.embedding_attention_seq2seq(
            encoder_inputs,
            decoder_inputs,
            tmp_cell, #new
            num_encoder_symbols=source_vocab_size,
            num_decoder_symbols=target_vocab_size,
            embedding_size=size,
            output_projection=output_projection,
            feed_previous=do_decode,
            dtype=dtype)

那么现在就没有错误了。
但作为一个菜鸟,我不知道这里的代码是否像以前一样工作,而且似乎这些变化使模型运行得更慢。

我想更新我将 tensorflow 降级到 1.0.0 (tensorflow-GPU) 并且它对我有用的每个人。 模型按预期运行。 我假设 1.0.0 的 CPU 版本应该按预期运行? 或者?。
谢谢 :)

大家好,不知道大家是否还对它感兴趣,但我发现问题与将作为参数传递的单元格复制到embedding_attention_seq2seq函数的操作有关。 这是因为编码器和解码器都使用相同的单元定义。 我认为本教程已被弃用,因为它使用带有分桶的 seq2seq 模型,而不是动态 seq2seq。 但是,我正在粘贴一个有效的修改函数。 该函数在文件tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py中更新。

谢谢,
法比奥

```!蟒蛇
def embedding_attention_seq2seq(encoder_inputs,
解码器输入,
enc_cell,
dec_cell,
num_encoder_symbols,
num_decoder_symbols,
嵌入尺寸,
num_heads=1,
output_projection=无,
feed_previous=假,
dtype=无,
范围=无,
初始状态注意=假):
"""使用注意力嵌入序列到序列模型。

该模型首先通过新创建的嵌入(形状为
[num_encoder_symbols x input_size])。 然后它运行一个 RNN 进行编码
将 encoder_inputs 嵌入到状态向量中。 它保留了这个的输出
RNN 在每一步中使用以供以后注意。 接下来,它嵌入decoder_inputs
由另一个新创建的嵌入(形状为 [num_decoder_symbols x
输入尺寸])。 然后它运行注意力解码器,用最后一个初始化
编码器状态,在嵌入式解码器输入上并关注编码器输出。

警告:当 output_projection 为 None 时,注意向量的大小
并且变量将与 num_decoder_symbols 成比例,可以很大。

参数:
encoder_inputs:形状为 [batch_size] 的一维 int32 张量列表。
解码器输入:形状为 [batch_size] 的一维 int32 张量列表。
单元格:tf.nn.rnn_cell.RNNCell 定义单元格函数和大小。
num_encoder_symbols:整数; 编码器端的符号数。
num_decoder_symbols:整数; 解码器端的符号数。
embedding_size:整数,每个符号的嵌入向量的长度。
num_heads:从 attention_states 读取的注意力头数。
output_projection:无或一对(W,B)输出投影权重和
偏见; W 具有形状 [output_size x num_decoder_symbols] 并且 B 具有
形状 [num_decoder_symbols]; 如果提供且 feed_previous=True,则每个
馈送先前的输出将首先乘以 W 并添加 B。
feed_previous:布尔或标量布尔张量; 如果为真,则只有第一个
将使用decoder_inputs(“GO”符号),以及所有其他解码器
输入将取自先前的输出(如在 embedding_rnn_decoder 中)。
如果为 False,decoder_inputs 按给定的方式使用(标准解码器情况)。
dtype:初始 RNN 状态的 dtype(默认值:tf.float32)。
范围:创建的子图的变量范围; 默认为
“embedding_attention_seq2seq”。
initial_state_attention:如果为 False(默认),则初始注意力为零。
如果为 True,则从初始状态和注意力初始化注意力
状态。

回报:
形式为 (outputs, state) 的元组,其中:
输出:与二维张量的decoder_inputs 长度相同的列表
包含生成的形状 [batch_size x num_decoder_symbols]
输出。
state:每个解码器单元在最后时间步的状态。
它是一个形状为 [batch_size x cell.state_size] 的 2D 张量。
"""
与 variable_scope.variable_scope(
范围或“embedding_attention_seq2seq”,dtype=dtype)作为范围:
dtype = scope.dtype
# 编码器。

encoder_cell = enc_cell

encoder_cell = core_rnn_cell.EmbeddingWrapper(
    encoder_cell,
    embedding_classes=num_encoder_symbols,
    embedding_size=embedding_size)
encoder_outputs, encoder_state = rnn.static_rnn(
    encoder_cell, encoder_inputs, dtype=dtype)

# First calculate a concatenation of encoder outputs to put attention on.
top_states = [
    array_ops.reshape(e, [-1, 1, encoder_cell.output_size]) for e in encoder_outputs
]
attention_states = array_ops.concat(top_states, 1)

# Decoder.
output_size = None
if output_projection is None:
  dec_cell = core_rnn_cell.OutputProjectionWrapper(dec_cell, num_decoder_symbols)
  output_size = num_decoder_symbols

if isinstance(feed_previous, bool):
  return embedding_attention_decoder(
      decoder_inputs,
      encoder_state,
      attention_states,
      dec_cell,
      num_decoder_symbols,
      embedding_size,
      num_heads=num_heads,
      output_size=output_size,
      output_projection=output_projection,
      feed_previous=feed_previous,
      initial_state_attention=initial_state_attention)

# If feed_previous is a Tensor, we construct 2 graphs and use cond.
def decoder(feed_previous_bool):
  reuse = None if feed_previous_bool else True
  with variable_scope.variable_scope(
      variable_scope.get_variable_scope(), reuse=reuse):
    outputs, state = embedding_attention_decoder(
        decoder_inputs,
        encoder_state,
        attention_states,
        dec_cell,
        num_decoder_symbols,
        embedding_size,
        num_heads=num_heads,
        output_size=output_size,
        output_projection=output_projection,
        feed_previous=feed_previous_bool,
        update_embedding_for_previous=False,
        initial_state_attention=initial_state_attention)
    state_list = [state]
    if nest.is_sequence(state):
      state_list = nest.flatten(state)
    return outputs + state_list

outputs_and_state = control_flow_ops.cond(feed_previous,
                                          lambda: decoder(True),
                                          lambda: decoder(False))
outputs_len = len(decoder_inputs)  # Outputs length same as decoder inputs.
state_list = outputs_and_state[outputs_len:]
state = state_list[0]
if nest.is_sequence(encoder_state):
  state = nest.pack_sequence_as(
      structure=encoder_state, flat_sequence=state_list)
return outputs_and_state[:outputs_len], state

```

@fabiofumarola谢谢你的功能。 看起来真的很有帮助。 我还看到该教程已被弃用。 我仍在等待官方教程发布。 看起来你已经使用了新的 api。 您是否有任何代码可以查找以开始对新 api 进行编码?
任何帮助都将不胜感激。 再一次感谢你 :)

@syw2014你的问题解决了吗?

@w268wang还没有,还在等待其他解决方案,不过@Miopas的评论可以试试,我正在尝试@fabiofumarola的解决方案

它说TypeError: embedding_attention_seq2seq() missing 1 required positional argument: 'dec_cell'
使用@fabiofumarola发布的更新后。 你们能帮帮我吗?

是的,因为我提出的更新要求您更改
embedding_attention_seq2seq 函数。 如果你去你的源文件
tensorflow release 你可以改变你自己的方法定义。

2017 年 7 月 2 日星期日 18:15,sachinh35 [email protected] trote

它说 TypeError: embedding_attention_seq2seq() missing 1 required
位置参数:'dec_cell'


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-312500996
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABepUEc3W8m5CVDQGnCLu4dcJVFwwLDZks5sJ8IOgaJpZM4MWl4f
.

>

从移动版 Gmail 发送

是的,我做了同样的事情。 我在 tensorflow 版本中更改了 seq2seq.py 文件中的函数。 我仍然遇到同样的错误。 该函数还有一个参数吗?

是的,现在在您的代码中,您需要指定 rnn_cells。 一个用于编码器
另一个用于解码器。

2017 年 7 月 2 日星期日 20:54,fabio fumarola [email protected]写道:

是的

2017 年 7 月 2 日星期日 18:50,sachinh35 [email protected]写道:

是的,我做了同样的事情。 我更改了 seq2seq.py 文件中的函数
张量流发布。 我仍然遇到同样的错误。 有没有
函数的更多参数?


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-312503106
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABepUOXTQC_mzLuhcwW0iZRVkLmmr8yIks5sJ8pugaJpZM4MWl4f
.

>

从移动版 Gmail 发送

我对此完全陌生。 也许这是一个非常基本的问题,但你能说出在这段代码中作为解码器单元传递的参数吗? 我正在尝试使用自己的数据集开发 seq2seq,如 tensorflow 教程中所示。

`
从 __future__ 导入 absolute_import
从 __future__ 进口部门
从 __future__ 导入 print_function

随机导入

将 numpy 导入为 np
from Six.moves import xrange # pylint: disable=redefined-builtin
将张量流导入为 tf

导入 data_utils

类 Seq2SeqModel(对象):
def __init__(self,
source_vocab_size,
target_vocab_size,
水桶,
尺寸,
层数,
max_gradient_norm,
批量大小,
学习率,
learning_rate_decay_factor,
使用_lstm=假,
num_samples=512,
forward_only=假,
dtype=tf.float32):

self.source_vocab_size = source_vocab_size
self.target_vocab_size = target_vocab_size
self.buckets = buckets
self.batch_size = batch_size
self.learning_rate = tf.Variable(
    float(learning_rate), trainable=False, dtype=dtype)
self.learning_rate_decay_op = self.learning_rate.assign(
    self.learning_rate * learning_rate_decay_factor)
self.global_step = tf.Variable(0, trainable=False)


output_projection = None
softmax_loss_function = None

if num_samples > 0 and num_samples < self.target_vocab_size:
  w_t = tf.get_variable("proj_w", [self.target_vocab_size, size], dtype=dtype)
  w = tf.transpose(w_t)
  b = tf.get_variable("proj_b", [self.target_vocab_size], dtype=dtype)
  output_projection = (w, b)

  def sampled_loss(labels, inputs):
    labels = tf.reshape(labels, [-1, 1])

    local_w_t = tf.cast(w_t, tf.float32)
    local_b = tf.cast(b, tf.float32)
    local_inputs = tf.cast(inputs, tf.float32)
    return tf.cast(
        tf.nn.sampled_softmax_loss(local_w_t, local_b, local_inputs, labels,
                                   num_samples, self.target_vocab_size),
        dtype)
  softmax_loss_function = sampled_loss


def single_cell():
  return tf.nn.rnn_cell.GRUCell(size)
if use_lstm:
  def single_cell():
    return tf.nn.rnn_cell.BasicLSTMCell(size)
cell = single_cell()
if num_layers > 1:
  cell = tf.nn.rnn_cell.MultiRNNCell([single_cell() for _ in range(num_layers)])


def seq2seq_f(encoder_inputs, decoder_inputs, do_decode):
  return tf.contrib.legacy_seq2seq.embedding_attention_seq2seq(
      encoder_inputs,
      decoder_inputs,
      cell,
      num_encoder_symbols=source_vocab_size,
      num_decoder_symbols=target_vocab_size,
      embedding_size=size,
      output_projection=output_projection,
      feed_previous=do_decode,
      dtype=dtype)


self.encoder_inputs = []
self.decoder_inputs = []
self.target_weights = []
for i in xrange(buckets[-1][0]):  # Last bucket is the biggest one.
  self.encoder_inputs.append(tf.placeholder(tf.int32, shape=[None],
                                            name="encoder{0}".format(i)))
for i in xrange(buckets[-1][1] + 1):
  self.decoder_inputs.append(tf.placeholder(tf.int32, shape=[None],
                                            name="decoder{0}".format(i)))
  self.target_weights.append(tf.placeholder(dtype, shape=[None],
                                            name="weight{0}".format(i)))

# Our targets are decoder inputs shifted by one.
targets = [self.decoder_inputs[i + 1]
           for i in xrange(len(self.decoder_inputs) - 1)]

# Training outputs and losses.
if forward_only:
  self.outputs, self.losses = tf.contrib.legacy_seq2seq.model_with_buckets(
      self.encoder_inputs, self.decoder_inputs, targets,
      self.target_weights, buckets, lambda x, y: seq2seq_f(x, y, True),
      softmax_loss_function=softmax_loss_function)
  # If we use output projection, we need to project outputs for decoding.
  if output_projection is not None:
    for b in xrange(len(buckets)):
      self.outputs[b] = [
          tf.matmul(output, output_projection[0]) + output_projection[1]
          for output in self.outputs[b]
      ]
else:
  self.outputs, self.losses = tf.contrib.legacy_seq2seq.model_with_buckets(
      self.encoder_inputs, self.decoder_inputs, targets,
      self.target_weights, buckets,
      lambda x, y: seq2seq_f(x, y, False),
      softmax_loss_function=softmax_loss_function)

# Gradients and SGD update operation for training the model.
params = tf.trainable_variables()
if not forward_only:
  self.gradient_norms = []
  self.updates = []
  opt = tf.train.GradientDescentOptimizer(self.learning_rate)
  for b in xrange(len(buckets)):
    gradients = tf.gradients(self.losses[b], params)
    clipped_gradients, norm = tf.clip_by_global_norm(gradients,
                                                     max_gradient_norm)
    self.gradient_norms.append(norm)
    self.updates.append(opt.apply_gradients(
        zip(clipped_gradients, params), global_step=self.global_step))

self.saver = tf.train.Saver(tf.global_variables())

def step(self, session, encoder_inputs, decoder_inputs, target_weights,
bucket_id,forward_only):

# Check if the sizes match.
encoder_size, decoder_size = self.buckets[bucket_id]
if len(encoder_inputs) != encoder_size:
  raise ValueError("Encoder length must be equal to the one in bucket,"
                   " %d != %d." % (len(encoder_inputs), encoder_size))
if len(decoder_inputs) != decoder_size:
  raise ValueError("Decoder length must be equal to the one in bucket,"
                   " %d != %d." % (len(decoder_inputs), decoder_size))
if len(target_weights) != decoder_size:
  raise ValueError("Weights length must be equal to the one in bucket,"
                   " %d != %d." % (len(target_weights), decoder_size))

# Input feed: encoder inputs, decoder inputs, target_weights, as provided.
input_feed = {}
for l in xrange(encoder_size):
  input_feed[self.encoder_inputs[l].name] = encoder_inputs[l]
for l in xrange(decoder_size):
  input_feed[self.decoder_inputs[l].name] = decoder_inputs[l]
  input_feed[self.target_weights[l].name] = target_weights[l]

# Since our targets are decoder inputs shifted by one, we need one more.
last_target = self.decoder_inputs[decoder_size].name
input_feed[last_target] = np.zeros([self.batch_size], dtype=np.int32)

# Output feed: depends on whether we do a backward step or not.
if not forward_only:
  output_feed = [self.updates[bucket_id],  # Update Op that does SGD.
                 self.gradient_norms[bucket_id],  # Gradient norm.
                 self.losses[bucket_id]]  # Loss for this batch.
else:
  output_feed = [self.losses[bucket_id]]  # Loss for this batch.
  for l in xrange(decoder_size):  # Output logits.
    output_feed.append(self.outputs[bucket_id][l])

outputs = session.run(output_feed, input_feed)
if not forward_only:
  return outputs[1], outputs[2], None  # Gradient norm, loss, no outputs.
else:
  return None, outputs[0], outputs[1:]  # No gradient norm, loss, outputs.

def get_batch(self, data, bucket_id):

encoder_size, decoder_size = self.buckets[bucket_id]
encoder_inputs, decoder_inputs = [], []

# Get a random batch of encoder and decoder inputs from data,
# pad them if needed, reverse encoder inputs and add GO to decoder.
for _ in xrange(self.batch_size):
  encoder_input, decoder_input = random.choice(data[bucket_id])

  # Encoder inputs are padded and then reversed.
  encoder_pad = [data_utils.PAD_ID] * (encoder_size - len(encoder_input))
  encoder_inputs.append(list(reversed(encoder_input + encoder_pad)))

  # Decoder inputs get an extra "GO" symbol, and are padded then.
  decoder_pad_size = decoder_size - len(decoder_input) - 1
  decoder_inputs.append([data_utils.GO_ID] + decoder_input +
                        [data_utils.PAD_ID] * decoder_pad_size)

# Now we create batch-major vectors from the data selected above.
batch_encoder_inputs, batch_decoder_inputs, batch_weights = [], [], []

# Batch encoder inputs are just re-indexed encoder_inputs.
for length_idx in xrange(encoder_size):
  batch_encoder_inputs.append(
      np.array([encoder_inputs[batch_idx][length_idx]
                for batch_idx in xrange(self.batch_size)], dtype=np.int32))

# Batch decoder inputs are re-indexed decoder_inputs, we create weights.
for length_idx in xrange(decoder_size):
  batch_decoder_inputs.append(
      np.array([decoder_inputs[batch_idx][length_idx]
                for batch_idx in xrange(self.batch_size)], dtype=np.int32))

  # Create target_weights to be 0 for targets that are padding.
  batch_weight = np.ones(self.batch_size, dtype=np.float32)
  for batch_idx in xrange(self.batch_size):
    # We set weight to 0 if the corresponding target is a PAD symbol.
    # The corresponding target is decoder_input shifted by 1 forward.
    if length_idx < decoder_size - 1:
      target = decoder_inputs[batch_idx][length_idx + 1]
    if length_idx == decoder_size - 1 or target == data_utils.PAD_ID:
      batch_weight[batch_idx] = 0.0
  batch_weights.append(batch_weight)
return batch_encoder_inputs, batch_decoder_inputs, batch_weights`

这是堆栈溢出的好问题。

2017 年 7 月 3 日上午 8:46,“sachinh35” [email protected]写道:

我对此完全陌生。 也许这是一个非常基本的问题,但你能
告诉在此代码中要作为解码器单元传递的参数是什么? 我是
尝试使用自己的 tensorflow 教程开发 seq2seq
数据集。
`# 版权所有 2015 TensorFlow 作者。 版权所有。
根据 Apache 许可证 2.0 版(“许可证”)获得许可; 您可以
除非遵守许可,否则不得使用此文件。 您可以获得一个
许可证副本位于http://www.apache.org/licenses/LICENSE-2.0除非
适用法律要求或书面同意,分发的软件
根据许可按“原样”分发,不提供任何保证
或任何明示或暗示的条件。 请参阅许可证
管理权限和限制的特定语言

执照。 ==================================================== ==========

"""具有注意机制的序列到序列模型。"""

未来导入 absolute_import
来自未来进口部门
未来导入 print_function

随机导入

将 numpy 导入为 np
from Six.moves import xrange # pylint: disable=redefined-builtin
将张量流导入为 tf

导入 data_utils

类 Seq2SeqModel(对象):
"""具有注意力和多个桶的序列到序列模型。

这个类实现了一个多层循环神经网络作为编码器,
和一个基于注意力的解码器。 这与中描述的模型相同
这篇论文: http ://arxiv.org/abs/1412.7449 - 请在那里寻找
细节,
或进入 seq2seq 库以实现完整的模型实现。
除了 LSTM 单元之外,此类还允许使用 GRU 单元,并且
采样 softmax 来处理大的输出词汇量。 单层
该模型的版本,但带有双向编码器,在
http://arxiv.org/abs/1409.0473
下一篇论文的第 3 节描述了采样的 softmax。
http://arxiv.org/abs/1412.2007
"""

定义初始化(自我,
source_vocab_size,
target_vocab_size,
水桶,
尺寸,
层数,
max_gradient_norm,
批量大小,
学习率,
learning_rate_decay_factor,
使用_lstm=假,
num_samples=512,
forward_only=假,
dtype=tf.float32):
"""创建模型。

参数:
source_vocab_size:源词汇的大小。
target_vocab_size:目标词汇的大小。
buckets:对 (I, O) 的列表,其中 I 指定最大输入长度
将在该存储桶中处理,并且 O 指定最大输出
长度。 输入长于 I 或输出的训练实例
比 O 长的将被推到下一个桶并相应地填充。
我们假设列表已排序,例如 [(2, 4), (8, 16)]。
size:模型每一层的单元数。
num_layers:模型中的层数。
max_gradient_norm:梯度将被剪裁到最大程度。
batch_size:训练期间使用的批次大小;
模型构建独立于batch_size,所以可以
如果方便的话,在初始化后改变,例如,为了解码。
learning_rate:开始的学习率。
learning_rate_decay_factor:在需要时将学习率衰减这么多。
use_lstm:如果为真,我们使用 LSTM 单元而不是 GRU 单元。
num_samples:采样 softmax 的样本数。
forward_only:如果设置,我们不会在模型中构造反向传递。
dtype:用于存储内部变量的数据类型。
"""
self.source_vocab_size = source_vocab_size
self.target_vocab_size = target_vocab_size
self.buckets = 桶
self.batch_size = batch_size
self.learning_rate = tf.Variable(
浮动(学习率),可训练=假,dtype=dtype)
self.learning_rate_decay_op = self.learning_rate.assign(
self.learning_rate * learning_rate_decay_factor)
self.global_step = tf.Variable(0, trainable=False)

如果我们使用采样的 softmax,我们需要一个输出投影。

output_projection = 无
softmax_loss_function = 无

只有当我们采样的词汇量小于词汇量时,采样的 softmax 才有意义。

如果 num_samples > 0 且 num_samples < self.target_vocab_size:
w_t = tf.get_variable("proj_w", [self.target_vocab_size, size], dtype=dtype)
w = tf.转置(w_t)
b = tf.get_variable("proj_b", [self.target_vocab_size], dtype=dtype)
output_projection = (w, b)

def sampled_loss(标签,输入):
标签 = tf.reshape(标签, [-1, 1])
# 我们需要使用 32 位浮点数来计算 sampled_softmax_loss
# 避免数值不稳定。
local_w_t = tf.cast(w_t, tf.float32)
local_b = tf.cast(b, tf.float32)
local_inputs = tf.cast(输入,tf.float32)
返回 tf.cast(
tf.nn.sampled_softmax_loss(local_w_t,local_b,local_inputs,标签,
num_samples, self.target_vocab_size),
类型)
softmax_loss_function = sampled_loss

为我们的 RNN 创建内部多层单元。

定义单细胞():
返回 tf.nn.rnn_cell.GRUCell(大小)
如果使用_lstm:
定义单细胞():
返回 tf.nn.rnn_cell.BasicLSTMCell(大小)
细胞 = 单细胞()
如果 num_layers > 1:
cell = tf.nn.rnn_cell.MultiRNNCell([single_cell() for _ in range(num_layers)])

seq2seq 函数:我们使用嵌入作为输入和注意力。

def seq2seq_f(encoder_inputs, decoder_inputs, do_decode):
返回 tf.contrib.legacy_seq2seq.embedding_attention_seq2seq(
编码器输入,
解码器输入,
细胞,
num_encoder_symbols=source_vocab_size,
num_decoder_symbols=target_vocab_size,
嵌入尺寸=尺寸,
输出投影=输出投影,
feed_previous=do_decode,
dtype=dtype)

输入的提要。

self.encoder_inputs = []
self.decoder_inputs = []
self.target_weights = []
for i in xrange(buckets[-1][0]): # 最后一个桶是最大的。
self.encoder_inputs.append(tf.placeholder(tf.int32, shape=[None],
name="编码器{0}".format(i)))
对于 xrange(buckets[-1][1] + 1) 中的 i:
self.decoder_inputs.append(tf.placeholder(tf.int32, shape=[None],
name="解码器{0}".format(i)))
self.target_weights.append(tf.placeholder(dtype, shape=[None],
name="weight{0}".format(i)))

我们的目标是移位一的解码器输入。

目标 = [self.decoder_inputs[i + 1]
对于我在 xrange(len(self.decoder_inputs) - 1)]

培训输出和损失。

如果 forward_only:
self.outputs, self.losses = tf.contrib.legacy_seq2seq.model_with_buckets(
self.encoder_inputs,self.decoder_inputs,目标,
self.target_weights, buckets, lambda x, y: seq2seq_f(x, y, True),
softmax_loss_function=softmax_loss_function)
# 如果我们使用输出投影,我们需要投影输出以进行解码。
如果 output_projection 不是无:
对于 xrange(len(buckets)) 中的 b:
self.outputs[b] = [
tf.matmul(输出, output_projection[0]) + output_projection[1]
用于 self.outputs[b] 中的输出
]
别的:
self.outputs, self.losses = tf.contrib.legacy_seq2seq.model_with_buckets(
self.encoder_inputs,self.decoder_inputs,目标,
self.target_weights,桶,
λx, y: seq2seq_f(x, y, False),
softmax_loss_function=softmax_loss_function)

用于训练模型的梯度和 SGD 更新操作。

参数 = tf.trainable_variables()
如果不是 forward_only:
self.gradient_norms = []
自我更新 = []
opt = tf.train.GradientDescentOptimizer(self.learning_rate)
对于 xrange(len(buckets)) 中的 b:
梯度 = tf.gradients(self.losses[b], params)
clipped_gradients, norm = tf.clip_by_global_norm(gradients,
max_gradient_norm)
self.gradient_norms.append(norm)
self.updates.append(opt.apply_gradients(
zip(clipped_gradients, params), global_step=self.global_step))

self.saver = tf.train.Saver(tf.global_variables())

def step(self, session, encoder_inputs, decoder_inputs, target_weights,
bucket_id,forward_only):
"""运行模型输入给定输入的步骤。

参数:
session:要使用的张量流会话。
encoder_inputs:作为编码器输入的 numpy int 向量列表。
decoder_inputs:作为解码器输入的 numpy int 向量列表。
target_weights:作为目标权重提供的 numpy 浮点向量列表。
bucket_id:使用模型的哪个桶。
forward_only:是向后还是只向前。

回报:
由梯度范数组成的三元组(如果我们没有向后做,则为 None),
平均困惑度和输出。

提高:
ValueError:如果 encoder_inputs、decoder_inputs 的长度或
target_weights 不同意指定 bucket_id 的桶大小。
"""

检查尺寸是否匹配。

编码器尺寸,解码器尺寸 = self.buckets[bucket_id]
如果 len(encoder_inputs) != encoder_size:
raise ValueError("编码器长度必须等于桶中的长度,"
" %d != %d。" % (len(encoder_inputs), encoder_size))
如果 len(decoder_inputs) != decoder_size:
raise ValueError("解码器长度必须等于桶中的长度,"
" %d != %d。" % (len(decoder_inputs), decoder_size))
如果 len(target_weights) != decoder_size:
raise ValueError("权重长度必须等于桶中的长度,"
" %d != %d。" % (len(target_weights), decoder_size))

输入提要:编码器输入、解码器输入、target_weights,如提供。

input_feed = {}
对于 xrange(encoder_size) 中的 l:
input_feed[self.encoder_inputs[l].name] = encoder_inputs[l]
对于 xrange(decoder_size) 中的 l:
input_feed[self.decoder_inputs[l].name] = decoder_inputs[l]
input_feed[self.target_weights[l].name] = target_weights[l]

由于我们的目标是移位了 1 的解码器输入,我们还需要一个。

last_target = self.decoder_inputs[decoder_size].name
input_feed[last_target] = np.zeros([self.batch_size], dtype=np.int32)

输出提要:取决于我们是否向后退一步。

如果不是 forward_only:
output_feed = [self.updates[bucket_id], # 更新执行 SGD 的操作。
self.gradient_norms[bucket_id], # 梯度范数。
self.losses[bucket_id]] # 这批的损失。
别的:
output_feed = [self.losses[bucket_id]] # 这批的损失。
for l in xrange(decoder_size): # 输出 logits。
output_feed.append(self.outputs[bucket_id][l])

输出 = session.run(output_feed, input_feed)
如果不是 forward_only:
return outputs[1], outputs[2], None # 梯度范数,损失,无输出。
别的:
return None, outputs[0], outputs[1:] # 没有梯度范数,损失,输出。

def get_batch(self, data, bucket_id):
"""从指定的bucket中随机获取一批数据,准备step。

要在 step(..) 中提供数据,它必须是批处理主要向量的列表,而
此处的数据包含单个长度主要的情况。 所以这个的主要逻辑
功能是将数据案例重新索引为正确的格式以供馈送。

参数:
数据:大小为 len(self.buckets) 的元组,其中每个元素包含
我们用来创建批次的输入和输出数据对列表。
bucket_id:整数,要为哪个桶获取批次。

回报:
三元组(encoder_inputs、decoder_inputs、target_weights)
具有适当格式的构造批处理,以便稍后调用 step(...)。
"""
编码器尺寸,解码器尺寸 = self.buckets[bucket_id]
编码器输入,解码器输入 = [],[]

从数据中获取随机批次的编码器和解码器输入,

如果需要,填充它们,反向编码器输入并将 GO 添加到解码器。

对于 xrange 中的 _(self.batch_size):
编码器输入,解码器输入 = random.choice(data[bucket_id])

# 编码器输入被填充然后反转。
encoder_pad = [data_utils.PAD_ID] * (encoder_size - len(encoder_input))
encoder_inputs.append(list(reversed(encoder_input + encoder_pad)))

# 解码器输入得到一个额外的“GO”符号,然后被填充。
解码器垫尺寸 = 解码器尺寸 - 长度(解码器输入) - 1
decoder_inputs.append([data_utils.GO_ID] + decoder_input +
[data_utils.PAD_ID] * decoder_pad_size)

现在我们从上面选择的数据创建批量主要向量。

batch_encoder_inputs,batch_decoder_inputs,batch_weights = [],[],[]

批量编码器输入只是重新索引的编码器输入。

对于 xrange(encoder_size) 中的 length_idx:
batch_encoder_inputs.append(
np.array([encoder_inputs[batch_idx][length_idx]
对于 xrange(self.batch_size)] 中的 batch_idx,dtype=np.int32))

批量解码器输入是重新索引的解码器输入,我们创建权重。

对于 xrange(decoder_size) 中的 length_idx:
batch_decoder_inputs.append(
np.array([decoder_inputs[batch_idx][length_idx]
对于 xrange(self.batch_size)] 中的 batch_idx,dtype=np.int32))

# 为填充的目标创建 target_weights 为 0。
batch_weight = np.ones(self.batch_size, dtype=np.float32)
对于 xrange(self.batch_size) 中的 batch_idx:
# 如果对应的目标是 PAD 符号,我们将权重设置为 0。
# 对应的目标是前移1的decoder_input。
如果 length_idx < 解码器大小 - 1:
目标 = 解码器输入[batch_idx][length_idx + 1]
如果 length_idx == decoder_size - 1 或 target == data_utils.PAD_ID:
批处理权重[batch_idx] = 0.0
batch_weights.append(batch_weight)
返回 batch_encoder_inputs、batch_decoder_inputs、batch_weights`


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-312679587
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtim0l5UMHHtbL1sz7meXserV8NVS7cks5sKQzXgaJpZM4MWl4f
.

好的! 不过谢谢! :)

@ebrevdo关于 seq2seq 使用新 api 的新教程何时发布有任何更新吗?
谢谢你。 惊人的工作!

是的,正在等待新教程……很高兴知道它是否计划很快发布…… @ebrevdo

试图在内核测试中获取代码并使用遗留的 seq2seq 改进波束搜索,但这具有挑战性......

我们期待接下来的一周!

2017 年 7 月 3 日上午 10:16,“prashantserai” [email protected]写道:

是的,正在等待新的教程……很高兴知道它是否是
计划很快发布.. @ebrevdo
https://github.com/ebrevdo

尝试在内核测试中获取代码并使用
遗留的 seq2seq,但它似乎具有挑战性......


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-312697274
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtim45-HTuQrIRDhphqqHjqkKOKTe53ks5sKSHYgaJpZM4MWl4f
.

嗨,大家好,

对此问题的任何更新,我在 tensorflow 1.1-gpu for mac os x 上都遇到了同样的情况

@tshi1983
我在 ubuntu 的 tensorflow 1.1-gpu 上遇到了同样的问题。
我升级到 tf 1.2。 它仍然不起作用。
然后我在文件中更改函数 embedding_attention_seq2seq
张量流/contrib/legacy_seq2seq/python/ops/seq2seq.py
到上面@fabiofumarola建议的那个。
现在它开始训练。 我还没有测试解码。

将单元格定义的代码移动到 seq2seq_f 中:

def seq2seq_f(encoder_inputs, decoder_inputs, do_decode):
      def single_cell():
        return tf.contrib.rnn.GRUCell(size)
      if use_lstm:
        def single_cell():
          return tf.contrib.rnn.BasicLSTMCell(size)
      cell = single_cell()
      if num_layers > 1:
        cell = tf.contrib.rnn.MultiRNNCell([single_cell() for _ in range(num_layers)])
      return tf.contrib.legacy_seq2seq.embedding_attention_seq2seq(
      ...
      )

然后“python translate.py --data_dir data/--train_dir checkpoint/--size=256 --num_layers=2 --steps_per_checkpoint=50”就可以工作了。

@huxuanlai它有效! 至少它现在正在训练,谢谢!

@huxuanlai也为我工作。

我收到了相同的AttributeError: 'NoneType' object has no attribute 'update'但有tf.contrib.legacy_seq2seq.model_with_buckets 。 我在 ubuntu 16.04 lts 上运行 tf 1.2.1 (GPU)。

这似乎仅在我有超过 1 个存储桶时才会发生。

完整追溯:

Traceback (most recent call last):
  File "chatbot.py", line 262, in <module>
    main()
  File "chatbot.py", line 257, in main
    train()
  File "chatbot.py", line 138, in train
    model.build_graph()
  File "/home/jkarimi91/Projects/cs20/code/hw/a3/model.py", line 134, in build_graph
    self._create_loss()
  File "/home/jkarimi91/Projects/cs20/code/hw/a3/model.py", line 102, in _create_loss
    softmax_loss_function=self.softmax_loss_function)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/site-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 1206, in model_with_buckets
    decoder_inputs[:bucket[1]])
  File "/home/jkarimi91/Projects/cs20/code/hw/a3/model.py", line 101, in <lambda>
    lambda x, y: _seq2seq_f(x, y, False),
  File "/home/jkarimi91/Projects/cs20/code/hw/a3/model.py", line 76, in _seq2seq_f
    feed_previous=do_decode)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/site-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 848, in embedding_attention_seq2seq
    encoder_cell = copy.deepcopy(cell)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 174, in deepcopy
    y = copier(memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/site-packages/tensorflow/python/layers/base.py", line 476, in __deepcopy__
    setattr(result, k, copy.deepcopy(v, memo))
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 230, in _deepcopy_list
    y.append(deepcopy(a, memo))
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 190, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 334, in _reconstruct
    state = deepcopy(state, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 257, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 190, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 334, in _reconstruct
    state = deepcopy(state, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 257, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 190, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 334, in _reconstruct
    state = deepcopy(state, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 257, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 190, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 334, in _reconstruct
    state = deepcopy(state, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 257, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 257, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 230, in _deepcopy_list
    y.append(deepcopy(a, memo))
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 190, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 334, in _reconstruct
    state = deepcopy(state, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 257, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 190, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 334, in _reconstruct
    state = deepcopy(state, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 257, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 190, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 334, in _reconstruct
    state = deepcopy(state, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 257, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 230, in _deepcopy_list
    y.append(deepcopy(a, memo))
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 237, in _deepcopy_tuple
    y.append(deepcopy(a, memo))
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 257, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 190, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 334, in _reconstruct
    state = deepcopy(state, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 163, in deepcopy
    y = copier(x, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 257, in _deepcopy_dict
    y[deepcopy(key, memo)] = deepcopy(value, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 190, in deepcopy
    y = _reconstruct(x, rv, 1, memo)
  File "/home/jkarimi91/Apps/anaconda2/envs/tf/lib/python2.7/copy.py", line 343, in _reconstruct
    y.__dict__.update(state)
AttributeError: 'NoneType' object has no attribute 'update'

@Tshzzz @jtubert
thx,您的解决方案对我有用。 我的 tf 版本是 1.1.0。

我从:

    lstm_cell = tf.contrib.rnn.BasicLSTMCell(HIDDEN_SIZE, state_is_tuple=True)
    cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(NUM_LAYERS)])
    output, _ = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)  

到:

    cells=[]
    for _ in range(NUM_LAYERS):
        cell = tf.contrib.rnn.BasicLSTMCell(HIDDEN_SIZE, state_is_tuple=True)
        cells.append(cell)
    multicell = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True)
    output, _ = tf.nn.dynamic_rnn(multicell, X, dtype=tf.float32)

这仍然没有解决,尝试了所有可能的解决方案,在这个线程和 stackoverflow 中提到的,它不适用于 tensorflow 1.3 或 1.2 或 1.1

我面临这个错误:
TypeError: embedding_attention_seq2seq() missing 1 required positional argument: 'dec_cell'

错误指向 seq2seq_model.py 中的此函数,即 seq2seq_model.py 中的第 142 行:

def seq2seq_f(encoder_inputs, decoder_inputs, do_decode): return tf.contrib.legacy_seq2seq.embedding_attention_seq2seq( encoder_inputs, decoder_inputs, cell, num_encoder_symbols=source_vocab_size, num_decoder_symbols=target_vocab_size, embedding_size=size, output_projection=output_projection, feed_previous=do_decode, dtype=dtype)

遇到此错误并设法解决此问题的任何人,请帮助我纠正此问题。

ValueError:尝试重用RNNCell与第一次使用不同的变量范围。 第一次使用单元格是在范围 'rnn/multi_rnn_cell/cell_0/gru_cell' 中,这次尝试是在范围 'rnn/multi_rnn_cell/cell_1/gru_cell' 中。 如果您希望它使用一组不同的权重,请创建一个新的单元实例。 如果在使用之前:MultiRNNCell([GRUCell(...)] * num_layers),请更改为:MultiRNNCell([GRUCell(...) for _ in range(num_layers)])。 如果在您使用相同的单元实例作为双向 RNN 的正向和反向单元之前,只需创建两个实例(一个用于正向,一个用于反向)。 在 2017 年 5 月,我们将开始将此单元格的行为转换为使用现有存储的权重(如果有),当它以 scope=None 调用时(这可能导致静默模型退化,因此此错误将一直存在到那时。)

源代码:
从 tensorflow.contrib 导入 rnn
输入 = tf.placeholder(dtype=tf.int32, shape=[None, None], name="inputs")
keep_prob = tf.placeholder(dtype=tf.float32, name="keep_prob")
细胞 = rnn.GRUCell(10)
细胞= rnn.DropoutWrapper(细胞=细胞,input_keep_prob=keep_prob)
cell = rnn.MultiRNNCell([范围内 _ 的单元格 (5)], state_is_tuple=True)

输出,状态 = tf.nn.dynamic_rnn(细胞=细胞,输入=look_up,dtype=tf.float32)
解决方案:
输入 = tf.placeholder(dtype=tf.int32, shape=[None, None], name="inputs")
keep_prob = tf.placeholder(dtype=tf.float32, name="keep_prob")
cell = rnn.MultiRNNCell([rnn.DropoutWrapper(rnn.GRUCell(10), input_keep_prob=keep_prob) for _ in range(5)] , state_is_tuple=True)

你对 tf nightlies 有这个问题吗?

2017 年 10 月 1 日上午 8:34,“周宝华” [email protected]写道:

在带有 ios 的 cpu 上使用 tensorflow 1.1 时,我遇到了同样的问题。


你收到这个是因为你被提到了。
直接回复此邮件,在 GitHub 上查看
https://github.com/tensorflow/tensorflow/issues/8191#issuecomment-333384725
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABtimwOv7vf5vvFXBllbZryjCFwmJcU6ks5sn7DxgaJpZM4MWl4f
.

AttributeError:“NoneType”对象没有属性“更新”

在 tf=1.3

ValueError:尝试重用RNNCell与第一次使用不同的变量范围。 首次使用单元格的范围为“embedding_attention_seq2seq/rnn/multi_rnn_cell/cell_0/gru_cell”,此尝试的范围为“embedding_attention_seq2seq/rnn/multi_rnn_cell/cell_1/gru_cell”。 如果您希望它使用一组不同的权重,请创建一个新的单元实例。 如果在使用之前:MultiRNNCell([GRUCell(...)] * num_layers),请更改为:MultiRNNCell([GRUCell(...) for _ in range(num_layers)])。 如果在您使用相同的单元实例作为双向 RNN 的正向和反向单元之前,只需创建两个实例(一个用于正向,一个用于反向)。 在 2017 年 5 月,我们将开始将此单元格的行为转换为使用现有存储的权重(如果有),当它以 scope=None 调用时(这可能导致静默模型退化,因此此错误将一直存在到那时。)

已经 14 天没有活动,并且分配了awaiting tensorflower标签。 请相应地更新标签和/或状态。

Nagging Awaiting TensorFlower:已经 14 天没有活动并且分配了awaiting tensorflower标签。 请相应地更新标签和/或状态。

解决方案是迁移到更新版本的 TF。 该线程与最初的问题大相径庭。 关闭。

如果您想要即时解决方案,您可以尝试我尝试过的方法:

pip install tensorflow==1.0
问题出在 Tenorflow 1.1 版本上,它对我有用。

此页面是否有帮助?
0 / 5 - 0 等级