首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tensorflow:张量二值化

Tensorflow:张量二值化
EN

Stack Overflow用户
提问于 2018-11-21 14:37:30
回答 1查看 1.5K关注 0票数 0

我希望以这样的方式来转换这个数据集:每个张量都有一个给定的大小n,并且这个新张量的索引i上的一个特性被设置为1当且仅当原始特征中有一个i (模n)。

我希望下面的例子能让事情变得更清楚

假设我有一个数据集,如:

代码语言:javascript
复制
t = tf.constant([
  [0, 3, 4],
  [12, 2 ,4]])
ds = tf.data.Dataset.from_tensors(t)

我想得到(如果n = 9)

代码语言:javascript
复制
t = tf.constant([
  [1, 0, 0, 1, 1, 0, 0, 0, 0], # index set to 1 are 0, 3 and 4
  [0, 0, 1, 1, 1, 0, 0, 0, 0]]) # index set to 1 are 2, 4, and 12%9 = 3

我知道如何将模应用于张量,但我找不到如何完成其余的转换--谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-21 14:46:51

这与tf.one_hot类似,仅适用于同一时间的多个值。这里有一种方法可以做到:

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

def binarization(t, n):
    # One-hot encoding of each value
    t_1h = tf.one_hot(t % n, n, dtype=tf.bool, on_value=True, off_value=False)
    # Reduce across last dimension of the original tensor
    return tf.cast(tf.reduce_any(t_1h, axis=-2), t.dtype)

# Test
with tf.Graph().as_default(), tf.Session() as sess:
    t = tf.constant([
        [ 0,  3,  4],
        [12,  2,  4]
    ])
    t_m1h = binarization(t, 9)
    print(sess.run(t_m1h))

输出:

代码语言:javascript
复制
[[1 0 0 1 1 0 0 0 0]
 [0 0 1 1 1 0 0 0 0]]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53414433

复制
相关文章

相似问题

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