如何从张量中随机选择元素,并在条件上选择元素?

时间:2019-04-26 15:18:00

标签: python python-3.x tensorflow

我有一个用0和1填充的张量。现在,我想随机选择例如50%的元素等于1。我怎么做? 例如,我有以下张量:

tensor = tf.constant([[0, 0, 1], [0, 1, 0], [1, 1, 0]])

现在,我想随机选择等于1个元素的50%的坐标(在这种情况下,我要从4个元素中选择2个元素)。生成的张量可能如下所示:

[[0, 0, 1], [0, 0, 0], [0, 1, 0]]

1 个答案:

答案 0 :(得分:0)

您可以使用numpy。

import numpy as np

tensor = np.array([0, 1, 0, 1, 0, 1, 0, 1])
percentage = 0.5

ones_indices = np.where(tensor==1)
ones_length = np.shape(ones_indices)[1]
random_indices = np.random.permutation(ones_length)
ones_indices[0][random_indices][:int(ones_length * percentage)]

编辑:使用张量定义,我已经调整了代码:

import numpy as np

tensor = np.array([[0, 0, 1], [0, 1, 0], [1, 1, 0]])
percentage = 0.5

indices = np.where(tensor == 1)
length = np.shape(indices)[1]
random_idx = np.random.permutation(length)
random_idx = random_idx[:int(length * percentage)]
random_indices = (indices[0][random_idx], indices[1][random_idx])
z = np.zeros(np.shape(tensor), dtype=np.int64)
z[random_indices] = 1

# output
z