我试图从张量中随机删除一行。到目前为止我看到的最简单的方法如下(引用 here ):
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
a_vecs = tf.unstack(a, axis=1)
val = tf.constant(1)
del a_vecs[val]
a_new = tf.stack(a_vecs, 1)
我想传递给“del”一个基于张量运算的随机整数。但是当我使用时:
ran = tf.random_uniform((1,), minval=0, maxval=val, dtype=tf.int32)
我返回一个数组,但 del 不接受数组。另外,如果有更简单的方法从数组中删除,请告诉我。
最佳答案
您可以使用您需要的任何尺寸和形状的tf.boolean_mask
。使用 np.random.choice
#your_shape = int or array
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
ran = tf.random_uniform((1,), minval=0, maxval=2, dtype=tf.int32)
a_vecs = tf.unstack(a, axis=1)
rm = np.random.choice([True, False], your_shape)
a_new = tf.boolean_mask(a_vecs, rm)
或者您可以使用 np.asscalar
将数组转换为标量,但它需要在 session 中运行。
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
ran = tf.random_uniform((1,), minval=0, maxval=2, dtype=tf.int32)
a_vecs = tf.unstack(a, axis=1)
with tf.Session() as sess:
r = ran.eval()
val = np.asscalar(r)
del a_vecs[val]
a_new = tf.stack(a_vecs, 1)
关于python - 从张量中随机移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54727889/