[英]Saving h5 model by relative path - Keras tensorflow
嘿,我亲爱的社区。
我们如何使用 tensorflow 嵌入式 keras 将模型保存到相对文件路径?
model.save('/models/model.h5')
我试过:
'./models/'
'/models/'
'models/'
两者似乎都不起作用,我总是以:
InvalidArgumentError (see above for traceback): Failed to create a NewWriteableFile:
我不想提供绝对路径,因为它可能会动态变化。
该错误可能与以下原因之一有关:
指定的文件夹是否存在? 如果没有,你应该使用:
import os os.makedirs('models/') # Creating a directory model.save('models/model.h5') # Saving model
您是否有权写入该文件夹? 如果您使用的是基于 Unix 的系统(即 Mac OS 或 Linux),那么您可以通过以下方式进行检查:
ls -l models/
可以在此处找到有关 Unix 文件权限的友好教程。
您的路径是否包含特殊符号? (即~
用户文件夹)您需要使用os.path.expanduser
来解析路径。
添加@FalconUA 提到的内容,这里我提供了一个保存tensorflow.keras
模型的示例,该模型将保存在当前目录下的model_path
文件夹中。 这适用于最新的 tensorflow ( TF2.0.0rc2
)。
import tensorflow as tf
from tensorflow import keras
mnist = tf.keras.datasets.mnist
#import data
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# create a model
def create_model():
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
# compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
# Create a basic model instance
model=create_model()
model.fit(x_train, y_train, epochs=1)
loss, acc = model.evaluate(x_test, y_test,verbose=1)
print("Original model, accuracy: {:5.2f}%".format(100*acc))
# Save entire model to a HDF5 file
model.save('./model_path/my_model.h5')
# Recreate the exact same model, including weights and optimizer.
new_model = keras.models.load_model('./model_path/my_model.h5')
loss, acc = new_model.evaluate(x_test, y_test)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
这是一个响应问题的函数的简单示例。 如果该文件夹不存在,则创建一个新文件夹,否则使用现有文件夹。
def save_model(path, model):
if not os.path.exists(path):
print('save directories...', flush=True)
os.makedirs(path)
model.save(path + '/handrecognition_model.h5')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.