【问题标题】:Pickle multy layer CNN in Theano, Lenet5Theano、Lenet 5 中的 Pickle 多层 CNN
【发布时间】:2017-06-27 04:34:06
【问题描述】:

我是深度学习的新手,但遇到了问题。 我正在使用 Theano 进行图像识别,并且我想使用经过训练的模型创建一个预测系统。 我引用了 LeNet5 Convolutional Neural Networks (LeNet) 并训练了自己的数据,现在我想使用训练后的模型来预测新图像。 在Classifying MNIST digits using Logistic Regression 中,它描述了腌制训练模型的方法,但这只是逻辑回归,而不是多层 CNN。以同样的方式我保存了每一层,但我不能用它来预测。 请帮我! 这是我的代码:

def predict():
"""
An example of how to load a trained model and use it
to predict labels.
"""

# load the saved model
#x = Data
x = T.matrix('x')
Data = x.reshape((1, 1, 32, 32))
layer0
layer1
layer2_input = layer1.output.flatten(2)
layer2
layer3

# compile a predictor function
predict_model = theano.function([layer0.input],
    layer0.output)
    #inputs=[layer0.input],
    #outputs=layer3.y_pred)

# We can test it on some examples from test test
#dataset='facedata_cross_6_2_6.pkl.gz'
#datasets = load_data(dataset)
#test_set_x, test_set_y = datasets[2]
#test_set_x = test_set_x.get_value()
#reshape=np.reshape(test_set_x[26],(28,28))
#plt.imshow(reshape)

predicted_values = predict_model(Data)
print("Predicted values for the first 10 examples in test set:")
print(predicted_values)

【问题讨论】:

    标签: deep-learning theano conv-neural-network image-recognition


    【解决方案1】:

    有很多方法可以保存您的模型。我经常使用的是通过pickle每一层的权重和偏差(顺序由你决定):

    f = file('Models/bestmodel.pickle','wb')
    cPickle.dump(layer0.W.get_value(borrow=True),f,protocol=cPickle.HIGHEST_PROTOCOL)
    cPickle.dump(layer1.W.get_value(borrow=True),f,protocol=cPickle.HIGHEST_PROTOCOL)
    cPickle.dump(layer2.W.get_value(borrow=True),f,protocol=cPickle.HIGHEST_PROTOCOL)
    ...
    cPickle.dump(layer0.b.get_value(borrow=True),f,protocol=cPickle.HIGHEST_PROTOCOL)            
    cPickle.dump(layer1.b.get_value(borrow=True),f,protocol=cPickle.HIGHEST_PROTOCOL)
    cPickle.dump(layer2.b.get_value(borrow=True),f,protocol=cPickle.HIGHEST_PROTOCOL)
    ...
    f.close()
    

    然后对于预测系统,创建相同的模型架构并使用保存的模型作为初始值(与您保存的顺序相同):

    f=file('Models/bestmodel.pickle','rb')
    layer0.W.set_value(cPickle.load(f), borrow=True)
    layer1.W.set_value(cPickle.load(f), borrow=True)
    layer2.W.set_value(cPickle.load(f), borrow=True)
    ...
    layer0.b.set_value(cPickle.load(f), borrow=True)
    layer1.b.set_value(cPickle.load(f), borrow=True)
    layer2.b.set_value(cPickle.load(f), borrow=True)
    ...
    f.close()
    

    【讨论】:

    • 成功了!伙计,你太棒了!谢谢!我使用如下代码,#layer0 = pickle.load(open('best_model_layer0.pkl')) #layer1 = pickle.load(open('best_model_layer1.pkl')) #layer2 = pickle.load(open('best_model_layer2. pkl')) #layer3 = pickle.load(open('best_model_layer3.pkl')) 但每次都预测为[0]。您的代码解决了一切问题!
    • Okey.. 很高兴它有效 :) 如果您认为这是一个已被接受的答案,您可以在我的答案中单击已接受的符号(“v”复选符号)以通知未来的读者
    • 是的,我想要,但我的声誉还不够 :(
    • 哇,认真的吗?我认为接受答案不需要最低限度的声誉,但没关系
    猜你喜欢
    • 2016-12-03
    • 2016-12-01
    • 2017-04-02
    • 2015-12-15
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    相关资源
    最近更新 更多