gpt4 book ai didi

tensorflow - 将字符串张量转换为小写

转载 作者:行者123 更新时间:2023-12-03 12:42:17 25 4
gpt4 key购买 nike

有没有办法将字符串张量转换为小写,而无需在 session 中进行评估?某种 tf.string_to_lower操作?

更具体地说,我正在从 tfrecords 读取数据。文件,所以我的数据是由张量组成的。然后我想使用 tf.contrib.lookup.index_table_from_*查找数据中单词的索引,我需要它不区分大小写。将数据写入之前降低数据 tfrecords不是一种选择,因为它需要保持原始格式。一种选择是存储原始的和降低的,但如果可能的话,我想避免这种情况。

最佳答案

这是一个使用 tensorflow ops 的实现:

def lowercase(s):
ucons = tf.constant_initializer([chr(i) for i in range(65, 91)])
lcons = tf.constant_initializer([chr(i) for i in range(97, 123)])

upchars = tf.constant(ucons, dtype=tf.string)
lchars = tf.constant(lcons, dtype=tf.string)

upcharslut = tf.contrib.lookup.index_table_from_tensor(mapping=upchars, num_oov_buckets=1, default_value=-1)
splitchars = tf.string_split(tf.reshape(s, [-1]), delimiter="").values
upcharinds = upcharslut.lookup(splitchars)
return tf.reduce_join(tf.map_fn(lambda x: tf.cond(x[0] > 25, lambda: x[1], lambda: lchars[x[0]]), (upcharinds, splitchars), dtype=tf.string))

if __name__ == "__main__":
s = "komoDO DragoN "
sess = tf.Session()
x = lowercase(s)
sess.run(tf.global_variables_initializer())
sess.run(tf.tables_initializer())
print(sess.run([x]))

返回 [b'komodo dragon ']

关于tensorflow - 将字符串张量转换为小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44791932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com