在 Tensorflow 中保存和恢复经过训练的模型
在 Tensorflow 中训练模型后,保存和重用它至关重要。以下是有效处理模型存储的方法:
保存训练好的模型(Tensorflow 0.11 及以上版本):
示例代码:
import tensorflow as tf # Prepare input placeholders w1 = tf.placeholder("float", name="w1") w2 = tf.placeholder("float", name="w2") # Define test operation w3 = tf.add(w1, w2) w4 = tf.multiply(w3, tf.Variable(2.0, name="bias"), name="op_to_restore") # Initialize variables and run session sess = tf.Session() sess.run(tf.global_variables_initializer()) # Create saver object saver = tf.train.Saver() # Save the model saver.save(sess, 'my_test_model', global_step=1000)
恢复保存的模型型号:
示例代码:
# Restore model saver = tf.train.import_meta_graph('my_test_model-1000.meta') saver.restore(sess, tf.train.latest_checkpoint('./')) # Get placeholders and feed data w1 = sess.graph.get_tensor_by_name("w1:0") w2 = sess.graph.get_tensor_by_name("w2:0") feed_dict = {w1: 13.0, w2: 17.0} # Run saved operation op_to_restore = sess.graph.get_tensor_by_name("op_to_restore:0") result = sess.run(op_to_restore, feed_dict)
以上是如何在TensorFlow中有效保存和恢复训练好的模型?的详细内容。更多信息请关注PHP中文网其他相关文章!