如何在没有会话的情况下保存tensorflow ML模型?

时间:2018-10-05 17:29:00

标签: python python-3.x numpy tensorflow

当我查找此问题时,我发现了使用会话变量的解决方案。我没有使用会话变量,所以它们不起作用。我也尝试过tf.keras.models.save_modeltf.keras.models.load_model,但是当我运行load_model时,出现了与无法访问文件有关的错误。

是否有最佳解决方案?

我的错误: KeyError: 0

我的训练代码:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(512, activation=tf.nn.relu),
  tf.keras.layers.Dropout(0.2),
  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)

tf.keras.models.save_model(model,"model.h5",overwrite=True,
  include_optimizer=True)

我的测试代码:

import tensorflow as tf
from tensorflow import keras
from keras.models import load_model
import numpy as np

model = load_model("model.h5")

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

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

plt.figure(figsize=(20,20))
for i in range(25):
  plt.subplot(5,5,i+1)
  plt.xticks([])
  plt.yticks([])
  plt.grid(False)
  plt.imshow(x_test[i])
  plt.xlabel(np.argmax(model.predict(x_test)[i]))  

plt.show()

0 个答案:

没有答案