How to extract n 1-D tensors from a given two-dimensional tensor?

I have a two-dimensional tensor:

a = [[6, 5, 4], [3, 2, 1], [1, 2, 3], [4, 5, 6], [7, 8, 1], [5, 2, 6] ]

I want to extract K 1-D tensors randomly and not repeat . Then, combining them with another two-dimensional tensor b:

b = [5, 2, 6], [3, 2, 1], [6, 5, 4]

I do not find any functions that perform this, so I implement it as below:

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

but the result has a repeating 1-D tensor, such as:

bb = [[5, 2, 6], [3, 2, 1], [5, 2, 6]]

Can someone help me fix this?

+4
source share
1 answer

, , 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)
+2

All Articles