Search code examples
luatorch

In lua/torch, write tensor out without printing type


I'm new to lua and just cannot find the answer to what seems a terribly simple question.

I want to print out some tensors which correspond to word embeddings in a Word2Vec style. Each line should start with a word, followed by the tensor elements. I have the following code:

function Word2Vec:print_semantic_space()
    if self.word_vecs_norm == nil then
        self.word_vecs_norm = self:normalize(self.word_vecs.weight:double())
    end
    for word,_ in pairs(self.vocab) do
        vec=self.word_vecs_norm[self.word2index[word]]
        vec:resize(vec:size(1),1) 
        vec=vec:t()
        io.write(word," ",tostring(vec))
    end
end

This is all fine and good, but I keep getting the tensor type and size printed out too:

usually -0.2063  0.5654  0.1447  0.2765 -0.3903  0.2646  0.2254  0.5064 -0.1009 -0.0260
[torch.DoubleTensor of size 1x10]
go -0.5896  0.1330  0.1361 -0.0193 -0.5612  0.3529  0.3683  0.0141  0.0447 -0.1963
[torch.DoubleTensor of size 1x10]

How can I tell lua not to return the type? Like this:

usually -0.2063  0.5654  0.1447  0.2765 -0.3903  0.2646  0.2254  0.5064 -0.1009 -0.0260
go -0.5896  0.1330  0.1361 -0.0193 -0.5612  0.3529  0.3683  0.0141  0.0447 -0.1963

Sorry if the answer is out there and I haven't searched for the right keywords. I'm still new to lua's concepts.


Solution

  • You can write your own dump function, e.g.:

    local dump = function(vec)
        vec = vec:view(vec:nElement())
        local t = {}
        for i=1,vec:nElement() do
            t[#t+1] = string.format('%.4f', vec[i])
        end
        return table.concat(t, '  ')
    end
    

    And use it instead of tostring.