Print tensor type?

How to print out the tensor type without printing out the whole tensor?

9 Likes

Simple: tensor.type(). Unfortunately the docs aren’t totally clear that this works so easily.

13 Likes

Actually tensor.type() without any arguments returns an error that it’s missing an unspecified positional argument.

3 Likes

Something unusual about the tensor that you’re working with? The following should work fine (note that the Python builtin type also gives what you want).

>>> import torch
>>> a = torch.ones(1)
>>> a.type()
'torch.FloatTensor'
>>> type(a)
<class 'torch.FloatTensor'>
2 Likes

Thanks. It seems that the issue has to do with if the tensor is a Variable.

import torch
from torch.autograd import Variable
a = torch.ones(1)
a.type()
'torch.FloatTensor’
type(a)
< class ‘torch.FloatTensor’>
b = Variable(a)
print(b.type())
TypeError: type() missing 1 required positional argument: 't’
print(b.data.type())
< class ‘torch.FloatTensor’>

the right way to do this is type(tensor)

3 Likes

If the object is a torch Variable, not the plain torch Tensor, using type() method of the object without any argument will cause this error.

TypeError: type() missing 1 required positional argument: ‘t’

But it is not clear what this error message means.

6 Likes

If you have a torch variable say a then simply do

type(a.data)

to know its type

2 Likes

In current builds, type(new Tensor(5)) now always returns ‘Variable’ instead of the actual tensor type… Is that a bug?

That’s not expected behavior I believe. Here is what I receive:

>>> type(torch.Tensor(5))
<class 'torch.FloatTensor'>

To summarize this thread:

  • To print tensor type use: print(type(tensor))
  • To print variable tensor type use: print(type(tensor.data))

In the latest stable release (0.4.0) type() of a tensor no longer reflects the data type.
You should use tensor.type() and isinstance() instead.
Have a look at the Migration Guide for more information.

10 Likes