saved_model操作例子3个

tf1.14

高级api

from tensorflow.contrib import predictor
import numpy as np
from PIL import Image
import pprint

model_path = "./"

img = Image.open("example.jpg")
img = img.resize((224, 224))
img_arr = np.asarray(img)
pprint.pprint(img_arr.reshape(-1)[:100000])

predict_fn = predictor.from_saved_model(model_path)
predictions = predict_fn({"input_1": np.reshape(img_arr, [1, 224, 224, 3])})

res = predictions['fc100'][0]
print(res)
label = np.argmax(res)
print(label)

load方法

import tensorflow as tf
import numpy as np
from PIL import Image
export_dir = "./"
from  tensorflow.saved_model import tag_constants
with tf.Session(graph=tf.Graph()) as sess:
    tf.saved_model.loader.load(sess,[tag_constants.TRAINING], export_dir)
    #graph = tf.get_default_graph()
    img = Image.open("example.jpg")
    img = img.resize((224, 224))
    img = np.expand_dims(img, 0)
    #img_arr = np.asarray(img)
    x = sess.graph.get_tensor_by_name('input_1:0')
    y = sess.graph.get_tensor_by_name('fc100/Softmax:0')
    
    
    scores = sess.run(y,
                      feed_dict={x: img})
    print("predict: %s" % np.argmax(scores, 1))
    #print("predict: %d, actual: %d" % (np.argmax(scores, 1), np.argmax(batch_ys, 1)))

打印tensorname

import tensorflow as tf
import numpy as np
from PIL import Image
export_dir = "./"
from  tensorflow.saved_model import tag_constants
with tf.Session(graph=tf.Graph()) as sess:
    tf.saved_model.loader.load(sess,[tag_constants.TRAINING], export_dir)
    graph = tf.get_default_graph()
    
    tensor_name_list = [tensor.name for tensor in tf.get_default_graph().as_graph_def().node]
    for tensor_name in tensor_name_list:
        print(tensor_name,'\n')

你可能感兴趣的:(python)