本人学习pytorch主要参考官方文档和 莫烦Python中的pytorch视频教程。
后文主要是对pytorch官网的文档的总结。
pytorch基础库
import torch
import torchvision
pytorch矩阵创建
#生成全0矩阵
x = torch.empty(5, 3)
print(x)
tensor([[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000]])
#生成全0矩阵并确定数据类型
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
#生成随机矩阵
x = torch.rand(5, 3)
print(x)
tensor([[0.8699, 0.0466, 0.7531],
[0.4607, 0.2218, 0.4715],
[0.7544, 0.9102, 0.6546],
[0.4535, 0.6450, 0.4187],
[0.3994, 0.5950, 0.7166]])
#生成固定矩阵
x = torch.tensor([5.5, 3])
print(x)
tensor([5.5000, 3.0000])
#生成与x大小相同的随机矩阵
x = torch.randn_like(x, dtype=torch.float)
print(x)
tensor([0.2306, 1.3089])
#获取矩阵大小
print(x.size())
#实际输出格式是列表
torch.Size([2])
![image.png](https://img.haomeiwen.com/i6201834/9d80c623bf088c64.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
基础矩阵运算
y = torch.rand(5, 3)
x = torch.rand(5, 3)
#加法
print(x + y)
print(torch.add(x, y))
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
y.add_(x)
print(y)
#带有"_"的方法会修改x。如 x.copy_(y), x.t_()等。
数据截取和改变维度
#数据切片的方法和numpy一样
x = torch.rand(4, 4)
print(x[:, 1])
#改变数据维数
y = x.view(16)
z = x.view(-1, 8) # -1表示该维度由其他维度计算得到,最多只能有一个-1
print(x.size(), y.size(), z.size())
# torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
获取torch数据内容
#对于仅有一个元素的使用item获取
x = torch.randn(1)
print(x)
print(x.item())
torch与numpy格式转化
a = torch.ones(5)
b = a.numpy()
print(b)
# [ 1. 1. 1. 1. 1.]
a = np.ones(5)
b = torch.from_numpy(a)
print(b)
# tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
GPU使用
# 使用``torch.device`` 将tensors移动到GPU
if torch.cuda.is_available(): #确定cuda是否可用
device = torch.device("cuda") # 一个cuda设备对象
y = torch.ones_like(x, device=device) # 在GPU上创建一个tensor
x = x.to(device) # 将数据一定到cuda上,也可以使用 ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # 通过``.to`` 将数据转移到CPU并显示
网友评论