首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在TensorFlow中编码标签?

如何在TensorFlow中编码标签?
EN

Stack Overflow用户
提问于 2017-02-07 14:35:30
回答 1查看 6.9K关注 0票数 4

我需要将我的字符串标签转换成像0,0,.,1,…0这样的向量。

据我所知,这是一种叫做热向量的东西。

我有10个类,所以有10个不同的字符串标签。

有谁能帮忙做正变换和逆变换吗?

我是tensorflow的新手,所以请善待我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-07 20:44:35

前进方向很容易,因为有tf.one_hot操作:

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

original_indices = tf.constant([1, 5, 3])
depth = tf.constant(10)
one_hot_encoded = tf.one_hot(indices=original_indices, depth=depth)

with tf.Session():
  print(one_hot_encoded.eval())

产出:

代码语言:javascript
运行
复制
[[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  1.  0.  0.  0.  0.]
 [ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]]

与此相反的情况也不算太糟,tf.where可以找到非零指数:

代码语言:javascript
运行
复制
def decode_one_hot(batch_of_vectors):
  """Computes indices for the non-zero entries in batched one-hot vectors.

  Args:
    batch_of_vectors: A Tensor with length-N vectors, having shape [..., N].
  Returns:
    An integer Tensor with shape [...] indicating the index of the non-zero
    value in each vector.
  """
  nonzero_indices = tf.where(tf.not_equal(
      batch_of_vectors, tf.zeros_like(batch_of_vectors)))
  reshaped_nonzero_indices = tf.reshape(
      nonzero_indices[:, -1], tf.shape(batch_of_vectors)[:-1])
  return reshaped_nonzero_indices

with tf.Session():
  print(decode_one_hot(one_hot_encoded).eval())

指纹:

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

https://stackoverflow.com/questions/42092508

复制
相关文章

相似问题

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