【问题标题】:How to iterate over a Tensor in Tensorflow and change its values if necessary?如何迭代 Tensorflow 中的张量并在必要时更改其值?
【发布时间】:2019-03-25 05:50:21
【问题描述】:

假设我在 TensorFlow 中有一个形状为 [600, 11] 的张量。最后(第 11)列的所有元素都为零。我想像这样迭代张量的值:对于每一行,我检查该行的前 10 个元素的最大值是否大于值 X。如果为真,则保持行不变,如果为假,则将行的前 10 个元素设置为零,并使第 11 个元素等于 1。我该怎么做?我的张量的结构如下图所示:

import tensorflow as tf

a = tf.zeros([600, 1], dtype=tf.float32)
b = tf.random.uniform([600,10], minval=0, maxval=1, dtype=tf.float32)
c = tf.concat([b, a], axis=1)

【问题讨论】:

  • 发布的问题似乎根本不包括任何解决问题的尝试。 StackOverflow 希望您首先尝试解决自己的问题,因为您的尝试有助于我们更好地了解您想要什么。请编辑问题以显示您尝试过的内容,以便在最小、完整和可验证的示例中说明您遇到的特定障碍。欲了解更多信息,please see

标签: python-3.x tensorflow


【解决方案1】:

您不能遍历张量,也不能设置单个元素的值。张量是不可变的,因此您总是必须从前一个张量构建一个新的张量。这就是您可以执行您所描述的操作的方法:

import tensorflow as tf

def modify_matrix(matrix, X):
    all_but_last_column = matrix[:, :-1]
    max_per_row = tf.reduce_max(all_but_last_column, axis=1)
    replace = tf.concat([tf.zeros_like(all_but_last_column),
                         tf.ones_like(matrix[:, -1])[:, tf.newaxis]], axis=1)
    mask = max_per_row > X
    return tf.where(mask, matrix, replace)

nums = [list(range(i * 10, (i + 1) * 10)) + [0] for i in range(1, 5)]
print(*nums, sep='\n')
# [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0]
# [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 0]
# [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 0]
# [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 0]
matrix = tf.constant(nums)
X = tf.constant(36, dtype=matrix.dtype)
result = modify_matrix(matrix, X)
print(sess.run(result))
# [[ 0  0  0  0  0  0  0  0  0  0  1]
#  [ 0  0  0  0  0  0  0  0  0  0  1]
#  [30 31 32 33 34 35 36 37 38 39  0]
#  [40 41 42 43 44 45 46 47 48 49  0]]

【讨论】:

  • 非常感谢您的回复。这似乎有效!我还找到了另一种解决方案,如下所示!
【解决方案2】:

我还找到了另一个对我有用的解决方案:

import tensorflow as tf

zeroes = tf.zeros([600, 1], dtype=tf.float32)
ones = tf.ones([600, 1], dtype=tf.float32)
b = tf.random.uniform([600,10], minval=0, maxval=1, dtype=tf.float32)
threshold = tf.constant(0.6, dtype=tf.float32)

check = tf.reduce_max(tf.cast(b > threshold, dtype=tf.float32), axis=1)
last_col = tf.where(check>0, zeroes, ones)
new_b = tf.where(check>0, b, tf.zeros([600, 10], dtype=tf.float32))
new_matrix = tf.concat([new_b, last_col], axis=1) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多