簡體   English   中英

如何通過export_savedmodel保存一個tensorflow estimator,然后在本地加載和使用?

[英]How to save a tensorflow estimator by export_savedmodel, then load and use it locally later?

我已經訓練了一個 tf 線性回歸估計器,如下所示:

sample_size = train_x.shape[0]
feature_size = train_x.shape[1]

feature_columns = [tf.feature_column.numeric_column("x", shape=[feature_size])]

lr_estimator = tf.estimator.LinearRegressor(feature_columns=feature_columns )

train_x_mat = train_x.as_matrix()
test_x_mat = test_x.as_matrix()


# Define the training inputs
train_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"x": train_x_mat},
    y=np.array(train_y_mat),
    num_epochs=None,
    shuffle=True)

# Train model.
lr_estimator.train(input_fn=train_input_fn, steps=2000)

其中 train_x 和 train_y 是熊貓數據框。 lr_estimator 確實有效,我可以成功調用 .predict。

我如何將其保存到文件中,然后將其加載回來進行預測? 我只是想構建一個小的python程序。 預測程序將在同一個桌面上運行。 我還不需要復雜的服務器服務。

def serving_input_receiver_fn():
    """
    input placeholder
    """
    inputs = {"x": tf.placeholder(shape=[feature_size], dtype=tf.float32)}
    return tf.estimator.export.ServingInputReceiver(inputs, inputs)

# export model and weights
export_dir = est_inception_v3.export_savedmodel(export_dir_base="/export_dir", 
    serving_input_receiver_fn=serving_input_receiver_fn)

# restore from disk
with tf.Session() as sess:
    tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], export_dir)
    predictor = SavedModelPredictor(export_dir)
    print(predictor({"x": test_x_mat}))

暫無
暫無

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

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