欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

pytorch官方教程学习笔记01:WHAT IS PYTORCH?

程序员文章站 2022-06-11 22:02:18
...

官网

1.创建张量:大小为5行3列:

whatever values were in the allocated memory at the time will appear as the initial values.

x = torch.empty(5, 3)

随机初始化:

x = torch.rand(5, 3)

全零+指定类型:

x = torch.zeros(5, 3, dtype=torch.long)

**自定义初始化:需要用到:【】 **

x = torch.tensor([[1, 2], [3, 4]])

输出大小:

print(x.size())

2.运算:

torch.add(x, y, out=result)
print(result)

直接加到y上了。

y.add_(x)
print(y)

3.改变维度:

x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)  # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())

这里的-1 设计的很妙啊!
pytorch官方教程学习笔记01:WHAT IS PYTORCH?

4.item():只适用于1行1列的tensor变为一个 Python number。

x = torch.randn(1)
print(x)
print(x.item())

pytorch官方教程学习笔记01:WHAT IS PYTORCH?

5.与numpy进行类型互转:

Converting a Torch Tensor to a NumPy Array:

b = a.numpy()

Converting NumPy Array to Torch Tensor:

b = torch.from_numpy(a)

6.最后,但是是最重要的一点:CUDA GPU 相关,用一个.to(设备),将其转化为特定设备上的类型。默认cpu。:

Tensors can be moved onto any device using the .to method.

# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
    device = torch.device("cuda")          # a CUDA device object
    y = torch.ones_like(x, device=device)  # directly create a tensor on GPU
    x = x.to(device)                       # or just use strings ``.to("cuda")``
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # ``.to`` can also change dtype together!

pytorch官方教程学习笔记01:WHAT IS PYTORCH?

相关标签: pytorch