Tensorflow.js中Cannot read properties of undefined (reading 'predict')报错解决
解决TensorFlow.js模型加载失败导致predict调用报错的问题
问题描述
调用训练好的可回收物体检测模型的model.predict()方法时,持续出现报错:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'predict')
排查确认模型未被正确加载,核心问题出在模型加载的代码逻辑上。
错误原因
原代码中模型加载部分的then回调未返回模型实例,导致model变量最终为undefined:
const model = await tf.loadGraphModel('model/model.json').then(model => { console.log(model); // 缺少return语句,Promise最终返回undefined });
此外,顶层await需要运行环境支持(如ES模块或现代浏览器),若未正确处理也会导致加载失败。
修复方案
1. 修正模型加载逻辑
确保await能获取到模型实例,两种写法任选其一:
// 写法一:直接await加载结果 const model = await tf.loadGraphModel('model/model.json'); console.log(model); // 写法二:保留then并返回模型 const model = await tf.loadGraphModel('model/model.json').then(model => { console.log(model); return model; // 必须返回模型实例 });
2. 包裹async函数(适配非顶层await环境)
若运行环境不支持顶层await,将所有依赖模型的代码包裹在async立即执行函数中:
(async function() { const Result = { 0: "aerosol", 1: "battery", 2: "cardboard", 3: "food can", 4: "glass bottle", 5: "ink cartridge", 6: "magazine", 7: "paper bag", 8: "plastic bag", 9: "plastic bottle", 10: "plastic utensils", 11: "soda can" }; const imageSelector = document.getElementById("image-selector"); const selectedImage = document.getElementById("selected-image"); // 正确加载模型 const model = await tf.loadGraphModel('model/model.json'); console.log(model); imageSelector.addEventListener("change", getUploadImage); function getUploadImage() { const file = this.files[0]; const reader = new FileReader(); reader.addEventListener("load", function () { const dataURL = reader.result; selectedImage.setAttribute("src", dataURL); // 原代码中predictionList未定义,需确保该变量存在或删除此行 // predictionList.innerHTML = ""; }); reader.readAsDataURL(file); } const predictButton = document.getElementById("predictBtn"); const resultList = document.getElementById("list"); predictButton.addEventListener("click", async function () { const image = selectedImage; const pre_image = tf.browser.fromPixels(image, 3) .resizeNearestNeighbor([256, 256]) .expandDims() .toFloat() .reverse(-1); const predict_result = await model.predict(pre_image).data(); console.log(predict_result); const order = Array.from(predict_result) .map(function (p, i) { return { probability: p, className: Result[i] }; }).sort(function (a, b) { return b.probability - a.probability; }).slice(0, 2); resultList.innerHTML = ""; order.forEach(function (p) { resultList.insertAdjacentHTML("beforeend", `<li>${p.className}: ${Math.trunc(p.probability * 100)} %</li>`); }); }); })();
3. 额外检查项
- 确认
model/model.json路径正确,通过浏览器Network面板验证该文件及相关权重文件是否成功加载(状态码200) - 确保已正确引入TensorFlow.js库,例如在HTML中添加:
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.14.0/dist/tf.min.js"></script>
内容的提问来源于stack exchange,提问作者devChrus
相关产品推荐
相关产品推荐

