1. 程式人生 > >tensorflow中儲存模型、載入模型做預測(不需要再定義網路結構)

tensorflow中儲存模型、載入模型做預測(不需要再定義網路結構)

下面用一個線下回歸模型來記載儲存模型、載入模型做預測

參考文章:

訓練一個線下回歸模型並儲存看程式碼:

  1. import tensorflow as tf
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. money=np.array([[109],[82],[99],[72],[87],[78],[86],[84],[94],[57]]).astype(np.float32)
  5. click=np.array([[11],[8],[8],[6],[7],[7],[7],[8],[9],[5]]).astype(np.float32)
  6. x_test
    =money[0:5].reshape(-1,1)
  7. y_test=click[0:5]
  8. x_train=money[5:].reshape(-1,1)
  9. y_train=click[5:]
  10. x=tf.placeholder(tf.float32,[None,1],name='x')#儲存要輸入的格式
  11. w=tf.Variable(tf.zeros([1,1]))
  12. b=tf.Variable(tf.zeros([1]))
  13. y=tf.matmul(x,w)+b
  14. tf.add_to_collection('pred_network', y)#用於載入模型獲取要預測的網路結構
  15. y_=tf.placeholder(tf.float32
    ,[None,1])
  16. cost=tf.reduce_sum(tf.pow((y-y_),2))
  17. train_step=tf.train.GradientDescentOptimizer(0.000001).minimize(cost)
  18. init=tf.global_variables_initializer()
  19. sess=tf.Session()
  20. sess.run(init)
  21. cost_history=[]
  22. saver = tf.train.Saver()
  23. for i in range(100):
  24. feed={x:x_train,y_:y_train}
  25. sess.run(train_step,feed_dict=
    feed)
  26. cost_history.append(sess.run(cost,feed_dict=feed))
  27. # 輸出最終的W,b和cost值
  28. print("109的預測值是:",sess.run(y, feed_dict={x:[[109]]}))
  29. print("W_Value: %f"% sess.run(w),"b_Value: %f"% sess.run(b),"cost_Value: %f"% sess.run(cost, feed_dict=feed))
  30. saver_path = saver.save(sess,"/Users/shuubiasahi/Desktop/tensorflow/modelsave/model.ckpt",global_step=100)
  31. print("model saved in file: ", saver_path)

模型訓練結果:

  1. 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.
  2. 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方法獲取。

載入訓練好的模型:

  1. import tensorflow as tf
  2. with tf.Session()as sess:
  3. new_saver=tf.train.import_meta_graph('/Users/shuubiasahi/Desktop/tensorflow/modelsave/model.ckpt-100.meta')
  4. new_saver.restore(sess,"/Users/shuubiasahi/Desktop/tensorflow/modelsave/model.ckpt-100")
  5. graph = tf.get_default_graph()
  6. x=graph.get_operation_by_name('x').outputs[0]
  7. y=tf.get_collection("pred_network")[0]
  8. print("109的預測值是:",sess.run(y, feed_dict={x:[[109]]}))


載入模型後的預測結果:

  1. 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.
  2. 109的預測值是:[[9.84855175]]
  3. Process finished with exit code 0