tensorflow 加载模型

训练模型

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
money=np.array([[109],[82],[99], [72], [87], [78], [86], [84], [94], [57]]).astype(np.float32)
click=np.array([[11], [8], [8], [6],[ 7], [7], [7], [8], [9], [5]]).astype(np.float32)
x_test=money[0:5].reshape(-1,1)
y_test=click[0:5]
x_train=money[5:].reshape(-1,1)
y_train=click[5:]
x=tf.placeholder(tf.float32,[None,1],name='x') #保存要输入的格式
w=tf.Variable(tf.zeros([1,1]))
b=tf.Variable(tf.zeros([1]))
y=tf.matmul(x,w)+b
tf.add_to_collection('pred_network', y) #用于加载模型获取要预测的网络结构
y_=tf.placeholder(tf.float32,[None,1])
cost=tf.reduce_sum(tf.pow((y-y_),2))
train_step=tf.train.GradientDescentOptimizer(0.000001).minimize(cost)
init=tf.global_variables_initializer()
sess=tf.Session()
sess.run(init)
cost_history=[]
saver = tf.train.Saver()
for i in range(100):
    feed={x:x_train,y_:y_train}
    sess.run(train_step,feed_dict=feed)
    cost_history.append(sess.run(cost,feed_dict=feed))
# 输出最终的W,b和cost值
print("109的预测值是:",sess.run(y, feed_dict={x: [[109]]}))
print("W_Value: %f" % sess.run(w), "b_Value: %f" % sess.run(b), "cost_Value: %f" % sess.run(cost, feed_dict=feed))
#    saver_path = saver.save(sess, "/modelsave/model.ckpt",global_step=100)
#    print("model saved in file: ", saver_path)
    
#saver.save(sess, "modelsave/model")
saver.save(sess, "modelsave/linermodel.cpkt") 

加载模型

import tensorflow as tf
with tf.Session() as sess:
    new_saver=tf.train.import_meta_graph('modelsave/model.ckpt-100.meta')
    new_saver.restore(sess,"modelsave/model.ckpt-100")
    graph = tf.get_default_graph()
    x=graph.get_operation_by_name('x').outputs[0]
    y=tf.get_collection("pred_network")[0]
    print("109的预测值是:",sess.run(y, feed_dict={x: [[109]]}))
posted @ 2019-01-03 11:00  luoganttcc  阅读(152)  评论(0编辑  收藏  举报