我想从张量中得到一个随机的次张量,并且形状是固定的。例如, 我需要从左张量得到右张量,每行的索引都是随机的,就像这样:
[[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}))
在这种情况下,它不起作用。谁能告诉我该怎么做?你知道吗
使用^{} 可以这样做:
我通常用numpy库来做这个。你知道吗
然后可以使用以下代码获得所需的一列:
这样,您就得到了所需的随机列作为numpy数组,然后可以将其与tensorflow一起使用,如图所示:
如果您不想永久性地修改“a\u instance”矩阵,请记住在shuffle方法中使用“a\u instance”的副本。你知道吗
相关问题 更多 >
编程相关推荐