0

I was browsing the pytorch documentation and noticed a different way of expressing imports that I never encountered before:

import torch.nn as nn

I would have usually written this as:

from torch import nn

At a first glance both methods look to me like they achieve the same thing, am I correct? Are there any differences between those methods? If not is there a best-practice suggesting to use one over the other?

martineau
  • 119,623
  • 25
  • 170
  • 301
Matteo Zanoni
  • 3,429
  • 9
  • 27
  • 2
    Practically they're the same. Under the hood, they're different. https://stackoverflow.com/questions/9439480/from-import-vs-import – Eric Lee Oct 19 '21 at 16:02

1 Answers1

2
import torch.nn as nn

This is a bit confusing since both names end with nn, so with a bit different example-

import torch.nn as x

This is like "assigning" torch.nn in x.
I.e. x.foo is exactly as torch.nn.foo.

from torch import nn

Here nn is an abberviation form. nn.foo is the same as torch.nn.foo.

There is another way to import with named imports:

from torch import nn as x

Which will allow you to call torch.nn module by calling x.
Hope it's more clear now

jsofri
  • 227
  • 1
  • 10
  • Thanks, but i feel my question still lacks an answer... Can you confirm that `import torch.nn as x` is absolutely identical to `from torch import nn as x`? If so do you also feel like there is a preferred way to do so? I was a bit confused by the example as well but it is [here](https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#define-a-convolutional-neural-network) – Matteo Zanoni Oct 19 '21 at 18:49
  • yes. you can print x in each case and see that it's referring to the same module – jsofri Oct 20 '21 at 05:12