Tensorflowjs需要3维,尽管我在Python中使用了2维

2024-05-23 12:41:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试测试一个模型,我使用Python中的XOR运算符值对其进行了培训:

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);
    });

谢谢大家!


Tags: inputmodellayerstfjstrainactivationpredict
1条回答
网友
1楼 · 发布于 2024-05-23 12:41:31

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

但是tf.tensor([1,1],[1,2])将在python中工作,因为上面提到了这一点。然而,与js相比,只有当输入张量为张量1d时,才能进行广播。所以即使这样也不行

为了解决JS中的问题,可以考虑在第一轴(轴=0)上张量张量:
tf.tensor([1,1],[1, 2,1], "int32")

相关问题 更多 >