Detailed explanation of the use of pickle library

Release: 2018-05-16 17:42:12
54310 people have browsed it

The use of the pickle library is mentioned in the article "Understanding what machine learning is through a simple example", and this article will further elaborate on it.

So why do we need the operations of serialization and deserialization?

  1. Easy to store. The serialization process turns textual information into a stream of binary data. In this way, the information is easily stored in the hard disk. When a file needs to be read, the data is read from the hard disk and then deserialized to obtain the original data. When the Python program is running, some data such as strings, lists, and dictionaries are obtained. I want to save them for a long time for future use, instead of simply putting them in the memory and losing the data when the power is turned off. The Pickle module in the python module collection comes in handy, it can convert objects into a format that can be transmitted or stored.

  2. The loads() function performs the same deserialization as the load() function. Instead of accepting a stream object and reading the serialized data from a file, it accepts a str object containing the serialized data and returns the object directly.

  3. Code example:

  4. [python] view plain copy
    #!/usr/bin/env python  
    # -*- coding: UTF-8 -*-  
    import cPickle as pickle   
    obj = 123, "abcdedf", ["ac", 123], {"key": "value", "key1": "value1"}  
    print obj# 输出:(123, 'abcdedf', ['ac', 123], {'key1': 'value1', 'key': 'value'})      
    # 序列化到文件    
    with open(r"d:\a.txt", "r+") as f:  
        pickle.dump(obj, f)      
    with open(r"d:\a.txt") as f:  
        print pickle.load(f)# 输出:(123, 'abcdedf', ['ac', 123], {'key1': 'value1', 'key': 'value'})    
    # 序列化到内存(字符串格式保存),然后对象可以以任何方式处理如通过网络传输    
    obj1 = pickle.dumps(obj)  
    print type(obj1)# 输出:    
    print obj1# 输出:python专用的存储格式    
    obj2 = pickle.loads(obj1)  
    print type(obj2)# 输出:    
    print obj2# 输出:(123, 'abcdedf', ['ac', 123], {'key1': 'value1', 'key': 'value'})
    Copy after login

2. Easy to transmit. When two processes communicate remotely, they can send various types of data to each other. No matter what type of data it is, it is transmitted over the network in the form of a binary sequence. The sender needs to convert this object into a byte sequence before it can be transmitted on the network; the receiver needs to restore the byte sequence into an object.

  • Understand what machine learning is through a simple example

pickle is a standard module of the python language. The pickle library is included after installing python. No need to install it separately.
The pickle module implements basic data serialization and deserialization. Through the serialization operation of the pickle module, we can save the object information running in the program to a file and store it permanently; through the deserialization operation of the pickle module, we can create the object saved by the last program from the file.
In the official introduction, the English description of the serialization operation has several words, such as "serializing", "pickling", "serialization", "marshalling" or "flattening", etc., they all represent serialization mean. Correspondingly, there are many English words for deserialization operations, such as "de-serializing", "unpickling", "deserailization", etc. To avoid confusion, generally use "pickling"/"unpickling", or "serialization"/"deserailization".
pickle The module is serialized in binary form and saved to a file (the suffix of the saved file is ".pkl"), and cannot be opened directly for preview. Another serialization standard module of python, json, is human-readable and can be opened and viewed directly (for example, viewed in notepad++).

The pickle module has two main types of interfaces, namely serialization and deserialization.

is often used in this way:

[python] view plain copy
import cPickle as pickle  
Copy after login

The serialization operation includes:

  • pickle.dump()
    Copy after login
  • Deserialization operations include:

  • Pickler(file, protocol).dump(obj)
    Copy after login
  • pickle.load()

  • Unpickler(file).load()

2 序列化操作

2.1 序列化方法pickle.dump()

序列化的方法为 pickle.dump(),该方法的相关参数如下:
pickle.dump(obj, file, protocol=None,*,fix_imports=True)
该方法实现的是将序列化后的对象obj以二进制形式写入文件file中,进行保存。它的功能等同于 Pickler(file, protocol).dump(obj)

import picklewith open('svm_model_iris.pkl', 'wb') as f:
    pickle.dump(svm_classifier, f)
Copy after login


此外,参数可选 pickle.HIGHEST_PROTOCOL和pickle.DEFAULT_PROTOCOL。当前,python3.5版本中,pickle.HIGHEST_PROTOCOL的值为4,pickle.DEFAULT_PROTOCOL的值为3。当protocol参数为负数时,表示选择的参数是pickle.HIGHEST_PROTOCOL。

Detailed explanation of the use of pickle library

2.2 序列化方法pickle.dumps()

pickle.dumps(obj, protocol=None,*,fix_imports=True)

2.3 序列化方法Pickler(file, protocol).dump(obj)

pickle模块提供了序列化的面向对象的类方法,即 class pickle.Pickler(file, protocol=None,*,fix_imports=True),Pickler类有dump()方法。
Pickler(file, protocol).dump(obj) 实现的功能跟 pickle.dump() 是一样的。


3 反序列化操作

3.1 反序列化方法pickle.load()

序列化的方法为 pickle.load(),该方法的相关参数如下:
pickle.load(file, *,fix_imports=True, encoding=”ASCII”. errors=”strict”)
该方法实现的是将序列化的对象从文件file中读取出来。它的功能等同于 Unpickler(file).load()

import picklewith open('svm_model_iris.pkl', 'rb') as f:
    model = pickle.load(f)
Copy after login



3.2 反序列化方法pickle.loads()

pickle.loads(bytes_object, *,fix_imports=True, encoding=”ASCII”. errors=”strict”)

3.3 反序列化方法Unpickler(file).load()

pickle模块提供了反序列化的面向对象的类方法,即 class pickle.Unpickler(file, *,fix_imports=True, encoding="ASCII". errors="strict"),Pickler类有load()方法。
Unpickler(file).load() 实现的功能跟 pickle.load() 是一样的。

4 那些类型可以进行序列化和反序列化操作


Detailed explanation of the use of pickle library



The above is the detailed content of Detailed explanation of the use of pickle library. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact
Popular Tutorials
Latest Downloads
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap welfare online PHP training,Help PHP learners grow quickly!