Tensorflow:张量二值化 [英] Tensorflow: tensor binarization

查看:38
本文介绍了Tensorflow:张量二值化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以这样一种方式转换这个数据集:每个张量都有给定的大小 n 并且这个新张量的索引 i 处的特征设置为 1当且仅当原始特征中存在 i(模 n).

I want to transform this dataset in such a way that each tensor has a given size n and that a feature at index i of this new tensor is set to 1 if and only if there is a i in the original feature (modulo n).

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

I hope the following example will make things clearer

假设我有一个数据集:

t = tf.constant([
  [0, 3, 4],
  [12, 2 ,4]])
ds = tf.data.Dataset.from_tensors(t)

我想得到(如果 n = 9)

I want to get (if n = 9)

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

我知道如何将模应用于张量,但我不知道如何进行其余的转换谢谢

I know how to apply the modulo to a tensor, but I don't find how to do the rest of the transformation thanks

推荐答案

类似于 tf.one_hot,仅适用于同时多个值.这是一种方法:

That is similar to tf.one_hot, only for multiple values at the same time. Here is a way to do that:

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))

输出:

[[1 0 0 1 1 0 0 0 0]
 [0 0 1 1 1 0 0 0 0]]

这篇关于Tensorflow:张量二值化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆