【问题标题】:Load saved model in separate file Tensorflow-Keras M1 Mac在单独的文件中加载保存的模型 Tensorflow-Keras M1 Mac
【发布时间】:2021-09-18 21:45:12
【问题描述】:

我正在学习 Sentdex 的教程,但是我尝试从新文件 (run_test.py) 加载我保存的模型并遇到以下错误。

ValueError: Could not find matching function to call loaded from the SavedModel. 
Got:
 Positional arguments (1 total):
  * Tensor("inputs:0", shape=(None, 28, 28), dtype=uint8)
 Keyword arguments: {}

Expected these arguments to match one of the following 1 option(s):

Option 1:
 Positional arguments (1 total):
  * TensorSpec(shape=(None, 28, 28), dtype=tf.float32, name='inputs')
 Keyword arguments: {}

main.py

import tensorflow as tf
import numpy as np

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())  
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) 
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) 
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) 
model.fit(x_train, y_train, epochs=1) # run the training process 3 times

val_loss, val_acc = model.evaluate(x_test, y_test)

model.save('num_reader_basic.model')

run_test.py

import tensorflow as tf
import numpy as np

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

new_model = tf.keras.models.load_model('num_reader_basic.model')
predictions = new_model.predict(x_test)
print(np.argmax(predictions[0]))

在与模型训练文件(main.py)相同的文件中运行加载命令时,它不会导致任何错误,只有在从单独的文件中运行时才会导致错误。我的第二个文件 (run_test.py) 中是否有任何错误,或者是否有其他方法可以从新文件中加载已保存的模型?

【问题讨论】:

  • 在运行您的代码示例时,我无法重现该错误。您使用的是哪个 TensorFlow 版本?我发现了类似的问题:stackoverflow.com/questions/58575586/…github.com/tensorflow/tensorflow/issues/37339这可能与TF版本有关。
  • 是的,我认为这与我的 tensorflow 有关,因为我在 M1 芯片上运行。由于 Python for M1 附带 2 个架构,因此架构会导致问题。感谢您的建议,如果您不指出,我可能不会查看我的程序版本。

标签: python tensorflow keras apple-m1


【解决方案1】:

问题不是来自代码本身,而是由 M1 架构和 TensorFlow 安装引起的。请注意,原来的 TensorFlow 不能很好地与新芯片配合使用,因此需要单独安装版本。

有很多方法可以安装 TensorFlow 的 arm64 版本,但这个 one 适合我。

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 2021-03-08
    • 2020-12-24
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多