Python--pickle Serialization (persistence)

Source: Internet
Author: User

The machine learning process is divided into the training process and the prediction process. The training process gets a model and the prediction process gets the predicted results. To save time, it's a good idea to call the already constructed model every time the prediction is executed, rather than having to retrain the model before each prediction.

Taking the decision tree as an example, it is a good idea to call a decision tree that has already been constructed each time the classification is performed. You can serialize an object using the Pickle module in Python. The serialized object can save the object pickle.dump () on disk and read it out pickle.load () when needed. any object can perform serialization operations, and the Dictionary object is no exception!!!

Code:

1 ImportPickle2 #Storing the decision Tree Model Inputtree (Dictionary object) in the file filename3 defStoretree (inputtree,filename):4Fw=open (filename,'W')5 pickle.dump (INPUTTREE,FW)6 fw.close ()7 #to read the decision tree in file filename8 defgrabtree (filename):9Fr=open (filename)Ten     returnPickle.load (FR)

To open the DOS client test:

In [all]: Store a decision tree in a dictionary,mytree={' no surfacing ': {0: ' No ', 1:{' flippers ': {0: ' No ', 1: ' Yes ' }}}

In []: Get the file "ClassifierStorage.txt", open the file to see what it looks like after serialization:

In []: Read the decision tree in "ClassifierStorage.txt"

Out []: output "Mytree"

Python--pickle Serialization (persistence)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.