我有一个2-D张量:
a = [[6,5,4],[3,2,1],[1,2,3],[4,5,6],[7,8,1],[5,2] ,6]]
我想提取K 1-D张量随机和不重复。接下来,将它们与另一个2-D张量b组合:
b = [5,2,6],[3,2,1],[6,5,4]
我没有找到任何这样做的功能,所以我实现它如下:
rand_var_1 = tf.random_crop(a, size=[1, 3], seed=1)
rand_var_2 = tf.random_crop(a, size=[1, 3], seed=2)
rand_var_3 = tf.random_crop(a, size=[1, 3], seed=3)
rand_var_4 = tf.random_crop(a, size=[1, 3], seed=4)
b = tf.concat(0, [rand_var_1, rand_var_2, rand_var_3, rand_var_4])
b_rs = sess.run(b)
print "b_rs:\n",b_rs
但结果有重复的1-D张量,如:
bb = [[5,2,6],[3,2,1],[5,2,6]]
可以请别人帮我解决这个问题吗?
答案 0 :(得分:2)
以下应该可以工作,基本上生成一个数组数组,数组的长度为a
,将它们混洗并使用第一个K
来索引并获取行,
import numpy as np
#Number of samples
K = 3
#Array
a =[[6, 5, 4], [3, 2, 1], [1, 2, 3], [4, 5, 6], [7, 8, 1], [5, 2, 6]]
N = len(a)
#Get an array on size of a, shuffle and take first K to use
#permutation used as suggested by @EelcoHoogendoorn
indices = np.random.permutation(N)
#Take the first k samples
samples = indices[:K]
b = [a[i] for i in samples]
#Print
print('a = ', a)
print('b = ', b)