使用TensorFlow.js预测时如何解决‘object null is not iterable’错误?
TensorFlow.js预测时出现
TypeError: object null is not iterable的解决方法 问题重现
我在构建序列分类器时按以下流程操作:
- 用TensorFlow.Keras训练模型,通过Python代码转为TFJS格式:
tfjs.converters.save_keras_model(model, './')
- 在JavaScript中通过ES模块加载模型:
import * as tf from '@tensorflow/tfjs'; var model = null; async function loadModel() { model = await tf.loadLayersModel('assets/model/model.json'); console.log('Loaded') } loadModel();
- 编写预测函数:
async function pred() { tens = tf.zeros([batchSize, sentenceLength]); const preds = await model.predict(tens); return preds; }
调用pred()时触发错误:
TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))
错误指向model.predict()行,排查后发现问题出在index.html中的全局脚本引入:
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
移除该行后错误消失。
问题原因
同时使用ES模块导入和CDN全局脚本引入会导致TensorFlow.js的内部命名空间冲突,模型加载后实例出现异常,调用predict方法时触发空对象迭代的错误。
解决方法
确保只使用一种方式引入TensorFlow.js:
- 保留ES模块的
import * as tf from '@tensorflow/tfjs',删除CDN脚本标签; - 或者放弃ES模块导入,仅使用CDN全局脚本,此时代码中不需要
import语句,直接使用全局的tf对象。
内容的提问来源于stack exchange,提问作者Syed Salman
相关产品推荐
相关产品推荐

