将 tf.string 字符数组转换为 1 热编码 float32 数组的向量



我正在为我的TensorFlow模型编写一种特征工程方法。我正在尝试根据其中的字符将tf.string转换为 1-hot 编码向量。

具体来说,假设我有一个 "UDRLURDL" 的 TF 输入字符串(在我的例子中,每个字符对应于一个方向。我想将该字符串转换为 1-hot 编码的 float32s 向量。我们有 4 个字符 (UDRL(,因此 1-hot 编码输出将是

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

我或多或少没有看到任何对字符串中的单个字符进行操作的 TF 操作。我们可以以某种方式将tf.string视为字符数组并进行此转换吗?

我的最终解决方案(灵感来自@hars(:

  original_string = tf.squeeze(original_string, axis=1)
  split_string = tf.string_split(original_string, delimiter="")
  table = tf.contrib.lookup.index_table_from_tensor(
      mapping=tf.constant(["U", "D", "L", "R"]), num_oov_buckets=0)
  indices = table.lookup(split_string.values)
  embeddings = tf.constant([[1, 0, 0, 0],
                            [0, 1, 0, 0],
                            [0, 0, 1, 0],
                            [0, 0, 0, 1]])
  encoded = tf.nn.embedding_lookup(embeddings, indices)

如果您可以将字符串从"UDRL"转换为"3210"。您可以使用tf.nn.embeddings_lookup执行此操作,如下所示:

embeddings = tf.constant([[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]])
labels = [0,3,1,2]
encode_tensors = tf.nn.embedding_lookup(embeddings,labels)

sess.run(encode_tensors( 的输出:

array([[1, 0, 0, 0],
   [0, 0, 0, 1],
   [0, 1, 0, 0],
   [0, 0, 1, 0]], dtype=int32)

希望这有帮助!

我更喜欢使用一个热而不是embedding_lookup。

import tensorflow as tf
vocabulary = "UDLR"
original_string = "UDLRUDLR"
mapping_characters = tf.string_split([vocabulary], delimiter="")
input_characters = tf.string_split([original_string], delimiter="")
table = tf.contrib.lookup.index_table_from_tensor(
    mapping=mapping_characters.values, default_value=0)
encoded = tf.one_hot(table.lookup(input_characters.values), 
                     len(vocabulary), dtype=tf.int8)
tf.InteractiveSession().as_default()
tf.tables_initializer().run()
print(encoded.eval())

结果:

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

最新更新