tensorflow讀取一個模型後多次使用

訓練好一個模型後,將其投入使用,會有在項目初始化後多次加載測試數據的需求,可以採用保存graph的思想實現

(在一個項目中需要加載多個模型同樣可用)

另:這條博客接我的上一條https://blog.csdn.net/qq_34470213/article/details/104076898,是在上一個代碼的基礎上改寫的。

1、新建文件test.py,建一個類Model_test,用來保存模型,包括一個初始化方法,用來初始化模型(項目中僅需初始化時調用一次),一個測試調用方法,用來調用模型進行測試(每次測試調用一次)。

class Model_test():
    def restore(self):
        self.model = Model.LeNet5(1, 5)
        path = "D:/model/model/model.ckpt"
        self.model.load(path)

    def restore_test(self, image_path):
        image = Process.process_one(image_path)
        sort = self.model.test1(image)
        return sort

2、在model.py的類中添加初始化函數和測試函數,這裏和之前的測試函數的差別在於拆分開了加載和測試的部分,並且將graph和session保存爲了類屬性變量。

    def load(self, model_path):
        self.graph = tf.Graph()
        self.sess = tf.Session(graph=self.graph)
        with self.sess.graph.as_default():
            self.sess.run(tf.global_variables_initializer())
            self.sess.run(tf.local_variables_initializer())
            saver11 = tf.train.import_meta_graph(model_path+'.meta',
                                               clear_devices=True)
            saver11.restore(self.sess, model_path)

    def test1(self, image):
        x = tf.placeholder(tf.float32, [None, 64, 64, 1], name='x-input')
        self.activation = self.graph.get_tensor_by_name('layer6-fc2/add:0')
        image = np.array(image) / 255.0
        image = np.reshape(image, (-1, 64, 64, 1))
        logit = tf.arg_max(self.activation, 1)
        y, label = self.sess.run((self.activation, logit), feed_dict={'x-input:0': image})
        return label

3、以上兩步就可以成功實現了,調用方法爲:

tm = test.Model_test()
tm.restore()


……


while(True){
    sort = tm.restore_test(pathname[i])
}

……

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章