How to predict using model generated by Torch?

2019-07-13 03:39发布

问题:

I have executed the neuralnetwork_tutorial.lua. Now that I have the model, I would like to test it with some of my own handwritten images. But I have tried many ways by storing the weights, and now by storing the complete model using torch save and load methods.

However now that I try to predict my own handwritten images(converted to 28X28 DoubleTensor) using model:forward(testImageTensor)

...ches/torch/install/share/lua/5.1/dp/model/sequential.lua:30: attempt to index local 'carry' (a nil value)
stack traceback:
        ...ches/torch/install/share/lua/5.1/dp/model/sequential.lua:30: in function '_forward'
        ...s/torches/torch/install/share/lua/5.1/dp/model/model.lua:60: in function 'forward'
        [string "model:forward(testImageTensor)"]:1: in main chunk
        [C]: in function 'xpcall'
        ...aries/torches/torch/install/share/lua/5.1/trepl/init.lua:588: in function 'repl'
        ...ches/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:185: in main chunk
        [C]: at 0x0804d650

回答1:

You have two options.

One. Use the encapsulated nn.Module to forward your torch.Tensor:

mlp2 = mlp:toModule(datasource:trainSet():sub(1,2))
input = testImageTensor:view(1, 1, 32, 32)
output = mlp2:forward(input)

Two. Encapsulate your torch.Tensor into a dp.ImageView and forward that through your dp.Model :

inputView = dp.ImageView('bchw', testImageTensor:view(1, 1, 32, 32))
outputView = mlp:forward(inputView, dp.Carry{nSample=1})
output = outputView:forward('b')