Tensorflow.js令牌生成器

时间:2018-08-02 22:40:12

标签: javascript machine-learning tensorflow.js natural-language-processing

我是机器学习和Tensorflow的新手,因为我不了解python,所以我决定使用javascript版本(可能更像是包装器)。

问题是我试图建立一个处理自然语言的模型。因此,第一步是将文本标记化,以便将数据提供给模型。我做了很多研究,但其中大多数使用的是tensorflow的python版本,其使用的方法类似:tf.keras.preprocessing.text.Tokenizer,但在tensorflow.js中找不到类似的方法。我陷入了这一步,不知道如何将文本传输到可以提供给模型的向量。请帮忙:)

3 个答案:

答案 0 :(得分:7)

要将文本转换为矢量,有很多方法可以使用,所有方法都取决于用例。最直观的一种是使用术语频率的术语,即给定语料库的词汇量(所有可能的单词),所有文本文档都将表示为矢量,其中每个条目代表单词在文本文档中的出现。

有了这个词汇:

["machine", "learning", "is", "a", "new", "field", "in", "computer", "science"]

以下文字:

["machine", "is", "a", "field", "machine", "is", "is"] 

将被转换为该向量:

[2, 0, 3, 1, 0, 1, 0, 0, 0] 

该技术的缺点之一是向量中可能有很多0,其大小与语料库的词汇量相同。这就是为什么还有其他技术的原因。然而,bag of words经常被提及。并且使用tf.idf

的版本略有不同

const vocabulary = ["machine", "learning", "is", "a", "new", "field", "in", "computer", "science"]
const text = ["machine", "is", "a", "field", "machine", "is", "is"] 
const parse = (t) => vocabulary.map((w, i) => t.reduce((a, b) => b === w ? ++a : a , 0))
console.log(parse(text))

还有以下module可能会帮助您实现所需的目标

答案 1 :(得分:2)

好吧,我遇到了这个问题,并通过以下步骤对其进行了处理:

  1. tokenizer.fit_on_texts([data])之后,在您的python代码中打印tokenizer.word_index
  2. 将word_index输出复制并保存为json文件。
  3. 引用此json对象以生成标记化的单词,如下所示: function getTokenisedWord(seedWord) { const _token = word2index[seedWord.toLowerCase()] return tf.tensor1d([_token]) }
  4. 提供模型: const seedWordToken = getTokenisedWord('Hello'); model.predict(seedWordToken).data().then(predictions => { const resultIdx = tf.argMax(predictions).dataSync()[0]; console.log('Predicted Word ::', index2word[resultIdx]); })
  5. index2wordword2index json对象的反向映射。

答案 2 :(得分:0)

const vocabulary = ["machine", "learning", "is", "a", "new", "field", "in", "computer", "science"]
const text = ["machine", "is", "a", "field", "machine", "is", "is"] 
const parse = (t) => vocabulary.map((w, i) => t.reduce((a, b) => b === w ? ++a : a , 0))
console.log(parse(text))