日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

tensorflow保存模型和加载模型的方法(Python和Android)

發布時間:2024/4/15 Android 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 tensorflow保存模型和加载模型的方法(Python和Android) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

tensorflow保存模型和加載模型的方法(Python和Android)

一、tensorflow保存模型的幾種方法:

(1)?tf.train.saver()保存模型

? ? ?使用 tf.train.saver()保存模型,該方法保存模型文件的時候會產生多個文件,會把計算圖的結構和圖上參數取值分成了不同的文件存儲。這種方法是在TensorFlow中是最常用的保存方式。

? ? 例如:

import tensorflow as tf # 聲明兩個變量 v1 = tf.Variable(tf.random_normal([1, 2]), name="v1") v2 = tf.Variable(tf.random_normal([2, 3]), name="v2") init_op = tf.global_variables_initializer() # 初始化全部變量 saver = tf.train.Saver() # 聲明tf.train.Saver類用于保存模型 with tf.Session() as sess:sess.run(init_op)print("v1:", sess.run(v1)) # 打印v1、v2的值一會讀取之后對比print("v2:", sess.run(v2))saver_path = saver.save(sess, "save/model.ckpt") # 將模型保存到save/model.ckpt文件print("Model saved in file:", saver_path)

? ? 運行后,會在save目錄下保存了四個文件:

? ? 其中

  • checkpoint是檢查點文件,文件保存了一個目錄下所有的模型文件列表;
  • model.ckpt.meta文件保存了TensorFlow計算圖的結構,可以理解為神經網絡的網絡結構,該文件可以被 tf.train.import_meta_graph 加載到當前默認的圖來使用。
  • ckpt.data : 保存模型中每個變量的取值

參考資料:
https://blog.csdn.net/michael_yt/article/details/74737489

https://blog.csdn.net/lwplwf/article/details/62419087

(2)tf.train.write_graph()

? ? 使用 tf.train.write_graph()保存模型,該方法只是保存了模型的結構,并不保存訓練完畢的參數值。

(3)convert_variables_to_constants固化模型結構

? ? 很多時候,我們需要將TensorFlow的模型導出為單個文件(同時包含模型結構的定義與權重),方便在其他地方使用(如在Android中部署網絡)。利用tf.train.write_graph()默認情況下只導出了網絡的定義(沒有權重),而利用tf.train.Saver().save()導出的文件graph_def與權重是分離的,因此需要采用別的方法。?我們知道,graph_def文件中沒有包含網絡中的Variable值(通常情況存儲了權重),但是卻包含了constant值,所以如果我們能把Variable轉換為constant,即可達到使用一個文件同時存儲網絡架構與權重的目標。

? ? TensoFlow為我們提供了convert_variables_to_constants()方法,該方法可以固化模型結構,將計算圖中的變量取值以常量的形式保存。而且保存的模型可以移植到Android平臺。

????參考資料:
????【1】https://blog.csdn.net/sinat_29957455/article/details/78511119

? ? 【2】這里主要實現第三種方法,因為該方法保存的模型可以移植到Android平臺運行。以下Python代碼,都共享在

? ? ??Github:https://github.com/PanJinquan/tensorflow-learning-tutorials/tree/master/MNIST-Demo;

? ? 【3】移植Android的詳細過程可參考本人的另一篇博客資料《將tensorflow MNIST訓練模型移植到Android》:

? ? ? ?https://blog.csdn.net/guyuealian/article/details/79672257

二、訓練和保存模型

? ? 以MNIST手寫數字識別為例,這里首先使用Python版的TensorFlow實現SoftMax Regression分類器,并將訓練好的模型的網絡拓撲結構和參數保存為pb文件,其中convert_variables_to_constants函數,會將計算圖中的變量取值以常量的形式保存:https://blog.csdn.net/sinat_29957455/article/details/78511119

#coding=utf-8 from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf from tensorflow.python.framework import graph_util print('tensortflow:{0}'.format(tf.__version__))mnist = input_data.read_data_sets("Mnist_data/", one_hot=True)#create model with tf.name_scope('input'):x = tf.placeholder(tf.float32,[None,784],name='x_input')#輸入節點名:x_inputy_ = tf.placeholder(tf.float32,[None,10],name='y_input') with tf.name_scope('layer'):with tf.name_scope('W'):#tf.zeros([3, 4], tf.int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]W = tf.Variable(tf.zeros([784,10]),name='Weights')with tf.name_scope('b'):b = tf.Variable(tf.zeros([10]),name='biases')with tf.name_scope('W_p_b'):Wx_plus_b = tf.add(tf.matmul(x, W), b, name='Wx_plus_b')y = tf.nn.softmax(Wx_plus_b, name='final_result')# 定義損失函數和優化方法 with tf.name_scope('loss'):loss = -tf.reduce_sum(y_ * tf.log(y)) with tf.name_scope('train_step'):train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)print(train_step) # 初始化 sess = tf.InteractiveSession() init = tf.global_variables_initializer() sess.run(init) # 訓練 for step in range(100):batch_xs,batch_ys =mnist.train.next_batch(100)train_step.run({x:batch_xs,y_:batch_ys})# variables = tf.all_variables()# print(len(variables))# print(sess.run(b))# 測試模型準確率 pre_num=tf.argmax(y,1,output_type='int32',name="output")#輸出節點名:output correct_prediction = tf.equal(pre_num,tf.argmax(y_,1,output_type='int32')) accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) a = accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}) print('測試正確率:{0}'.format(a))# 保存訓練好的模型 #形參output_node_names用于指定輸出的節點名稱,output_node_names=['output']對應pre_num=tf.argmax(y,1,name="output"), output_graph_def = graph_util.convert_variables_to_constants(sess, sess.graph_def,output_node_names=['output']) with tf.gfile.FastGFile('model/mnist.pb', mode='wb') as f:#’wb’中w代表寫文件,b代表將數據以二進制方式寫入文件。f.write(output_graph_def.SerializeToString()) sess.close()# 注: # convert_variables_to_constants函數,會將計算圖中的變量取值以常量的形式保存:https://blog.csdn.net/sinat_29957455/article/details/78511119

?

三、加載和測試

批量測試:

import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data from PIL import Image import matplotlib import matplotlib.pyplot as plt#模型路徑 model_path = 'model/mnist.pb' #測試數據 mnist = input_data.read_data_sets("Mnist_data/", one_hot=True) x_test = mnist.test.images x_labels = mnist.test.labels;with tf.Graph().as_default():output_graph_def = tf.GraphDef()with open(model_path, "rb") as f:output_graph_def.ParseFromString(f.read())tf.import_graph_def(output_graph_def, name="")with tf.Session() as sess:tf.global_variables_initializer().run()# x_test = x_test.reshape(1, 28 * 28)input_x = sess.graph.get_tensor_by_name("input/x_input:0")output = sess.graph.get_tensor_by_name("output:0")# 【1】下面是進行批量測試----------------------------------------------------------pre_num = sess.run(output, feed_dict={input_x: x_test})#利用訓練好的模型預測結果#結果批量測試的準確率correct_prediction = tf.equal(pre_num, tf.argmax(x_labels, 1,output_type='int32'))accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))acc = sess.run(accuracy, feed_dict={input_x: x_test})# a = accuracy.eval({x: mnist.test.images, y_: mnist.test.labels})print('測試正確率:{0}'.format(acc))#【2】下面是進行單張圖片的測試-----------------------------------------------------testImage=x_test[0];test_input = testImage.reshape(1, 28 * 28)pre_num = sess.run(output, feed_dict={input_x: test_input})#利用訓練好的模型預測結果print('模型預測結果為:',pre_num)#顯示測試的圖片testImage = testImage.reshape(28, 28)testImage=np.array(testImage * 255, dtype="int32")fig = plt.figure(), plt.imshow(testImage, cmap='binary') # 顯示圖片plt.title("prediction result:"+str(pre_num))plt.show()#保存測定的圖片testImage = Image.fromarray(testImage)testImage = testImage.convert('L')testImage.save("data/test_image.jpg")# matplotlib.image.imsave('data/name.jpg', im)sess.close()

?

單個樣本測試:

?

import tensorflow as tf import numpy as np from PIL import Image import matplotlib.pyplot as plt#模型路徑 model_path = 'model/mnist.pb' #測試圖片 testImage = Image.open("data/test_image.jpg");with tf.Graph().as_default():output_graph_def = tf.GraphDef()with open(model_path, "rb") as f:output_graph_def.ParseFromString(f.read())tf.import_graph_def(output_graph_def, name="")with tf.Session() as sess:tf.global_variables_initializer().run()# x_test = x_test.reshape(1, 28 * 28)input_x = sess.graph.get_tensor_by_name("input/x_input:0")output = sess.graph.get_tensor_by_name("output:0")#對圖片進行測試testImage=testImage.convert('L')testImage = testImage.resize((28, 28))test_input=np.array(testImage)test_input = test_input.reshape(1, 28 * 28)pre_num = sess.run(output, feed_dict={input_x: test_input})#利用訓練好的模型預測結果print('模型預測結果為:',pre_num)#顯示測試的圖片# testImage = test_x.reshape(28, 28)fig = plt.figure(), plt.imshow(testImage,cmap='binary') # 顯示圖片plt.title("prediction result:"+str(pre_num))plt.show()

讀取圖片進行測試:

import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import cv2 as cv #模型路徑 model_path = 'model/mnist.pb' #測試圖片 testImage = cv.imread("data/test_image.jpg");with tf.Graph().as_default():output_graph_def = tf.GraphDef()with open(model_path, "rb") as f:output_graph_def.ParseFromString(f.read())tf.import_graph_def(output_graph_def, name="")with tf.Session() as sess:tf.global_variables_initializer().run()# x_test = x_test.reshape(1, 28 * 28)input_x = sess.graph.get_tensor_by_name("input/x_input:0")output = sess.graph.get_tensor_by_name("output:0")#對圖片進行測試testImage=cv.cvtColor(testImage, cv.COLOR_BGR2GRAY)testImage=cv.resize(testImage,dsize=(28, 28))test_input=np.array(testImage)test_input = test_input.reshape(1, 28 * 28)pre_num = sess.run(output, feed_dict={input_x: test_input})#利用訓練好的模型預測結果print('模型預測結果為:',pre_num)# cv.imshow("image",testImage)# cv.waitKey(0)#顯示測試的圖片fig = plt.figure(), plt.imshow(testImage,cmap='binary') # 顯示圖片plt.title("prediction result:"+str(pre_num))plt.show()

源碼Github:https://github.com/PanJinquan/MNIST-TensorFlow-Python

上面TensorFlow保存訓練好的模型,可以移植到Android,詳細過程可以參考另一篇博客資料《將tensorflow MNIST訓練模型移植到Android》:https://blog.csdn.net/guyuealian/article/details/79672257

?

?

總結

以上是生活随笔為你收集整理的tensorflow保存模型和加载模型的方法(Python和Android)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 人妻丰满熟妇岳av无码区hd | 日韩视频免费观看高清完整版在线观看 | 欧美裸体xxxx极品少妇 | 奇米网狠狠干 | 美国一级黄色大片 | 国产夫妻露脸 | 日韩福利| 国产小视频免费在线观看 | 亚洲乱码中文字幕久久孕妇黑人 | 中日一级片| 亚洲性图一区二区三区 | 久久久久久久久久影院 | 日韩123区 | 国产成人不卡 | 夜夜se | 影音先锋美女 | 黄色91免费观看 | 日批免费观看 | 久久全国免费视频 | 亚洲美女av网站 | 欧美三级视频在线播放 | 操模特| 东北少妇av | 色噜噜视频 | 欧美福利视频在线 | 91人人爱| 天堂网www| 黄色仓库av | 丰满岳乱妇一区二区三区 | 亚洲成a人片777777久久 | 激情综合六月 | 69视频在线观看免费 | 拍摄av现场失控高潮数次 | 国产日韩一区二区三区 | 99久久久无码国产精品免费 | 日本欧美成人 | 老司机福利院 | 99热这里只有精品5 国产精品伦子伦免费视频 精品一二三 | 成人在线免费视频播放 | 欧美一区二区三区激情视频 | 中文字幕一区二区三区在线观看 | 黄色一级片av | 日韩电影二区 | 无码精品一区二区免费 | 欧美一区二区三区四区在线 | 日本欧美一区二区三区 | 日韩中文字幕在线 | 天堂v在线观看 | 欧美一区二区三区黄色 | 天天色天天射天天干 | 97超级碰碰| 伊人久久97 | 亚洲专区欧美专区 | 精品妇女一区二区三区 | 三八激情网 | 国产日韩精品久久 | 国产高清视频在线播放 | 国产 福利 在线 | 自拍偷拍 国产 | 午夜影院体验区 | 人人搞人人 | 成人xxxx | 久久精品亚洲精品国产欧美 | 午夜之声l性8电台lx8电台 | 国产刺激对白 | 国产一级黄色片子 | 狠狠看 | 亚洲伦理在线观看 | 免费一级特黄特色大片 | 欧洲做受高潮欧美裸体艺术 | 一级片亚洲 | 国产欧美一区二区精品性色 | 来吧亚洲综合网 | 亚洲精品伊人 | 亚洲美女色视频 | 一区二区在线观看免费 | 亚洲女人天堂色在线7777 | 桃色视频网站 | 国产黄色小视频在线观看 | 中文在线观看免费视频 | 国产精品无圣光 | 我不卡av | 乱色熟女综合一区二区三区 | 国产高清精品在线观看 | 91 高清 在线 制服 偷拍 | 影音先锋中文字幕在线 | 超碰97国产在线 | 少妇av导航 | av网站免费看 | 伊人久久狼人 | 人人妻人人藻人人爽欧美一区 | 精品欧美在线观看 | 亚洲色图20p | www国产91 | 五月婷婷狠狠 | 老版水浒传83版免费播放 | 成年人黄色大片 | 日韩欧美毛片 | 欧美hdxxxx|