首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tensorflow从每行中随机采样

Tensorflow从每行中随机采样
EN

Stack Overflow用户
提问于 2019-07-29 22:57:27
回答 1查看 167关注 0票数 1

假设我有一个形状为(m, n)的张量A,我想从每一行中随机采样k个元素(没有替换),得到一个形状为(m, k)的张量B。如何在tensorflow中做到这一点?

下面是一个例子:

A:[1,2,3,4,5,6,7,8,9,10,11,12]

k:2

B:[1,3,5,6,9,8,12,10]

EN

回答 1

Stack Overflow用户

发布于 2019-07-29 23:39:21

这是实现这一点的一种方法:

代码语言:javascript
复制
import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    tf.random.set_random_seed(0)
    a = tf.constant([[1,2,3], [4,5,6], [7,8,9], [10,11,12]], tf.int32)
    k = tf.constant(2, tf.int32)
    # Tranpose, shuffle, slice, undo transpose
    aT = tf.transpose(a)
    aT_shuff = tf.random.shuffle(aT)
    at_shuff_k = aT_shuff[:k]
    result = tf.transpose(at_shuff_k)
    print(sess.run(result))
    # [[ 3  1]
    #  [ 6  4]
    #  [ 9  7]
    #  [12 10]]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57256418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档