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 设计的很妙啊!
4.item():只适用于1行1列的tensor变为一个 Python number。
x = torch.randn(1)
print(x)
print(x.item())
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!
上一篇: Go官方教程学习笔记
下一篇: 关于java8一些常见的特性使用
推荐阅读
-
PyTorch学习笔记01: PyTorch基本概念
-
学习笔记|Pytorch使用教程25(Batch Normalization)
-
pytorch官方教程学习:AUTOGRAD自动求导
-
pytorch官方教程学习笔记2—— Datasets & DataLoaders
-
pytorch官方教程学习笔记1
-
pytorch官方教程学习笔记01:WHAT IS PYTORCH?
-
机器学习笔记4-0:PyTorch简明教程
-
Pytorch官方教程学习笔记【01】-Pytorch深度学习60分钟闪电战-What is PyTorch?
-
Pytorch官方教程学习笔记(1)
-
pytorch官方教程学习笔记02:AUTOGRAD自动求导