【问题标题】:Generate ngram (bigram or trigram) in Keras / Tensorflow在 Keras / Tensorflow 中生成 ngram(bigram 或 trigram)
【发布时间】:2022-01-28 17:28:03
【问题描述】:

我想从一系列标记中生成生成 n-grams

bigram:: "1 3 4 5" --> { (1,3), (3,4), (4,5) }

搜索后发现this线程使用:

def find_ngrams(input_list, n):
  return zip(*[input_list[i:] for i in range(n)])

如果我在训练期间使用这段代码,我认为它会影响性能。所以我在寻找更好的选择。

【问题讨论】:

    标签: machine-learning tensorflow deep-learning keras


    【解决方案1】:

    如果需要生成字符串格式的bigram

    import tensorflow as tf
    
    tf.enable_eager_execution()
    
    sentence = ['this is example sentence']
    x = tf.string_split(sentence).values[:-1] + ' ' + tf.string_split(sentence).values[1:]
    
    # tf.Tensor([b'this is' b'is example' b'example sentence'], shape=(3,), dtype=string)
    

    你也可以使用tensorflow-transform来生成ngram。

    import tensorflow_transform as tft
    
    tft.ngrams(tensor, (1,2), " ")
    

    注意:在 2019 年 1 月 22 日之前,tensorflow-transform 仅支持 python 2。

    【讨论】:

    • 这些 tf-transform 操作的额外好处是它们由核心图形操作驱动,因此它们可以在 python 之外工作!至少我的小实验 w/ngrams...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2017-12-21
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    相关资源
    最近更新 更多