在tensorflow中将单词剥离为其组成字符

时间:2019-01-20 08:59:58

标签: tensorflow tensorflow-hub

我有一个类型为[None, None]的形状为string的张量占位符。例如,它看起来像这样

[["Hello", "World"], ["Amercian", "people"]]

现在,我想将此2D张量转换为3D张量,现在基本上将每个单词剥离为其组成字符。所以输出看起来像 [[["H", "e", "l", "l", "o"], ["W", "o", "r", "l", "d"]], [["A", "m", "e", "r", "i", "c", "a", "n"], ["p", "e", "o", "p", "l", "e"]]]

由于每个单词具有不同数量的字符,因此新的张量应在小单词上填充空格。 张量流中有这种方法吗?

1 个答案:

答案 0 :(得分:0)

此运行

import tensorflow as tf
import tensorflow_transform as tft

input_data = tf.placeholder(shape=[None, None], dtype=tf.string, name="words")
words_flatten = tf.reshape(words, [tf.shape(words)[0] * tf.shape(words)[1]])
words_split = tf.string_split(words_flatten, delimiter="")
ngrams = tft.ngrams(words_split, ngram_range=(1,3), separator="")
tokens= tf.sparse_reset_shape(tf.sparse_fill_empty_rows(ngrams, "")[0])
tokens_dense = tf.reshape(
            tf.sparse_to_dense(tokens.indices, tokens.dense_shape, tokens.values, default_value=""),
            [tf.shape(words)[0], tf.shape(words)[1], -1]
        )

tokens_dense是所需的输出。