<强>一:需重定义神经网络继续训练的方法强>
1。训练代码
进口numpy np 进口tensorflow特遣部队 x_data=https://www.yisu.com/zixun/np.random.rand (100) .astype (np.float32) y_data=x_data * 0.1 + 0.3 重量=tf.Variable (tf.random_uniform ([1], -1.0, 1.0), name=" w ") 偏见=tf.Variable (tf.zeros ([1]), name=" b ") y=重量* x_data +偏见 损失=tf.reduce_mean (tf.square (y-y_data)) #损失 优化器=tf.train.GradientDescentOptimizer (0.5) 火车=optimizer.minimize(亏损) init=tf.global_variables_initializer () 税=tf.Session () sess.run (init) 储蓄者=tf.train.Saver (max_to_keep=0) 一步的范围(10): sess.run(火车) saver.save(税“。/save_mode global_step=一步)#保存 打印(“当前进行:“,步骤)
第一次训练截图:
2。恢复上一次的训练
进口numpy np 进口tensorflow特遣部队 税=tf.Session () 储蓄者=tf.train.import_meta_graph (r 'save_mode - 9.元) saver.restore(税,tf.train.latest_checkpoint (r '/')) 打印(sess.run (w: 0), sess.run (b: 0)) 图=tf.get_default_graph () 重量=graph.get_tensor_by_name (w: 0) 偏见=graph.get_tensor_by_name (b: 0) x_data=https://www.yisu.com/zixun/np.random.rand (100) .astype (np.float32) y_data=x_data * 0.1 + 0.3 y=重量* x_data +偏见 损失=tf.reduce_mean (tf.square (y-y_data)) 优化器=tf.train.GradientDescentOptimizer (0.5) 火车=optimizer.minimize(亏损) 储蓄者=tf.train.Saver (max_to_keep=0) 一步的范围(10): sess.run(火车) saver.save(税,r”。/save_new_mode”, global_step=步骤) 打印(“当前进行:“,一步,”“,sess.run(重量),sess.run(偏见))
<强>使用上次保存下的数据进行继续训练和保存:强>
#最后要提一下的是:
检查点文件
元保存了TensorFlow计算图的结构信息
人数(保存每个变量的取值
指数保存了表
加载恢复时的文件路径名是以检查点文件中的“model_checkpoint_path”值决定的
这个方法需要重新定义神经网络
<强>二:不需要重新定义神经网络的方法:强>
在上面训练的代码中加入:tf.add_to_collection(“名字”,参数)
进口numpy np 进口tensorflow特遣部队 x_data=https://www.yisu.com/zixun/np.random.rand (100) .astype (np.float32) y_data=x_data * 0.1 + 0.3 重量=tf.Variable (tf.random_uniform ([1], -1.0, 1.0), name=" w ") 偏见=tf.Variable (tf.zeros ([1]), name=" b ") y=重量* x_data +偏见 损失=tf.reduce_mean (tf.square (y-y_data)) 优化器=tf.train.GradientDescentOptimizer (0.5) 火车=optimizer.minimize(亏损) tf.add_to_collection (“new_way”、火车) init=tf.global_variables_initializer () 税=tf.Session () sess.run (init) 储蓄者=tf.train.Saver (max_to_keep=0) 一步的范围(10): sess.run(火车) saver.save(税“。/save_mode global_step=步骤) 打印(“当前进行:“,步骤)
在下面的载入代码中加入:tf.get_collection(“名字”),就可以直接使用了
进口numpy np 进口tensorflow特遣部队 税=tf.Session () 储蓄者=tf.train.import_meta_graph (r 'save_mode - 9.元) saver.restore(税,tf.train.latest_checkpoint (r '/')) 打印(sess.run (w: 0), sess.run (b: 0)) 图=tf.get_default_graph () 重量=graph.get_tensor_by_name (w: 0) 偏见=graph.get_tensor_by_name (b: 0) y=tf.get_collection (“new_way”) [0] 储蓄者=tf.train.Saver (max_to_keep=0) 一步的范围(10): sess.run (y) saver.save(税,r”。/save_new_mode”, global_step=步骤) 打印(“当前进行:“,一步,”“,sess.run(重量),sess.run(偏见))
总的来说,下面这种方法好像是要便利一些
以上这篇tensorflow如何继续训练之前保存的模型实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。