You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TensorFlow.js预测时如何解决‘object null is not iterable’错误?

TensorFlow.js预测时出现TypeError: object null is not iterable的解决方法

问题重现

我在构建序列分类器时按以下流程操作:

  1. 用TensorFlow.Keras训练模型,通过Python代码转为TFJS格式:
tfjs.converters.save_keras_model(model, './')
  1. 在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();
  1. 编写预测函数:
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:10:28