1

我是新的深度學習,我有一個問題。 我正在使用Theano進行圖像識別,並且我想使用訓練好的模型創建一個預測系統。 我引用了LeNet5 Convolutional Neural Networks (LeNet)並訓練了我自己的數據,現在我想使用訓練好的模型來預測新圖像。 在Classifying MNIST digits using Logistic Regression它描述了醃製訓練模型的方式,但它只是一個邏輯迴歸,而不是多層CNN。以同樣的方式,我保存了每一層,但我不能用它進行預測。 請幫幫我! 這裏是我的代碼:醃製多層CNN的Theano,Lenet5

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) 

回答

2

有很多方法可以保存你的模型。一個我經常使用是通過泡菜各個層的重量和偏壓(該順序是由你):

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() 
+0

工作!男人,你太棒了!謝謝!我使用如下代碼:#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]。你的代碼找出了一切! –

+0

Okey ..很高興它的作品:)如果您認爲這是一個被接受的答案,您可以在我的答案中點擊接受的符號('v'檢查符號)以通知未來的讀者 – malioboro

+0

是的我想但我的名聲不夠: –