首页 > 代码库 > tensorflow教程:变量创建、初始化、保存和加载

tensorflow教程:变量创建、初始化、保存和加载

变量保存到文件

import tensorflow as tf
import numpy as np
# Create two variables.
x_data = http://www.mamicode.com/np.float32([1,2,3,4,5,6,7,8,9,0])
weights = tf.Variable(tf.random_normal([10, 1], stddev=0.35), name="weights")
biases = tf.Variable(tf.zeros([1]), name="biases")
y = tf.matmul(x_data.reshape((1,-1)), weights)+biases
# Add an op to initialize the variables.
init_op = tf.global_variables_initializer()
saver = tf.train.Saver()
# Later, when launching the model
with tf.Session() as sess:
    # Run the init operation.
    sess.run(init_op)
    y_ = sess.run(y)
    print(y_)
    save_path = saver.save(sess, "./tmp/model.ckpt")
    print("Model saved in file: ", save_path)

从文件加载变量

import tensorflow as tf
import numpy as np
# Create two variables.
x_data = http://www.mamicode.com/np.float32([1,2,3,4,5,6,7,8,9,0])
weights = tf.Variable(tf.random_normal([10, 1], stddev=0.35), name="weights")
biases = tf.Variable(tf.zeros([1]), name="biases")
y = tf.matmul(x_data.reshape((1,-1)), weights)+biases
saver = tf.train.Saver()
# Later, when launching the model
with tf.Session() as sess:
    saver.restore(sess, ./tmp/model.ckpt)
    y_ = sess.run(y)
    print(y_)

参考链接

http://wiki.jikexueyuan.com/project/tensorflow-zh/how_tos/variables.html

tensorflow教程:变量创建、初始化、保存和加载