使用 Core API 创建模型时出错

Error when creating a model using Core API

我尝试按照 TensorFlow official site 上的教程创建基于 Core API 的机器学习模型。但我收到以下错误:

Error: Argument 'b' passed to 'matMul' must be a Tensor or TensorLike, but got 'null'

我正在 windows 10 和 tfjs@1.5.2

const tf = require('@tensorflow/tfjs');
const tfcore = require('@tensorflow/tfjs-core')


const w1 = tf.variable(tf.randomNormal([784, 32]));
const b1 = tf.variable(tf.randomNormal([32]));
const w2 = tf.variable(tf.randomNormal([32, 10]));
const b2 = tf.variable(tf.randomNormal([10]));

function model(x) {
  console.log(w1);
  return x.matMul(w1).add(b1).relu().matMul(w2).add(b2).softmax();
}


model(tfcore);

你能帮我解决这个错误吗?

错误说明了一切,您正在将张量乘以 null(第二个参数默认为 null)。

tf.matMul(tensor)

您需要为矩阵乘法提供第二个张量

作为 stated you need to supply two tensors for tf.matMul:

方法一

const a = tf.tensor2d([1, 2], [1, 2]);
const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);

a.matMul(b);

方法2

const a = tf.tensor2d([1, 2], [1, 2]);
const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);

tf.matMul(a, b);

在您的示例中,通过将 tfcore 传递给 model() 您正在使用 方法 2 因此需要将第二个张量传递给 matMul.但是,如果您将张量传递给 model(),它应该像 approach 1.

一样工作