gpt4 book ai didi

Tensorflow - 从不同的文件夹保存和恢复

转载 作者:行者123 更新时间:2023-12-03 09:45:05 25 4
gpt4 key购买 nike

我在 tensorflow 中创建并保存了简单的 nn:

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, [1, 1],name='input_placeholder')
y = tf.placeholder(tf.float32, [1, 1],name='input_placeholder')
W = tf.get_variable('W', [1, 1])
layer = tf.matmul(x, W, name='layer')
loss = tf.subtract(y,layer)
train_step = tf.train.AdagradOptimizer(0.1).minimize(loss, name='train_step')
all_saver = tf.train.Saver()

sess = tf.Session()
sess.run(tf.global_variables_initializer())

x_test = np.zeros((1, 1))
y_test = np.zeros((1, 1))
some_output = sess.run([train_step],feed_dict = {x:x_test,y:y_test})

save_path = r'C:\Temp\tf_exp\save_folder\test'
all_saver.save(sess,save_path)

然后我将 C:\Temp\tf_exp\save_folder\ 中的所有文件移动(完全移动而不是复制)到 C:\Temp\tf_exp\restore_folder .我移动的文件是:

checkpoint
test.data-00000-of-00001
test.index
test.meta

然后我尝试从新位置恢复 nn:

meta_path = r'C:\Temp\tf_exp\restore_folder\test.meta'
checkpoint_path = r'C:\Temp\tf_exp\restore_folder\\'
print(checkpoint_path)
new_all_saver = tf.train.import_meta_graph(meta_path)
sess=tf.Session()
new_all_saver.restore(sess, tf.train.latest_checkpoint(checkpoint_path))
graph = tf.get_default_graph()
layer= graph.get_tensor_by_name('layer:0')
x=graph.get_tensor_by_name('input_placeholder:0')

这是恢复代码生成的错误:

C:\Temp\tf_exp\restore_folder\\
ERROR:tensorflow:Couldn't match files for checkpoint C:\Temp\tf_exp\save_folder\test
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-9af4e683fc4b> in <module>()
5 new_all_saver = tf.train.import_meta_graph(meta_path)
6 sess=tf.Session()
----> 7 new_all_saver.restore(sess, tf.train.latest_checkpoint(checkpoint_path))
8 graph = tf.get_default_graph()
9 layer= graph.get_tensor_by_name('layer:0')

~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\training\saver.py in restore(self, sess, save_path)
1555 return
1556 if save_path is None:
-> 1557 raise ValueError("Can't load save_path when it is None.")
1558 logging.info("Restoring parameters from %s", save_path)
1559 sess.run(self.saver_def.restore_op_name,

ValueError: Can't load save_path when it is None.

如何避免?移动文件的正确方法是什么?

更新:

在我寻找答案时,看起来使用相对路径是可行的方法。但我不确定如何使用相对路径。我应该将 Python 的当前工作目录更改为我保存模型数据的位置吗?

最佳答案

创建tf.train.Saver()时只需添加save_relative_paths=True即可:

# original code: all_saver = tf.train.Saver()
all_saver = tf.train.Saver(save_relative_paths=True)

请引用official doc了解更多详情。

关于Tensorflow - 从不同的文件夹保存和恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47043606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com