在 tf.slim 中实施 N-hot 编码

implement N-hot encoding in tf.slim

如何根据tf.int64中索引1实现N-hot编码?输入是包含多个 tf.int64 的张量。 N-hot编码旨在取代tf.slim中的one-hot编码。

one_hot编码实现如下:

def dense_to_one_hot(labels_dense, num_classes):
  """Convert class labels from scalars to one-hot vectors."""
  num_labels = labels_dense.shape[0]
  index_offset = numpy.arange(num_labels) * num_classes
  labels_one_hot = numpy.zeros((num_labels, num_classes))
  labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
  return labels_one_hot

N-not编码表示:19=00010011,编码后的结果为[0,0,0,1,0,0,1,1]。

在下面找到@jdehesa 的替代答案。此版本计算位长度 N 本身(但仅适用于单值张量 - 或包含相同位长度值的张量):

import tensorflow as tf

def logn(x, n):
  numerator = tf.log(x)
  denominator = tf.log(tf.cast(n, dtype=numerator.dtype))
  return numerator / denominator

def count_bits(x):
    return tf.cast((logn(tf.cast(x, dtype=tf.float32), 2)) + 1, dtype=x.dtype)

def n_hot_encode(x):
    """
    Unpack an integer into its variable-length bit representation
    :param x: Int tensor of shape ()
    :return:  Bool tensor of shape (N,) with N = bit length of x
    """
    N = count_bits(x)
    bins = tf.bitwise.left_shift(1, tf.range(N))[::-1]
    x_unpacked = tf.reshape(tf.bitwise.bitwise_and(x, bins), [-1])
    x_bits = tf.cast(x_unpacked, dtype=tf.bool)
    return x_bits

with tf.Session() as sess:
    result = sess.run(n_hot_encode(tf.constant(19)))
    print(result)
    # > [ True False False  True  True]
    result = sess.run(n_hot_encode(tf.constant(255)))
    print(result)
    # > [ True  True  True  True  True  True  True  True]

上一个答案:

使用tf.one_hot()

labels_one_hot = tf.one_hot(labels_dense, num_classes)

这是一个解决方案:

import numpy as np
import tensorflow as tf

def n_hot_encoding(a, n):
    a = tf.convert_to_tensor(a)
    m = 1 << np.arange(n)[::-1]
    shape = np.r_[np.ones(len(a.shape), dtype=int), -1]
    m = m.reshape(shape)
    hits = tf.bitwise.bitwise_and(a[..., tf.newaxis], tf.cast(m, a.dtype))
    return tf.not_equal(hits, 0)


with tf.Graph().as_default(), tf.Session() as sess:
    n_hot = n_hot_encoding([19, 20, 21], 10)
    print(sess.run(tf.cast(n_hot, tf.int32)))

输出:

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

它假设N是一个常规标量(不是TensorFlow值)并且要转换的数组的维数是已知的(每个维的大小可以是动态的,但是a.shape 不应该只是 None)。该函数可以像这样适应仅 TensorFlow 的计算:

import tensorflow as tf

def n_hot_encoding(a, n):
    a = tf.convert_to_tensor(a)
    n = tf.convert_to_tensor(n)
    m = tf.bitwise.left_shift(1, tf.range(n)[::-1])
    shape = tf.concat([tf.ones([tf.rank(a)], dtype=tf.int64), [-1]], axis=0)
    m = tf.reshape(m, shape)
    hits = tf.bitwise.bitwise_and(a[..., tf.newaxis], tf.cast(m, a.dtype))
    return tf.not_equal(hits, 0)

这应该适用于任何输入,但可能会对每个图表做更多的额外工作 运行。