torch / nngraph

Graph Computation for nn
Other
299 stars 97 forks source link

how to access node in a trained gmodule #146

Closed vanpersie32 closed 7 years ago

vanpersie32 commented 7 years ago

hello, soumith, I have some question.If I have a trained gmodules, how can I have access to node in the gModules? @soumith

Naruto-Sasuke commented 7 years ago

net.modules[i] it is the topological order of gmodle graph. Or you can use

    local ind = 10
   local latent = nil
    for indexNode, node in pairs(net.forwardnodes) do
        if indexNode == ind then
            if node.data.module then
                latent = node.data.module.output:clone()  -- use it to get the specific module output
            end          
        end
    end

Note that the net.forwardnodes has a dump node(spliting inputs into different input nodes). So net.forwardnodes[10] equals net.modules[9]

vanpersie32 commented 7 years ago

@Naruto-Sasuke thank you for your kind reply. It works. I also find nnquery https://github.com/bshillingford/nnquery also solve the problem quickly

Naruto-Sasuke commented 7 years ago

It seems that the docs have not describe about the way to get the intermediate layer info. And some people want to know it. Here I give more info about it. In fact you can print out the nngraph model, and you can do it like this.

-- A simple function for printing nngraph model
function printNet(net)
    for i = 1, net:size(1) do
        print(string.format("%d: %s", i, net.modules[i]))
    end
end

It just prints out the topological order of nngraph. So you need to tell which layer you want(It should not be tough), then you can just net.modules[i] to get the exact layer you want. Or you want just traverse the forwardnodes, and then get your layer or do something else. It has been stated above.

varghesealex90 commented 7 years ago

Hi;

As suggested by Naruto, net.modules[i] seems to do the trick.

require 'nngraph' require 'image' ----load a simple model

a= nn.Identity()() b= nn.SpatialConvolution(3,4,3,3) (a) c= nn.SpatialMaxPooling(2,2) (b)

model=nn.Sequential() model:add(nn.gModule({a},{c}))

---- load data and forward pass the data data= image.lena() pred= model:forward(data)

----- now to see output of maxpool put 3 in get (), 2 to see convolution feature maps res=model.modules[1]:get(3).output

---- now reshape the feature map res= res:view(res:size(1),1,res:size(2),res:size(3))

itorch.image(res)