tensorflow中保存模型、加载模型做预测(不需要再定义网络结构)

下面用一个线下回归模型来记载保存模型、加载模型做预测

参考文章:

http://blog.csdn.net/thriving_fcl/article/details/71423039


训练一个线下回归模型并保存看代码:

 
    
  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-11 23:05:12.606557: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow 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-11 23:07:33.176523: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow 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

你可能感兴趣的:(python编程,机器学习)