如何从张量中得到随机子传感器?

2024-04-25 07:00:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从张量中得到一个随机的次张量,并且形状是固定的。例如, 我需要从左张量得到右张量,每行的索引都是随机的,就像这样:

[[1 4 3]         [[3]     [[4]
 [3 2 1]  ----->  [2]  or  [1] (generate randomly)
 [0 3 4]]         [3]]     [0]]

我试过了tf.切片以及tf.聚集,它不起作用。我试着写一个这样的代码测试用例:

import random
import tensorflow as tf

a = tf.convert_to_tensor([[[1, 4, 3]],
                          [[3, 2, 1]],
                          [[0, 3, 4]]])

T = a.get_shape().as_list()[0]

result_list = []

for i in range(T):
    idx = random.randint(0, 2)  # get a random idx
    result_list.append(a[i][0][idx])

y_hat = tf.reshape(tf.convert_to_tensor(result_list), shape=(T, 1))

with tf.Session() as sess:
    print(sess.run(y_hat))

    # y_hat: [[4]
    #         [1]
    #         [4]]

在这个测试用例中,它起了作用。但在真实环境中,'a'。shape=(无,3),所以
'T=a.get \u shape()。由于\u list()[0]'不是int值,我无法按范围(T)迭代T。 例如:

import random
import tensorflow as tf

a = tf.placeholder(shape=(None, 3), dtype=tf.int32)

result_list = []
T = a.get_shape().as_list()[0]

for i in range(T):
    idx = random.randint(0, 2)  # get a random idx
    result_list.append(a[i][0][idx])

y_hat = tf.reshape(tf.convert_to_tensor(result_list), shape=(T, 1))

with tf.Session() as sess:

    a_instance = [[[1, 4, 3]],
                  [[3, 2, 1]],
                  [[0, 3, 4]]]

    print(sess.run(y_hat, feed_dict={a: a_instance}))

在这种情况下,它不起作用。谁能告诉我该怎么做?你知道吗


Tags: toimportconvertgettfhatas测试用例
2条回答

使用^{}可以这样做:

import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    tf.random.set_random_seed(0)
    a = tf.constant([[1, 4, 3],
                     [3, 2, 1],
                     [0, 3, 4]])
    s = tf.shape(a)
    rows, cols = s[0], s[1]
    # Row indices
    ii = tf.expand_dims(tf.range(rows), 1)
    # Column indices
    jj = tf.random.uniform((rows, 1), 0, cols, dtype=ii.dtype)
    # Gather result
    result = tf.gather_nd(a, tf.stack([ii, jj], axis=-1))
    # Print some results
    print(sess.run(result))
    # [[3]
    #  [2]
    #  [4]]
    print(sess.run(result))
    # [[4]
    #  [1]
    #  [0]]
    print(sess.run(result))
    # [[3]
    #  [2]
    #  [0]]

我通常用numpy库来做这个。你知道吗

import numpy as np

a_instance = np.array([[1,4,3],[3,2,1],[0,3,4]])
a_instance = a_instance.T # transpose the matrix
np.random.shuffle(a_instance) # it performs the shuffle of the rows
a_instance = a_instance.T

然后可以使用以下代码获得所需的一列:

a_column = a_instance[:, 0]

这样,您就得到了所需的随机列作为numpy数组,然后可以将其与tensorflow一起使用,如图所示:

...
print(sess.run(y_hat, feed_dict={a: [a_column.tolist()]}))

如果您不想永久性地修改“a\u instance”矩阵,请记住在shuffle方法中使用“a\u instance”的副本。你知道吗

相关问题 更多 >