如何使用python在Theano中保存MLP模型?

时间:2016-08-02 12:45:00

标签: python serialization pickle deep-learning theano

我希望保存使用theano在MLP训练后获得的模型。

以下是代码:

def test_mlp(learning_rate=0.01, L1_reg=0.00, L2_reg=0.0001, n_epochs=500,
         dataset='mnist.pkl.gz', batch_size=20, n_hidden=500):

datasets = load_data(dataset)
...
######################
# BUILD ACTUAL MODEL #
######################
 # construct the MLP class
classifier = MLP(
    rng=rng,
    input=x,
    n_in=28 * 28,
    n_hidden=n_hidden,
    n_out=10
)
...
cost = cost = (
    classifier.negative_log_likelihood(y)
    + L1_reg * classifier.L1
    + L2_reg * classifier.L2_sqr
)
test_model = theano.function(...)
validate_model = theano.function(...)
train_model = theano.function(...)


###############
# TRAIN MODEL #
###############
...
best_validation_loss = numpy.inf
best_iter = 0
test_score = 0.
epoch = 0
done_looping = False

while (epoch < n_epochs) and (not done_looping):
            # after several processing I get the outputs as:

            validation_loss = numpy.mean(validation_losses)
            best_iter = iter
            test_score = numpy.mean(test_losses)

之后我需要将模型保存为:

            # save the best model
            with open('best_model.pkl', 'wb') as f:
                pickle.dump(classifier, f)

但它会导致如下错误:

Traceback (most recent call last):
  line 471, in <module>
    test_mlp()
  line 404, in test_mlp
    pickle.dump(classifier, f)
  File "/Users/X/anaconda/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects

我在逻辑回归模型上检查了它,它正在保存我的模型,我能够再次加载它。但这里有这个问题。你知道为什么会这样吗?解决方案是什么?

0 个答案:

没有答案