张量流:张量二值化

2024-04-26 03:19:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

我想得到(如果n=9)

^{pr2}$

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


Tags: 数据fromdatatf方式ds特征事情
1条回答
网友
1楼 · 发布于 2024-04-26 03:19:10

这与^{}类似,只是同时用于多个值。以下是一种方法:

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

输出:

^{pr2}$

相关问题 更多 >