问题描述
为什么每次运行 keras.Model.save()
都会生成不同的二进制文件,AFAIU,我何时已采取所有必要步骤来完全重现结果甚至二进制文件?
您可以通过在 docker 容器中简单地执行以下脚本来验证这一点。 saved_model.pb
和 variables
目录的内容总是会改变。创建一个容器:docker run --rm --volume=/host/dir/with/script:/workspace -it tensorflow/tensorflow:2.4.1 bash
# Setup environmental variables.
import os
os.environ["TF_DETERMINISTIC_OPS"] = "1"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import numpy as np
import random
import tensorflow as tf
import time
def initialise_seeds(seed):
os.environ["PYTHONHASHSEED"] = str(seed)
random.seed(seed)
np.random.seed(seed)
tf.random.set_seed(seed)
SEED = 42
initialise_seeds(SEED)
if __name__ == '__main__':
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(input_shape=(28,28)),tf.keras.layers.Dense(128,activation='relu'),tf.keras.layers.Dropout(0.2),tf.keras.layers.Dense(10),tf.keras.layers.softmax()
],name="best_ever")
model.compile(
optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(),metrics=['accuracy']
)
model.fit(x_train,y_train,epochs=2)
model.evaluate(x_test,y_test,verbose=2)
# Save the model weights.
ckpt = "/cp-0.ckpt"
model.save_weights(model.name + ckpt)
# Also save keras model.
model.save(model.name)
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
# Include necessary functions.
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS,tf.lite.OpsSet.SELECT_TF_OPS]
tflite_model = converter.convert()
# Save the model.
with open('model.tflite','wb') as f:
f.write(tflite_model)
# Load the TFLite model from disk and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Test model ouput on the same data to ensure correct function.
input_shape = input_details[0]['shape']
input_data = np.ones((input_shape),dtype=np.float32) * 0.5
interpreter.set_tensor(input_details[0]['index'],input_data)
interpreter.invoke()
# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data.shape)
谢谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)