我有一个形状为[None, None]
、类型为string
的张量占位符。例如,它看起来像这样
[[“你好”,“世界”],[“美国人”,“人民”]]
。
现在我想将此 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"]]]
。
由于每个单词的字符数不同,因此新的张量应该用空格填充小单词。 tensorflow 中有没有办法解决这个问题?
最佳答案
运行
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
是所需的输出。
关于tensorflow - 在 tensorflow 中将单词剥离为其组成字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54274941/