关于Python pickle的疑问

最近遇到一个python无法持久化的对象,让我很困扰。
查了一些资料,但感觉难以理解。所以决定先留存这个问题之后再解决。

TypeError: can’t pickle ml_ANN_MLP objects

问题在于model对象无法被存储成文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# -*- coding:utf-8 -*-
# 环境 python 2.7.11 OpenCV 3.1.0
import numpy as np
import cv2
# import cPickle as pickle
import pickle
print cv2.__version__
# 3.1.0
train_data = np.array([[0.9,0.9,0.9,0.9,0.9],
[0.9,0.9,0.8,0.9,0.9],
[0.9,0.9,0.9,0.8,0.9],
[0.9,0.8,0.9,0.9,0.9],
[0.9,0.9,0.9,0.8,0.9],
[0.1,0.1,0.1,0.1,0.0],
[0.1,0.1,0.1,0.1,0.1],
[0.1,0.1,0.1,0.0,0.1],
[0.1,0.0,0.1,0.1,0.1],
[0.1,0.1,0.1,0.1,0.1],
])
train_label = np.array([[1,0],
[1,0],
[1,0],
[1,0],
[1,0],
[0,1],
[0,1],
[0,1],
[0,1],
[0,1],])
train_data = train_data.astype(np.float32)
train_label = train_label.astype(np.float32)
cv_train_data = cv2.ml.TrainData_create(train_data, cv2.ml.ROW_SAMPLE, train_label)
model = cv2.ml.ANN_MLP_create()
# set train parameters
layer_sizes = np.int32([5, 15, 2])
criteria = (cv2.TERM_CRITERIA_COUNT | cv2.TERM_CRITERIA_EPS, 500, 0.0001)
model.setLayerSizes(layer_sizes)
model.setActivationFunction(cv2.ml.ANN_MLP_SIGMOID_SYM)
model.setTrainMethod(cv2.ml.ANN_MLP_BACKPROP)
model.setBackpropWeightScale(0.1)
model.setBackpropMomentumScale(0.1)
print 'Training MLP ...'
train_flag = model.train(cv_train_data)
print 'Taining finishing...'
feature = np.array([[0.0,0.1,0.0,0.0,0.0]])
feature = feature.astype(np.float32)
print model.predict(feature)
p1 = pickle.dumps(model)
print p1

无法pickle对象的处理
http://www.au92.com/archives/resove-python-can-not-serialize-datetime.html

另外我尝试了dill以及把整个python环境打包,仍无法处理
http://stackoverflow.com/questions/2049849/why-cant-i-pickle-this-object