【问题标题】:the asterisk in tf.gather_nd in python2.7 rise syntax errorpython2.7中tf.gather_nd中的星号上升语法错误
【发布时间】:2020-08-22 14:44:26
【问题描述】:

我使用的是Python2.7,无法更新,而且我有这行代码,在星号处报错,不知道为什么?以及如何解决!

inp = tf.random.uniform(shape=[4, 6, 2], maxval=20, dtype=tf.int32)

out = tf.math.reduce_max(inp, axis=2)
am = tf.math.argmax(out, axis=1)
o = tf.gather_nd(inp, [*enumerate(am)])

此代码是关于使用 TensorFlow 1.14 根据最大​​值从 3D 张量获取 2D 最大张量。如下图所示:

【问题讨论】:

  • 我不明白你想如何从inp 中选择值。在第一个 6x2 子矩阵中,以绿色突出显示第一行,这是包含子矩阵中最大值 (0.824) 的行。但是,在第二个子矩阵中,您突出显示第四行,它不包含子矩阵中的最大值,甚至也不包含任一列中的最大值。你到底需要什么?具有最大值的行,第一列中具有最大值的行,还有什么?
  • 对不起,我在突出显示时出错了,我没有注意到。我想要价值最大的行

标签: python python-2.7 tensorflow


【解决方案1】:

该星号语法在 Python 2 中不可用。它是在 7 年前的 Python 3.5 (PEP 448) 中添加的。

Python 2 的等价物是

o = tf.gather_nd(inp, [(i,j) for (i,j) in enumerate(am)])

但是您真的不应该使用 Python 2 或花时间学习它。如果您需要它来运行旧代码,则不必“更新”现有的 Python 2 安装。如果需要,您可以让 Python 3.8 与 Python 2 并行运行。出于工作原因,我的机器上并排安装了 3.8、3.7、3.6 和 2.7,没有任何问题。

【讨论】:

  • 我收到了这个错误,TypeError: Tensor objects are only iterable when eager execution is enabled。要迭代此张量,请使用 tf.map_fn。你没有注意到我正在开发 TensorFlow 1.14
  • 在这种情况下,您有 2 个选择。使用 Python 3.5 或更高版本,或遵循错误消息中的建议。您确实询问了语法错误。
【解决方案2】:

您问题中的语法错误是explained by BoarGules。对于您要解决的问题,您可以通过以下方式获得您想要的结果:

import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    # In TF 2.x: tf.random.set_seed
    tf.random.set_random_seed(0)
    # Input data
    inp = tf.random.uniform(shape=[4, 6, 2], maxval=100, dtype=tf.int32)

    # Find index of greatest value in last two dimensions
    s = tf.shape(inp)
    inp_res = tf.reshape(inp, [s[0], -1])
    max_idx = tf.math.argmax(inp_res, axis=1, output_type=s.dtype)
    # Get row index dividing by number of columns
    max_row_idx = max_idx // s[2]
    # Get rows with max values
    res = tf.gather_nd(inp, tf.expand_dims(max_row_idx, axis=1), batch_dims=1)
    # Print input and result
    print(*sess.run((inp, res)), sep='\n')

输出:

[[[22 78]
  [75 70]
  [31 10]
  [67  9]
  [70 45]
  [ 5 33]]

 [[82 83]
  [82 81]
  [73 58]
  [18 18]
  [57 11]
  [50 71]]

 [[84 55]
  [80 72]
  [93  1]
  [98 27]
  [36  6]
  [10 95]]

 [[83 24]
  [19  9]
  [46 48]
  [90 87]
  [50 26]
  [55 62]]]
[[22 78]
 [82 83]
 [98 27]
 [90 87]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    相关资源
    最近更新 更多