How to save and restore the DNNClassifier trained in Python TensorFlow; iris example

I am new to TensorFlow, just started studying a few days ago. I finished this tutorial ( https://www.tensorflow.org/versions/r0.9/tutorials/tflearn/index.html#tf-contrib-learn-quickstart ) and applied the same idea to my own dataset. (which worked out pretty well!)

Now I would like to save and restore the prepared DNNClassifier for future use. If anyone knows how to do this, let me know using the example iris code in the link above. Thanks for your help in advance!

+5
source share
2 answers

found a solution to this? If you haven’t done this, you can do this by specifying the model_dir parameter in the constructor when creating the DNNClassifier, this will create all the control points and files in this directory (save step). When you want to take a recovery step, you simply create another DNNClassifier, passing the same model_dir parameter (recovery phase), this will restore the model from the files created for the first time.

Hope this helps you.

+9
source

Below is my code ...

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))) 
0
source

All Articles