Tensorflowjs 需要 3 个维度,即使我在 Python 中用 2 个维度训练它

Tensorflowjs expects 3 Dimensions, even though I trained it with 2 in Python

我正在尝试测试我在 Python:

中使用异或运算符值训练的模型
x_train = [[1,0],[0,1],[0,0],[1,1]]
x_label = [1,1,0,0]

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(2,1)),
    keras.layers.Dense(8, activation="relu"),
    keras.layers.Dense(2, activation="softmax")
])

model.compile(optimizer="adam", loss="sparse_categorical_crossentropy",metrics=["accuracy"])
model.fit(x_train, x_label, epochs=15)

prediction = model.predict([[5,5]])
print("Prediction: ", np.argmax(prediction[0]))

它在 Python 中工作得很好,但是当我将它转换为 Tensorflow JS 文件时 (model.json),它不再工作了:

tfjs.converters.save_keras_model(model, "test_model")

正如你在上面看到的,我用 input_shape=(2,1) 训练了它。但是当我在 Nodejs 中尝试时,出现错误:

ValueError: Error when checking : expected flatten_input to have 3 dimension(s), but got array with shape [2,1]

我的 JS 代码:

tf.loadLayersModel(model_url).then((model)=>{
        const input = tf.tensor([1,1],[2,1], "int32");
        const prediciton = model.predict(input)
        console.log(prediciton);
        response.send(prediciton);
        return null;
    }).catch((e)=>{
        console.log(e);
    });

谢谢!

tf.tensor([1,1],[2,1])(相当于下面的数组:[[1], [1]]即使在python中也不起作用)。在 python 形状不匹配时,尺寸在最后一个轴上扩展。因此,生成的张量将具有形状 2、1、1,这与期望输入形状 [b, 2, 1].

的输入形状不匹配

但是,由于上述原因,tf.tensor([1,1],[1,2]) 将在 python 中工作。然而,似乎只有当输入张量是 tensor1d 时,广播才在 js 中完成。所以即使这样也行不通。

解决js中的问题,可以只考虑在第一个轴(axis = 0)上展开张量,如下:

tf.tensor([1,1],[1, 2,1], "int32")