tensorflow笔记-简单模型训练,保存与提取

训练模型和保存模型代码

import tensorflow as tf
import numpy as np

x_data = np.random.rand(100)
y_data = x_data*2+1

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)

w = tf.Variable(0.0)
b = tf.Variable(0.0)
prediction = w*x+b

loss = tf.reduce_mean(tf.square(y-prediction))
train = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for step in range(200):
        sess.run(train,feed_dict={x:x_data,y:y_data})
        if step%20==0:
            print(sess.run([w,b]))
    save_path = tf.train.Saver().save(sess,"./3/model.ckpt")

模型提取,测试

import tensorflow as tf
import numpy as np

x_data = np.random.rand(3)
y_data = 2*x_data+1

x = tf.placeholder(tf.float32)

w = tf.Variable(0.0)
b = tf.Variable(0.0)
y = x*w+b
init = tf.global_variables_initializer()

with tf.Session() as sess:
    #sess.run(init)
    saver = tf.train.Saver()
    saver.restore(sess, "./3/model.ckpt")
    result = sess.run(y,feed_dict={x:x_data})
    print(result,y_data)

模型提取,测试2

import tensorflow as tf
import numpy as np

x_data = np.random.rand(3)
y_data = 2*x_data+1
graph = tf.Graph()
with tf.Session(graph=graph) as sess:
    saver = tf.train.import_meta_graph('./3/model.ckpt.meta')
    saver.restore(sess, tf.train.latest_checkpoint("./3/"))
    input = graph.get_tensor_by_name("x:0")
    result = sess.run(tf.get_default_graph().get_tensor_by_name("add:0"),feed_dict={input:x_data})
    print(result,y_data)

你可能感兴趣的:(tensorflw)