【问题标题】:TensorflowException: Invalid GraphDef (TensorFlow 2.0)TensorflowException:无效的 GraphDef (TensorFlow 2.0)
【发布时间】:2020-05-21 00:12:29
【问题描述】:

我正在使用 tf.keras.models.Sequential 构建模型并将其保存为包含 saved_model.pb 文件的 SavedModel 对象。然后,该模型将用于使用 ML.net 的 C# 服务。

这是代码(从文档中提取和改编)

(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
train_labels = train_labels[:1000]
test_labels = test_labels[:1000]
train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0
test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0

# Define a simple sequential model
def create_model():
    model = tf.keras.models.Sequential([
    keras.layers.Dense(512, activation='relu', input_shape=(784,)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(10)
    ])

    model.compile(optimizer='adam',
                loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
                metrics=['accuracy'])

    return model

# Create a basic model instance
model = create_model()
model.fit(train_images, train_labels, epochs=5)

# Save model
#model.save('/Users/fco/Desktop/saved_model/test.h5', save_format='tf') 
tf.saved_model.save(model, '/Users/fco/Desktop/saved_model')

# Load model
new_model = tf.keras.models.load_model('/Users/fco/Desktop/saved_model')
print(new_model.predict(test_images).shape)

在 ML.NET 中加载 saved_model.pb 文件时,出现以下异常。

TensorflowException: Invalid GraphDef

当我搜索此错误时 - 它引用模型上的冻结重量,但解决方案适用于 TF1。 TF2似乎有更精简的模型保存方法,但我不明白哪里出了问题。

有人知道我错过了什么吗?

【问题讨论】:

    标签: tensorflow keras


    【解决方案1】:

    我不知道您的问题的答案,但您可以将模型保存为 .h5 格式并轻松加载。

    例子:

    使用保存您的模型

    model.save('/content/saved_model.h5')

    并使用加载它

    loaded_model= models.load_model('/content/saved_model.h5')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2018-05-07
      • 1970-01-01
      • 2019-07-27
      • 2016-12-15
      • 1970-01-01
      相关资源
      最近更新 更多