[英]Saving h5 model by relative path - Keras tensorflow
Hey to my beloved community.嘿,我亲爱的社区。
How do we save a model to a relative file path using tensorflow embedded keras?我们如何使用 tensorflow 嵌入式 keras 将模型保存到相对文件路径?
model.save('/models/model.h5')
I tried:我试过:
'./models/'
'/models/'
'models/'
Neither seems to work and I always end up with:两者似乎都不起作用,我总是以:
InvalidArgumentError (see above for traceback): Failed to create a NewWriteableFile:
I don't want to provide an absolute path as it might change dynamically.我不想提供绝对路径,因为它可能会动态变化。
The error might be related to one of the reasons below:该错误可能与以下原因之一有关:
Do the specified folder exists?指定的文件夹是否存在? If not, you should make it using:如果没有,你应该使用:
import os os.makedirs('models/') # Creating a directory model.save('models/model.h5') # Saving model
Do you have permission to write to that folder?您是否有权写入该文件夹? If you are using Unix-based system (ie Mac OS or Linux), then you can check it by:如果您使用的是基于 Unix 的系统(即 Mac OS 或 Linux),那么您可以通过以下方式进行检查:
ls -l models/
A friendly tutorial on Unix file permission can be found here .可以在此处找到有关 Unix 文件权限的友好教程。
Does your path contains special symbols?您的路径是否包含特殊符号? (ie ~
for user's folder) you will need to use os.path.expanduser
to resolve the path. (即~
用户文件夹)您需要使用os.path.expanduser
来解析路径。
Adding to what @FalconUA mentioned, Here I am providing an example of saving a tensorflow.keras
model to be saved in model_path
folder under current directory.添加@FalconUA 提到的内容,这里我提供了一个保存tensorflow.keras
模型的示例,该模型将保存在当前目录下的model_path
文件夹中。 This works well with most recent tensorflow ( TF2.0.0rc2
).这适用于最新的 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))
Here is a simple example of a function that responds to the question.这是一个响应问题的函数的简单示例。 If the folder does not exist create a new one else use the existing folder.如果该文件夹不存在,则创建一个新文件夹,否则使用现有文件夹。
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.