Chrome扩展加载TensorFlow模型提示无本地对应模型报错如何解决?
问题原因
- 你对TensorFlow.js的
localstorage://加载协议用法理解错误:该协议仅支持读取通过tf.Model.save('localstorage://xxx')接口存储的模型,TensorFlow.js会按内部约定格式存储模型拓扑、权重元数据等完整信息,你手动将model.json序列化为字符串存入localStorage的结构和TensorFlow.js预期的结构完全不匹配,因此会抛出找不到对应模型的报错。 - 你已经将模型文件放在扩展本地目录下,完全没必要绕
localStorage存储的中间步骤,直接加载扩展内静态资源即可。
推荐解决方案(直接加载扩展本地模型)
该方案无需依赖localStorage,不会触发存储上限问题,稳定性更高。
- 首先在
manifest.json中配置模型文件的可访问权限,示例如下:
如果使用Manifest V3:
{ "web_accessible_resources": [ { "resources": ["model/*"], "matches": ["<all_urls>"] } ] }
如果使用Manifest V2:
{ "web_accessible_resources": ["model/*"] }
注意将
resources路径替换为你实际存放model.json和bin权重文件的目录路径。
- 修改加载代码,通过
chrome.runtime.getURL生成扩展资源的合法访问路径:
async function load_model() { // 替换为你的model.json在扩展目录中的实际相对路径 const modelJsonPath = chrome.runtime.getURL('model/model.json'); const model = await tf.loadLayersModel(modelJsonPath); return model; }
特殊场景方案(必须通过localStorage加载)
如果你的业务场景确实需要先把模型存入localStorage再加载,按如下步骤操作:
// 首次使用:先加载本地模型,再通过TensorFlow.js官方接口存入localStorage async function initAndSaveModel() { const modelJsonPath = chrome.runtime.getURL('model/model.json'); const model = await tf.loadLayersModel(modelJsonPath); await model.save('localstorage://model'); return model; } // 后续加载时才可以使用localstorage协议读取 async function load_model() { const model = await tf.loadLayersModel('localstorage://model'); return model; }
注意:
localStorage通用存储上限为5MB左右,如果你的模型大小超过该上限会导致存储失败,后续加载也会报错,大体积模型不推荐使用该方案。
内容的提问来源于stack exchange,提问作者OKUU
相关产品推荐
相关产品推荐

