TensorFlow:DNNRegressor,如何保存模型以进行预测

我是TensorFlow的新手,我正试图将我的scikit-learn模型转换为TensorFlow符号,但我发现它过于复杂 .

在scikit-learn中,您只需调用 model.dump("ModelName.pkl") 来保存模型并调用 joblib.load("ModelName.pkl") 再次使用它 . 我试图用TensorFlow做类似的事情,但我收到以下错误:

Traceback (most recent call last):
  File "/Users/user0/Desktop/IPML_Model/tensorflow_model_train.py", line 39, in <module>
    saver = tf.train.Saver()
  File "/Library/Python/2.7/site-packages/tensorflow/python/training/saver.py", line 1139, in __init__
    self.build()
  File "/Library/Python/2.7/site-packages/tensorflow/python/training/saver.py", line 1161, in build
    raise ValueError("No variables to save")
ValueError: No variables to save

我想做的就是用 get_training_data() 训练模型,保存它,然后加载它,这样我就可以调用 predict . 这是我有的:

def get_training_data():
    X, y = preprocess_data()

    X_train, _, y_train, _ = train_test_split(X, y, test_size=0.2, random_state=123)

    feature_set = {f: tf.constant(X_train[f]) for f in features}
    label_set = tf.constant(y_train)

    return feature_set, label_set

# Start a session
sess = tf.Session()

# Initialize a DNNRegressor model
feature_cols = [real_valued_column(k) for k in features]
dnn_regressor = DNNRegressor(feature_columns=feature_cols, hidden_units=[50, 50], label_dimension=7, model_dir=os.getcwd())

# Train the model
dnn_regressor.fit(input_fn=lambda: get_training_data(), steps=5000)

# Save the model
saver = tf.train.Saver()
saver.save(sess, "dnnregressor.ckpt")

我可以在拟合之后在 dnnregressor 上调用 predict 并且不需要"Variables",但我想首先保存模型然后调用预测 . 什么是最简单,最简单的方法呢?

回答(1)

2 years ago

当你打电话时,模型保存在 model_dir 中:

dnn_regressor = DNNRegressor(feature_columns=feature_cols, hidden_units=[50, 50], label_dimension=7, model_dir=os.getcwd())

现在在 inference 期间再次调用上面的内容,它将从 model_dir 加载模型,然后调用 dnn_regressor.predict() 函数 .