簡體   English   中英

如何在張量流中驗證優化模型

[英]How to verify optimized model in tensorflow

我正在遵循codelabs教程 他們使用此腳本優化模型

python -m tensorflow.python.tools.optimize_for_inference \
  --input=tf_files/retrained_graph.pb \
  --output=tf_files/optimized_graph.pb \
  --input_names="input" \
  --output_names="final_result"

他們使用此腳本驗證了optimized_graph.pb

python -m scripts.label_image \
    --graph=tf_files/optimized_graph.pb \
    --image=tf_files/flower_photos/daisy/3475870145_685a19116d.jpg

問題是我嘗試對我自己的代碼使用optimize_for_inference ,這不適用於圖像分類。

以前,在進行優化之前,我使用此腳本通過對示例數據進行測試來驗證我的模型:

import tensorflow as tf
from tensorflow.contrib import predictor
from tensorflow.python.platform import gfile
import numpy as np

def load_graph(frozen_graph_filename):
    with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())

    with tf.Graph().as_default() as graph:
        tf.import_graph_def(graph_def, name="prefix")

    input_name = graph.get_operations()[0].name+':0'
    output_name = graph.get_operations()[-1].name+':0'

    return graph, input_name, output_name

def predict(model_path, input_data):
    # load tf graph
    tf_model,tf_input,tf_output = load_graph(model_path)

    x = tf_model.get_tensor_by_name(tf_input)
    y = tf_model.get_tensor_by_name(tf_output) 

    model_input = tf.train.Example(
        features=tf.train.Features(feature={
        "thisisinput": tf.train.Feature(float_list=tf.train.FloatList(value=input_data)),
    }))
    model_input = model_input.SerializeToString()

    num_outputs = 3
    predictions = np.zeros(num_outputs)
    with tf.Session(graph=tf_model) as sess:
        y_out = sess.run(y, feed_dict={x: [model_input]})
        predictions = y_out

    return predictions

if __name__=="__main__":
    input_data = [4.7,3.2,1.6,0.2] # my model recieve 4 inputs
    print(np.argmax(predict("not_optimized_model.pb",x)))

但是在優化模型后,我的測試腳本無法正常工作。 它引發一個錯誤:

ValueError:節點import / ParseExample / ParseExample的輸入0從import / inputtensors:0傳遞給float,與預期字符串不兼容。

所以我的問題是優化模型后如何驗證模型? 我不能像教程一樣使用--image命令。

在導出模型時,我通過使用tf.float32更改了占位符的類型來解決了該錯誤:

def my_serving_input_fn():
    input_data = {
        "featurename" : tf.placeholder(tf.float32, [None, 4], name='inputtensors')
    }
    return tf.estimator.export.ServingInputReceiver(input_data, input_data)

然后將上面的prediction函數更改為:

def predict(model_path, input_data):
    # load tf graph
    tf_model, tf_input, tf_output = load_graph(model_path)

    x = tf_model.get_tensor_by_name(tf_input)
    y = tf_model.get_tensor_by_name(tf_output) 

    num_outputs = 3
    predictions = np.zeros(num_outputs)
    with tf.Session(graph=tf_model) as sess:
        y_out = sess.run(y, feed_dict={x: [input_data]})
        predictions = y_out

    return predictions

凍結模型后,上面的預測代碼將起作用。 但是不幸的是,在導出模型后嘗試直接加載pb時,它會引發另一個錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM