1. 程式人生 > >tensorflow 儲存模型

tensorflow 儲存模型

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 25 15:29:59 2018

@author: lg
"""

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)


#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.meta")
#    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]]}))
#    sess.close()