我为TensorFlow模型编写了一种特征工程方法。我正在尝试根据其中的字符将tf.string
转换为1-hot编码的向量。
具体来说,假设我有一个TF输入字符串" UDRLURDL" (在我的例子中,每个字符对应一个方向。)。我想将该字符串转换为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
视为字符数组并进行此转换吗?
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)
答案 0 :(得分:2)
我更喜欢使用一个hot而不是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]]