【问题标题】:Tensorflow preprocessing split string to charsTensorflow预处理将字符串拆分为字符
【发布时间】:2021-12-15 02:56:27
【问题描述】:

我想编写使用TextVectorization 预处理层,但将字符串拆分为字符。

data = tf.constant(
    [
        "The Brain is wider than the Sky",
        "For put them side by side",
        "The one the other will contain",
        "With ease and You beside",
    ]
)
# Instantiate TextVectorization with "int" output_mode
text_vectorizer = preprocessing.TextVectorization(output_mode="int")
# Index the vocabulary via `adapt()`
text_vectorizer.adapt(data)

TextVectorization 类有 split 参数,它可以是一个函数。 在纯 python 上我想写这样的东西:

text_vectorizer = preprocessing.TextVectorization(output_mode="int",split=lambda x:list(x)))

但我应该如何在 TensorFlow 世界中编写它?

【问题讨论】:

    标签: python tensorflow tensorflow2.0 tf.keras


    【解决方案1】:

    尝试使用tf.strings.regex_replace并将每个序列先转换为单个字符串,然后再次应用tf.strings.regex_replace将字符串拆分为字符。接下来,使用tf.strings.strip 删除每个字符串的前导和尾随空格。最后,拆分并返回您的字符串:

    import tensorflow as tf
    
    def split_chars(input_data):
      s = tf.strings.regex_replace(input_data, ' ', '')
      tf.print('Single string --> ', s)
      s = tf.strings.regex_replace(s, '', ' ')
      tf.print('Characters --> ', s)
      s = tf.strings.strip(s)
      tf.print('Stripped --> ', s)
      s = tf.strings.split(s, sep = ' ')
      tf.print('Split --> ', s)
      return s
    
    data = tf.constant(
        [
            "The Brain is wider than the Sky",
            "For put them side by side",
            "The one the other will contain",
            "With ease and You beside",
        ]
    )
    input_text_processor = tf.keras.layers.TextVectorization(split = split_chars)
    
    input_text_processor.adapt(data)
    tf.print(f"Vocabulary --> {input_text_processor.get_vocabulary()}")
    
    Single string -->  ["thebrainiswiderthanthesky" "forputthemsidebyside" "theonetheotherwillcontain" "witheaseandyoubeside"]
    Characters -->  [" t h e b r a i n i s w i d e r t h a n t h e s k y " " f o r p u t t h e m s i d e b y s i d e " " t h e o n e t h e o t h e r w i l l c o n t a i n " " w i t h e a s e a n d y o u b e s i d e "]
    Stripped -->  ["t h e b r a i n i s w i d e r t h a n t h e s k y" "f o r p u t t h e m s i d e b y s i d e" "t h e o n e t h e o t h e r w i l l c o n t a i n" "w i t h e a s e a n d y o u b e s i d e"]
    Split -->  [['t', 'h', 'e', ..., 's', 'k', 'y'], ['f', 'o', 'r', ..., 'i', 'd', 'e'], ['t', 'h', 'e', ..., 'a', 'i', 'n'], ['w', 'i', 't', ..., 'i', 'd', 'e']]
    Vocabulary --> ['', '[UNK]', 'e', 't', 'i', 'h', 's', 'n', 'o', 'd', 'a', 'r', 'y', 'w', 'b', 'u', 'l', 'p', 'm', 'k', 'f', 'c']
    

    【讨论】:

    • 这是解决问题的方法,但不是解决方案。它与基本的split_chars 略有不同:例如,您丢失了有关“”等的信息。我找到了解决方案:有一个 tf.strings.unicode_split 函数,它只是将字符串拆分为字符。
    • 但我的问题仍然存在 - 有很多小型变压器操作可以在 tf.直接
    • 感谢您的反馈,您的问题到底是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2012-02-22
    • 2019-04-16
    相关资源
    最近更新 更多