【问题标题】:Prediction using .pb model which was exported using keras api使用 keras api 导出的 .pb 模型进行预测
【发布时间】:2021-05-18 18:01:43
【问题描述】:

我使用 keras api(使用 tensorflow 2.0)创建并保存了一个模型:

import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *

training_data_df = pd.read_csv("03\sales_data_training_scaled.csv")

X = training_data_df.drop('total_earnings', axis=1).values
Y = training_data_df[['total_earnings']].values

# Define the model
model = Sequential()
model.add(Dense(50, input_dim=9, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(1, activation='linear'))
model.compile(loss='mean_squared_error', optimizer='adam')

# Train the model
model.fit(
    X,
    Y,
    epochs=50,
    shuffle=True,
    verbose=2
)

# Load the separate test data set
test_data_df = pd.read_csv("03\sales_data_test_scaled.csv")

X_test = test_data_df.drop('total_earnings', axis=1).values
Y_test = test_data_df[['total_earnings']].values

test_error_rate = model.evaluate(X_test, Y_test, verbose=0)
print("The mean squared error (MSE) for the test data set is: {}".format(test_error_rate))

# Save the model to disk
model.save("04/model/trained_model")
print("Model saved to disk.")

以 .pb 格式保存模型。我知道我可以使用以下方法加载模型:

import tensorflow as tf

graph = tf.Graph() 
graph_def = tf.GraphDef()
graph_def.ParseFromString(pb_file.read()) 
with graph.as_default():
  tf.import_graph_def(graph_def)

但我对如何在加载模型后进行预测感到困惑? 我偶然发现了this,它在预测之前讨论了模型的输入和输出部分的名称。 我的问题是,当我使用 Keras api 创建模型时,如何找到这些名称然后预测模型?

这是来自链接的预测代码:

# These names are part of the model and cannot be changed.
output_layer = 'loss:0'
input_node = 'Placeholder:0'

with tf.compat.v1.Session() as sess:
    try:
        prob_tensor = sess.graph.get_tensor_by_name(output_layer)
        predictions = sess.run(prob_tensor, {input_node: [augmented_image] })
    except KeyError:
        print ("Couldn't find classification output layer: " + output_layer + ".")
        print ("Verify this a model exported from an Object Detection project.")
        exit(-1)

【问题讨论】:

    标签: python tensorflow keras tensorflow2.0 prediction


    【解决方案1】:
    #Save the model 
    model.save('saved_model/my_model')
    #Load the model 
    import tensorflow as tf
    new_model = tf.keras.models.load_model('saved_model/my_model')
    
    # Check its architecture
    new_model.summary()
    #Predict model
    new_model.predict(input)
    

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 2018-09-24
      相关资源
      最近更新 更多