我正在尝试保 stub 据 http://deeplearning.net/tutorial/code/mlp.py 使用 Theano 构建的多层感知器网络训练期间获得的模型使用 Logistic 回归器中显示的代码 http://deeplearning.net/tutorial/code/logistic_sgd.py ,特别是
# save the best model
with open('best_model.pkl', 'w') as f:
cPickle.dump(classifier, f)
但我得到的是
... loading data ... building the model ... training epoch 1, minibatch 74/74, validation error 38.333333 % epoch 1, minibatch 74/74, test error of best model 41.666667 % Traceback (most recent call last): File "mlp.py", line 423, in test_mlp() File "mlp.py", line 406, in test_mlp cPickle.dump(classifier, f, protocol=cPickle.HIGHEST_PROTOCOL) cPickle.PicklingError: Can't pickle : attribute lookup builtin.instancemethod failed
由于我在卷积网络中也遇到了这个问题,所以我的问题是:有一种通用方法可以在 Theano 中存储模型,以便重用于预测吗?
编辑 正如我现在使用的评论中所建议的
cPickle.dump((classifier.hiddenLayer.params,classifier.logRegressionLayer.params), f)
用于保存和
classifier.hiddenLayer.W = cPickle.load(open('best_model_mlp.pkl'))[0][0]
用于设置分类器中隐藏层的权重(例如)定义为
x = T.matrix('x')
classifier = MLP(
rng=rng,
input=x,
n_in = 28*28,
n_hidden= 500,
n_out=10
)
但是当我调用这个函数时
predict_model = theano.function(
inputs=[classifier.input],
outputs=classifier.logRegressionLayer.y_pred,
)
即使使用训练有素的网络,我也始终将 [0] 作为预测。 我在设置或保存参数时仍然做错了?
最佳答案
我今天也遇到了同样的问题。我不知道为什么这适用于 'logistic_sgd.py
' 而不适用于 'mlp.py'
但你可以做的就是存储 'classifier.params'
'classifier.params'
是您唯一需要的元素。从这些参数预测您的类应该不会太难(这已经在您的代码中)。
关于pickle - 保存 Theano 模型不适用于 MLP 网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34068922/