PyTorch入门使用

1. 张量 Tensor

张量是一个统称,其中包括很多类型:
0 阶张量:标量、常数,0-D Tensor
1 阶张量:向量,1-D Tensor
2 阶张量:矩阵,2-D Tensor
3 阶张量

n 阶张量

2. PyTorch 中张量的创建

使用 python 中的列表或序列创建张量

import torch

a = torch.tensor([[1, -1], [2, 3]])
print(a, type(a))

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]])

使用 numpy 中的数组创建张量

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a, type(a))

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32)

使用 torch 中的 api 创建张量

# 创建3x4的空张量,用无用数据填充
torch.empty(3, 4)
# 创建3x4的全是1的张量
torch.ones([3, 4])
# 创建3x4的全是0的张量
torch.zeros([3, 4])
# 创建3x4的全是随机数的张量,随机区间[0, 1)
torch.rand([3, 4])
# 创建3x4的随机整数张量,随机区间[low, high)
torch.randint(low=0, high=10, size=[3, 4])
# 创建3x4的随机数张量,随机值得分布均值为0,方差为1
torch.randn([3, 4])
# 创建单位张量
torch.eye(3, 4)

3. PyTorch 中的常用方法

is_tensor() 检测某个序列是否为 PyTorch 中的张量
is_storage() 检测某个序列是否被存储为 PyTorch 中的张量
tensor.item() 从张量中获取数据(当张量中仅有一个数据可用)

import torch
import numpy as np

a = torch.tensor(np.arange(1))
list1 = [1, 12, 43, 55]
print(a)
print(a.item())
print(torch.is_tensor(list1))
print(torch.is_storage(list1))

# 输出结果
tensor([0], dtype=torch.int32)
0
False
False

转化为 numpy 数组

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
print(a.numpy())

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32)
[[ 1 -1]
 [ 2  3]]

tensor.size() 获取张量形状
tensor.numel() 查看张量元素个数

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
print(a.size())
print(a.numel())

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32)
torch.Size([2, 2])
4

tensor.view() 改变张量形状,浅拷贝,仅仅改变形状

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
b = a.view((1, 4))
print(b)

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32)
tensor([[ 1, -1,  2,  3]], dtype=torch.int32)

tensor.dim() 获取维数
tensor.max() 获取最大值
tensor.min() 获取最小值
tensor.std() 获取标准差
tensor.t() / tensor.transpose() 转置

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
print(a.dim())
print(a.max())
print(a.t())

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32)
2
tensor(3, dtype=torch.int32)
tensor([[ 1,  2],
        [-1,  3]], dtype=torch.int32)

tensor[1, 3] 获取张量中第一行第三列的值(从 0 行 0 列开始)
tensor[1, 3]=100 对张量中第一行第三列的位置赋值 100
tensor[1, 2, 0] 切片

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a[1, 0])
a[1, 0] = 100
print(a)

# 输出结果
tensor(2, dtype=torch.int32)
tensor([[  1,  -1],
        [100,   3]], dtype=torch.int32)

4. Tensor 的数据类型

在 torch 中,默认的数据类型是32位浮点型,常用的不同数据类型的 Tensor有:
32 位的浮点型 torch.FloatTensor,
64 位浮点型 torch.DoubleTensor,
16 位整形 torch.ShortTensor,
32 位整形 torch.IntTensor 和 64 位整形 torch.LongTensor。

关于数据类型的常用方法:

torch.set_default_tensor_type(torch.DoubleTensor) 修改默认数据类型
torch.get_default_dtype() 获取张量默认数据类型
tensor.dtype 获取张量的数据类型

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a, a.dtype)

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32) torch.int32

创建张量时指定数据类型

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]), dtype=torch.float32)
print(a, a.dtype)

# 输出结果
tensor([[ 1., -1.],
        [ 2.,  3.]]) torch.float32

修改数据类型

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]), dtype=torch.int32)
print(a, a.dtype)
a = a.type(torch.float)
print(a, a.dtype)

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32) torch.int32
tensor([[ 1., -1.],
        [ 2.,  3.]]) torch.float32

5. tensor 的其它操作

tensor 和 tensor 相加

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]), dtype=torch.int32)
b = torch.tensor([[4, 5], [2, 1]])
print(a+b)
print(torch.add(a, b))
print(a.add(b))
# 带下划线的方法会对a就地修改
a.add_(b)
print(a)

# 输出结果
tensor([[5, 4],
        [4, 4]])
tensor([[5, 4],
        [4, 4]])
tensor([[5, 4],
        [4, 4]])
tensor([[5, 4],
        [4, 4]], dtype=torch.int32)

tensor 和数字进行操作

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]), dtype=torch.int32)
print(a+10)

# 输出结果
tensor([[11,  9],
        [12, 13]], dtype=torch.int32)

6. CUDA 平台

CUDA (Compute Unified Device Architecture),是 NVIDIA 推出的运算平台,其是一种通用并行计算架构,该架构使 GPU 能够解决复杂的计算问题。
torch.cuda 这个模块增加了对 CUDA tensor 的支持,能够在 cpu 和 gpu 上使用相同的方法操作tensor。
通过.to方法能够把一个 tensor 转移到另外一个设备(比如从CPU转到GPU)。

import torch
import numpy as np

x = torch.tensor(np.array([[1, -1], [2, 3]]), dtype=torch.int32)
# y = torch.tensor([[4, 5], [2, 1]])

if torch.cuda.is_available():
    # 创建一个cuda device对象
    device = torch.device("cuda")
    # 创建一个cuda上的tensor
    y = torch.ones_like(x, device=device)
    print(y)
    # 将x转化为cuda上的tensor
    x = x.to(device)
    print(x)
    z = x + y
    print(z)
    # 将gpu版本的tensor转化为cpu版本
    print(z.to("cpu", torch.double))

# 输出结果
tensor([[1, 1],
        [1, 1]], device='cuda:0', dtype=torch.int32)
tensor([[ 1, -1],
        [ 2,  3]], device='cuda:0', dtype=torch.int32)
tensor([[2, 0],
        [3, 4]], device='cuda:0', dtype=torch.int32)
tensor([[2., 0.],
        [3., 4.]], dtype=torch.float64)

注:可能大家在第一次安装 cuda、pytorch、anaconda 后,验证 torch.cuda.is_available()=True 时会遇到各种问题,本人也是弄了好久才解决,如果大家需要请留言,后续我会写一篇完整的教程。

Original: https://blog.csdn.net/m0_56501706/article/details/123023994
Author: Michael.py
Title: PyTorch入门使用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/69584/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载