如何保存和恢复在TensorFlow python中训练的DNNClassifier;虹膜示例

时间:2016-07-13 17:42:10

标签: python tensorflow

我是TensorFlow的新手,几天前才开始学习。我已经完成了本教程(https://www.tensorflow.org/versions/r0.9/tutorials/tflearn/index.html#tf-contrib-learn-quickstart)并将完全相同的想法应用到我自己的数据集中。 (结果非常好!)

现在我想保存并恢复经过培训的DNNClassifier以供进一步使用。如果有人知道如何操作,请使用上面链接中的iris示例代码告诉我。感谢您的帮助!

2 个答案:

答案 0 :(得分:11)

找到了解决方案吗?如果没有,您可以在创建DNNClassifier时在构造函数上指定model_dir参数,这将创建此目录中的所有检查点和文件(保存步骤)。如果要执行还原步骤,只需创建另一个传递相同model_dir参数(还原阶段)的DNNClassifier,这将从第一次创建的文件中还原模型。

希望这对你有所帮助。

答案 1 :(得分:1)

以下是我的代码......

import tensorflow as tf
import numpy as np

if __name__ == '__main__':
# Data sets
IRIS_TRAINING = "iris_training.csv"
IRIS_TEST = "iris_test.csv"

# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TRAINING, target_dtype=np.int)
test_set = tf.contrib.learn.datasets.base.load_csv(filename=IRIS_TEST, target_dtype=np.int)

x_train, x_test, y_train, y_test = training_set.data, test_set.data, training_set.target, test_set.target

# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.contrib.learn.DNNClassifier(hidden_units=[10, 20, 10], n_classes=3, model_dir="path_to_my_local_dir")

# print classifier.model_dir

# Fit model.
print "start fitting model..."
classifier.fit(x=x_train, y=y_train, steps=200)
print "finished fitting model!!!"

# Evaluate accuracy.
accuracy_score = classifier.evaluate(x=x_test, y=y_test)["accuracy"]
print('Accuracy: {0:f}'.format(accuracy_score))

#Classify two new flower samples.
new_samples = np.array(
    [[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=float)
y = classifier.predict_proba(new_samples)
print ('Predictions: {}'.format(str(y)))

#---------------------------------------------------------------------------------
#model_dir below has to be the same as the previously specified path!
new_classifier = tf.contrib.learn.DNNClassifier(hidden_units=[10, 20, 10], n_classes=3, model_dir="path_to_my_local_dir")
accuracy_score = new_classifier.evaluate(x=x_test, y=y_test)["accuracy"]
print('Accuracy: {0:f}'.format(accuracy_score))
new_samples = np.array(
    [[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=float)
y = classifier.predict_proba(new_samples)
print ('Predictions: {}'.format(str(y)))