【问题标题】:Tokeniser from Keras to Tensorflowjs从 Keras 到 Tensorflow Js 的分词器
【发布时间】:2021-01-21 17:29:17
【问题描述】:

我知道这可能看起来重复,但我无法找到适合我的解决方案。或者也许我只需要一个完整的例子。

问题是:我想实现一个网页来预测输入文本的类别,这要归功于预训练的模型。 我有对应于 tensorflowjs 模型和两者的 json 文件

  • tokeniser.json(由 Keras Tokenizer().to_json() 保存
  • vocab.json(另存为this question对应tokenizer.word_index

现在,我知道如何使用 tensorflowjs 的异步功能将模型加载到 javascript 对象中。 我怎样才能为标记器做同样的事情? 以及我如何标记(在导入的标记器下)输入文本?

======================== 澄清 ================ ===========

我的json文件的例子可以在theselinks找到

我尝试了以下代码

// loadVocab function to get the vocabulary from json.
async function loadVocab() {
  var word2index = await JSON.parse(await JSON.stringify(vocabPath));
  return word2index;
}

其中vocabPath 是包含上述网址的字符串。

在我的脚本结束时,我调用了一个函数init()

async function init(){
    model = await loadModel();
    word2index = await loadVocab();
    console.log(word2index["the"]); // I expect 1
}

但我当然得到了undefined,因为我猜它会将 url 的真实字符串作为 json,而不是那个 url 的 json。

有什么想法吗?

【问题讨论】:

  • 是关于如何加载json文件的问题吗?
  • 更多的是关于如何将 json 文件加载为 tensorflowjs 对象。
  • 这个问题对我来说有点不清楚。您能否举例说明您拥有的 json 以及加载后期望的结果类型?
  • 我有一个简单的 json,其中包含一个“字典”单词到索引。我想在javascript中实现一个标记器,这样,给定一个字符串,获取每个单词,进入单词到索引字典并返回与输入文本对应的整数列表

标签: javascript keras tensorflow.js


【解决方案1】:

要像这样加载从 python 中保存的词汇:

import json 
with open( 'word_dict.json' , 'w' ) as file:    
    json.dump( tokenizer.word_index , file )

您必须使用这样的 AJAX 调用加载 JSON:

function getJSON(url) {
    var resp ;
    var xmlHttp ;

    resp  = '' ;
    xmlHttp = new XMLHttpRequest();

    if(xmlHttp != null)
    {
        xmlHttp.open( "GET", url, false );
        xmlHttp.send( null );
        resp = xmlHttp.responseText;
    }

    return resp ;
}

var vocab = JSON.parse(getJSON('./word_dict.json'));

python 方面在这里解释得很好:Converting Python Keras NLP Model to Tensorflowjs

还有一个与下一步相关的问题,如何对其进行矢量化:Tensorflow.js tokenizer

【讨论】:

  • 非常感谢。我会尝试这个解决方案。我给你最好的答案,但是,我也会发布我的答案,因为我以一种可能不那么“纯粹”但更综合的方式解决了问题。
【解决方案2】:

我最终通过以下方式解决了这个问题,

let vocabPath = '/url/to/my/vocab.json';

async function loadVocab() {
    let vocab = await (await fetch(vocabPath)).json();
    return vocab;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 2019-06-04
    • 2019-04-30
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多