【问题标题】:Loading a keras model into tfjs causes input shape mismatch将 keras 模型加载到 tfjs 会导致输入形状不匹配
【发布时间】:2020-06-23 14:32:55
【问题描述】:

我在 Keras 中制作了一个模型并将其保存为 tfjs 模型。我成功地将它导入到我的 js 项目中。但是,由于输入形状错误,我无法在我的 JS 代码中使用该模型。 Keras 模型:

# Python
model = keras.Sequential([keras.layers.Dense(8,
    activation='sigmoid', input_dim=4),
keras.layers.Dense(3, activation='softmax')])
model.compile(optimizer='adam',loss='categorical_crossentropy', 
                  metrics=['accuracy'])
    model.fit(dx, dy, epochs=100, batch_size = 5)

当我在这样的python文件中使用它时,它可以按预期工作,例如:

# Python
model.predict_classes([[5.1, 3.5, 1.4, 0.2]]) # This works

但是当我在 JS 中尝试同样的方法时

// JS
sv = tf.tensor([s1v, s2v, s3v, s4v]) //s1v to s4v are floats
var pred = await model.predict(sv); // This gives an error

给出这个错误:

tfjs@latest:17 Uncaught (in promise) 错误:检查时出错:预期 dense_13_input 的形状为 [null,4],但得到的数组的形状为 [4,1]。

我不断收到同样的错误:

  1. 将 s1v...s4v 单独声明为 tf.scalar 并使用 tf.stack() 将它们堆叠
  2. 将 s1v...s4v 单独声明为 tf.tensor1d 并使用 tf.stack() 堆叠它们
  3. 在单个 tf.tensor1d 中声明 s1...s4v

请帮我解决这个问题...

【问题讨论】:

  • 试试sv = tf.tensor2d([s1v, s2v, s3v, s4v], [1, 4])

标签: javascript tensorflow keras tfjs-node tensorflow-layers


【解决方案1】:

据我所知,这个问题有两个修复方法

  • 为张量添加另一对括号sv = tf.tensor([[s1v, s2v, s3v, s4v]])
  • 将形状指定为第二个参数sv = tf.tensor([s1v, s2v, s3v, s4v], [1, 4])

【讨论】:

  • 添加第二组括号修复它谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-07
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 2020-10-10
  • 2019-01-26
  • 2019-12-12
相关资源
最近更新 更多