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)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值