tensorflow中儲存模型、載入模型做預測(不需要再定義網路結構)
阿新 • • 發佈:2019-02-07
下面用一個線下回歸模型來記載儲存模型、載入模型做預測
參考文章:
訓練一個線下回歸模型並儲存看程式碼:
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
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
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=
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,"/Users/shuubiasahi/Desktop/tensorflow/modelsave/model.ckpt",global_step=100)
print("model saved in file: ", saver_path)
模型訓練結果:
2017-10-1123:05:12.606557: W tensorflow/core/platform/cpu_feature_guard.cc:45]TheTensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
109的預測值是:[[9.84855175]]
儲存模型檔案分析:
一、 saver.restore()時填的檔名,因為在saver.save的時候,每個checkpoint會儲存三個檔案,如model.ckpt-100.meta, model.ckpt-100.index, model.ckpt-100.data-00000-of-00001
在import_meta_graph時填的就是meta檔名,我們知道權值都儲存在model.ckpt-100.data-00000-of-00001這個檔案中,但是如果在restore方法中填這個檔名,就會報錯,應該填的是字首,這個字首可以使用tf.train.latest_checkpoint(checkpoint_dir)這個方法獲取。
二、模型的y中有用到placeholder,在sess.run()的時候肯定要feed對應的資料,因此還要根據具體placeholder的名字,從graph中使用get_operation_by_name方法獲取。
載入訓練好的模型:
import tensorflow as tf
with tf.Session()as sess:
new_saver=tf.train.import_meta_graph('/Users/shuubiasahi/Desktop/tensorflow/modelsave/model.ckpt-100.meta')
new_saver.restore(sess,"/Users/shuubiasahi/Desktop/tensorflow/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]]}))
載入模型後的預測結果:
2017-10-1123:07:33.176523: W tensorflow/core/platform/cpu_feature_guard.cc:45]TheTensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
109的預測值是:[[9.84855175]]
Process finished with exit code 0