PyTorch 预备知识
1. 版本检查
在 官网 下载好后,可以按照如下进行版本检查。
- import torch
- print(torch.__version__)
本地输出:
- 2.4.0+cu124
2. 张量
在 PyTorch 中,基本的数据结构是张量。张量是一个可以包含单一数据类型元素的多维数组。像标量、向量、矩阵都可以看作是张量的特殊形式。
- import torch
- # 创建标量
- scalar = torch.tensor(6)
- print("标量:", scalar)
- print("标量的维度:", scalar.ndim)
- print("标量的值:", scalar.item())
- # 创建向量
- vector = torch.tensor([6, 6])
- print("\n向量:", vector)
- print("向量的维度:", vector.ndim)
- print("向量的形状:", vector.shape)
- # 创建矩阵
- matrix = torch.tensor([[7, 8], [9, 10]])
- print("\n矩阵:\n", matrix)
- print("矩阵的维度:", matrix.ndim)
- print("矩阵的第一行:", matrix[0])
- print("矩阵的形状:", matrix.shape)
- # 创建更高维度的张量
- tensor = torch.tensor([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]])
- print("\n更高维度的张量:\n", tensor)
- print("张量的维度:", tensor.ndim)
- print("张量的形状:", tensor.shape)
- print("张量的第一个元素(矩阵):\n", tensor[0])
本地输出:
- 标量: tensor(6)
- 标量的维度: 0
- 标量的值: 6
- 向量: tensor([6, 6])
- 向量的维度: 1
- 向量的形状: torch.Size([2])
- 矩阵:
- tensor([[ 7, 8],
- [ 9, 10]])
- 矩阵的维度: 2
- 矩阵的第一行: tensor([7, 8])
- 矩阵的形状: torch.Size([2, 2])
- 更高维度的张量:
- tensor([[[1, 2, 3],
- [4, 5, 6],
- [7, 8, 9]]])
- 张量的维度: 3
- 张量的形状: torch.Size([1, 3, 3])
- 张量的第一个元素(矩阵):
- tensor([[1, 2, 3],
- [4, 5, 6],
- [7, 8, 9]])
张量的维度,从打印的形式上看,是最外层括号的数量。
3. 随机张量
可以使用 torch.rand 创建指定维度的随机张量。
- import torch
- # 生成一个三维的随机张量
- random_tensor = torch.rand(2, 3, 4)
- print("三维随机张量:\n", random_tensor)
- print("张量的维度:", random_tensor.ndim)
- # 生成一个用于模拟图像数据的张量
- random_image_size_tensor = torch.rand(224, 224, 3)
- print("\n模拟图像数据的随机张量形状:", random_image_size_tensor.shape)
本地输出:
- 三维随机张量:
- tensor([[[0.2388, 0.8346, 0.5911, 0.5230],
- [0.3957, 0.8030, 0.3961, 0.5112],
- [0.4403, 0.4927, 0.4487, 0.5864]],
- [[0.6315, 0.8137, 0.6968, 0.7826],
- [0.3713, 0.5496, 0.9892, 0.7417],
- [0.9595, 0.9671, 0.1762, 0.4017]]])
- 张量的维度: 3
- 模拟图像数据的随机张量形状: torch.Size([224, 224, 3])
三维张量感觉抽象的话,可以结合图像来理解:三个维度分别对应宽、高和 RGB 值。
4. 零张量和单位张量
可以使用 torch.zeros 创建一个所有元素都为 0 的张量;使用 torch.ones 创建一个所有元素都为 1 的张量。
- import torch
- zeros = torch.zeros(size=(3, 4))
- print("零张量:\n", zeros)
- ones = torch.ones(size=(3, 4))
- print("单位张量:\n", ones)
本地输出:
- 零张量:
- tensor([[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 0., 0.]])
- 单位张量:
- tensor([[1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]])
5. 其他创建张量方式
torch.arange 可以生成一个等间隔数值的一维张量。
torch.zeros_like 可以根据给定的张量生成一个新的零张量,新张量的形状和数据类型与输入张量相同。
- import torch
- one_to_ten = torch.arange(start=1, end=11, step=1)
- print("1到10的整数张量:", one_to_ten)
- ten_zeros = torch.zeros_like(input=one_to_ten)
- print("形状相同的零张量:", ten_zeros)
本地输出:
- 1到10的整数张量: tensor([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
- 形状相同的零张量: tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
6. 数据类型
创建的张量,默认使用 float32 类型。可以使用 type() 方法,将张量从一种数据类型转换成另一种。
不同类型之间的张量进行操作,如果能成功,PyTorch 会自动选择更高精度的数据类型,作为结果数据类型。
- import torch
- float_32_tensor = torch.tensor([3.0, 6.0, 9.0])
- print("原始张量数据类型:", float_32_tensor.dtype)
- float_16_tensor = float_32_tensor.type(torch.float16)
- print("转换为float16的张量:", float_16_tensor)
- # 结果张量的数据类型将遵循更精确的类型(这里是float32)
- result_tensor = float_32_tensor * float_16_tensor
- print("乘法结果张量:", result_tensor)
本地输出:
- 原始张量数据类型: torch.float32
- 转换为float16的张量: tensor([3., 6., 9.], dtype=torch.float16)
- 乘法结果张量: tensor([ 9., 36., 81.])
7. 张量属性
张量的这三个属性很重要:数据类型(dtype)、形状(shape)和设备(device)。
- import torch
- some_tensor = torch.rand(3, 4)
- print("随机张量:\n", some_tensor)
- print(f"张量的数据类型: {some_tensor.dtype}")
- print(f"张量的形状: {some_tensor.shape}")
- print(f"张量所在的设备: {some_tensor.device}")
本地输出:
- 随机张量:
- tensor([[0.2504, 0.5435, 0.1293, 0.9244],
- [0.4105, 0.0778, 0.7599, 0.5284],
- [0.7450, 0.4227, 0.0662, 0.6182]])
- 张量的数据类型: torch.float32
- 张量的形状: torch.Size([3, 4])
- 张量所在的设备: cpu
8. 张量运算
张量的基本算术运算:加法(+ 或 torch.add);减法(- 或 torch.sub);乘法(* 或 torch.multiply);除法(/ 或 torch.div)。以上这些运算都是逐元素的。
乘法有点不同,还有一个矩阵乘法,使用 @ 或 torch.matmul。
- import torch
- tensor = torch.tensor([1, 2, 3])
- print("张量:", tensor)
- # 张量与标量的加法(逐元素)
- print("\n每个元素加 10 :", tensor + 10)
- print("使用 torch.add:", torch.add(tensor, 10))
- # 乘法(逐元素)
- print("\n每个元素乘以 10:", tensor * 10)
- print("使用 torch.multiply:", torch.multiply(tensor, 10))
- print("张量与张量的乘法:", tensor * tensor)
- # 张量的矩阵乘法
- print("\n张量的矩阵乘法:", torch.matmul(tensor, tensor))
- print("使用@符号:", tensor @ tensor)
本地输出:
- 张量: tensor([1, 2, 3])
- 每个元素加 10 : tensor([11, 12, 13])
- 使用 torch.add: tensor([11, 12, 13])
- 每个元素乘以 10: tensor([10, 20, 30])
- 使用 torch.multiply: tensor([10, 20, 30])
- 张量与张量的乘法: tensor([1, 4, 9])
- 张量的矩阵乘法: tensor(14)
- 使用@符号: tensor(14)
9. 转置
可用使用张量的 .T 属性进行矩阵转置。
- import torch
- tensor_A = torch.tensor([[1, 2],
- [3, 4],
- [5, 6]])
- tensor_B = torch.tensor([[7, 8],
- [9, 10],
- [11, 12]])
- print("张量 A:\n", tensor_A)
- print("张量 B:\n", tensor_B)
- result = torch.mm(tensor_A, tensor_B.T)
- print("A * B^T:\n", result)
torch.mm 也是矩阵乘法。是 torch.matmul 的缩写。
本地输出:
- 张量 A:
- tensor([[1, 2],
- [3, 4],
- [5, 6]])
- 张量 B:
- tensor([[ 7, 8],
- [ 9, 10],
- [11, 12]])
- A * B^T:
- tensor([[ 23, 29, 35],
- [ 53, 67, 81],
- [ 83, 105, 127]])
10. 张量聚合
张量聚合是将张量中的元素合并到一个单一结果或较小张量集的操作。通常涉及计算总和、平均值、最小值、最大值这些统计量。
- import torch
- x = torch.arange(0, 100, 10)
- print("张量 x:", x)
- print("张量 x 的数据类型:", x.dtype)
- # 计算并打印张量的最小值
- print("\n张量的最小值 (函数调用):", torch.min(x))
- print("张量的最小值 (方法调用):", x.min())
- # 计算并打印张量的最大值
- print("\n张量的最大值 (函数调用):", torch.max(x))
- print("张量的最大值 (方法调用):", x.max())
- # 计算并打印张量的平均值
- x_float = x.type(torch.float32)
- print("\n张量的平均值 (函数调用):", torch.mean(x_float))
- print("张量的平均值 (方法调用):", x_float.mean())
- # 计算并打印张量的总和
- print("\n张量的总和 (函数调用):", torch.sum(x))
- print("张量的总和 (方法调用):", x.sum())
计算平均值需要是浮点类型。
本地输出:
- 张量 x: tensor([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
- 张量 x 的数据类型: torch.int64
- 张量的最小值 (函数调用): tensor(0)
- 张量的最小值 (方法调用): tensor(0)
- 张量的最大值 (函数调用): tensor(90)
- 张量的最大值 (方法调用): tensor(90)
- 张量的平均值 (函数调用): tensor(45.)
- 张量的平均值 (方法调用): tensor(45.)
- 张量的总和 (函数调用): tensor(450)
- 张量的总和 (方法调用): tensor(450)
11. 索引函数
可以使用 .argmin 和 .argmax 找出张量中的最大和最小元素的索引。
- import torch
- x = torch.arange(1, 100, 10)
- print("张量:", x)
- min_index = x.argmin() # 返回最小元素的索引
- max_index = x.argmax() # 返回最大元素的索引
- # 打印最小值和最大值的索引
- print("张量中最小值的索引:", min_index)
- print("张量中最大值的索引:", max_index)
本地输出:
- 张量: tensor([ 1, 11, 21, 31, 41, 51, 61, 71, 81, 91])
- 张量中最小值的索引: tensor(0)
- 张量中最大值的索引: tensor(9)
12. reshape 和 view
reshape 和 view 都用于改变张量的形状,但它们在内部处理上有所不同。
reshape 可能会返回一个新的张量或一个共享内存视图,取决于原始张量的内存布局。
view 要求原始数据在内存中连续,且总是返回一个共享原始数据的张量视图。
只是改变形状,总元素的数量还需要和原始张量保持一致。
- import torch
- x = torch.arange(1., 10.)
- print("原始张量:", x)
- print("原始张量的形状:", x.shape)
- reshaped_tensor = x.reshape(1, 9)
- print("\n使用reshape变换后的张量:", reshaped_tensor)
- print("变换后的张量形状:", reshaped_tensor.shape)
- viewed_tensor = x.view(1, 9)
- print("\n使用view变换后的张量:", viewed_tensor)
- print("变换后的张量形状:", viewed_tensor.shape)
- # 修改通过view创建的张量中的元素,检查原始张量x的变化
- viewed_tensor[:, 0] = 5
- print("\n修改viewed_tensor后的张量:", viewed_tensor)
- print("查看原始张量x的变化:", x)
本地输出:
- 原始张量: tensor([1., 2., 3., 4., 5., 6., 7., 8., 9.])
- 原始张量的形状: torch.Size([9])
- 使用reshape变换后的张量: tensor([[1., 2., 3., 4., 5., 6., 7., 8., 9.]])
- 变换后的张量形状: torch.Size([1, 9])
- 使用view变换后的张量: tensor([[1., 2., 3., 4., 5., 6., 7., 8., 9.]])
- 变换后的张量形状: torch.Size([1, 9])
- 修改viewed_tensor后的张量: tensor([[5., 2., 3., 4., 5., 6., 7., 8., 9.]])
- 查看原始张量x的变化: tensor([5., 2., 3., 4., 5., 6., 7., 8., 9.])
13. stack
stack 将多个同形状的张量合并堆叠成一个新的维度。
- import torch
- tensor1 = torch.rand(2, 3, 4)
- tensor2 = torch.rand(2, 3, 4)
- tensor3 = torch.rand(2, 3, 4)
- # 打印原始张量
- print("Original tensor1:\n", tensor1)
- print("Original tensor2:\n", tensor2)
- print("Original tensor3:\n", tensor3)
- # 沿不同的维度堆叠这些张量
- stacked_dim0 = torch.stack([tensor1, tensor2, tensor3], dim=0)
- stacked_dim1 = torch.stack([tensor1, tensor2, tensor3], dim=1)
- stacked_dim2 = torch.stack([tensor1, tensor2, tensor3], dim=2)
- stacked_dim3 = torch.stack([tensor1, tensor2, tensor3], dim=3)
- # 打印每种堆叠的张量形状
- print("\nStacked along dimension 0 shape:", stacked_dim0.shape)
- print("Stacked along dimension 1 shape:", stacked_dim1.shape)
- print("Stacked along dimension 2 shape:", stacked_dim2.shape)
- print("Stacked along dimension 3 shape:", stacked_dim3.shape)
- # 打印最终堆叠的张量内容
- print("\nContents of Stacked along dimension 0:\n", stacked_dim0)
- print("\nContents of Stacked along dimension 1:\n", stacked_dim1)
- print("\nContents of Stacked along dimension 2:\n", stacked_dim2)
- print("\nContents of Stacked along dimension 3:\n", stacked_dim3)
本地输出:
- Original tensor1:
- tensor([[[0.7199, 0.0911, 0.0740, 0.8454],
- [0.3882, 0.7100, 0.8533, 0.9854],
- [0.7674, 0.3643, 0.4862, 0.3112]],
- [[0.2545, 0.3064, 0.6618, 0.5085],
- [0.8557, 0.7248, 0.4626, 0.8404],
- [0.6944, 0.4044, 0.1186, 0.3678]]])
- Original tensor2:
- tensor([[[0.4120, 0.8468, 0.1986, 0.6609],
- [0.1452, 0.7707, 0.0474, 0.3399],
- [0.3705, 0.4415, 0.1923, 0.8661]],
- [[0.3099, 0.5840, 0.0212, 0.6477],
- [0.7680, 0.0792, 0.3609, 0.6135],
- [0.4450, 0.5942, 0.9047, 0.2399]]])
- Original tensor3:
- tensor([[[0.3059, 0.0484, 0.4267, 0.6936],
- [0.0041, 0.2334, 0.0086, 0.1341],
- [0.2003, 0.1958, 0.7369, 0.2554]],
- [[0.3188, 0.6289, 0.3392, 0.3064],
- [0.9468, 0.3915, 0.4709, 0.6216],
- [0.6450, 0.9173, 0.1603, 0.3267]]])
- Stacked along dimension 0 shape: torch.Size([3, 2, 3, 4])
- Stacked along dimension 1 shape: torch.Size([2, 3, 3, 4])
- Stacked along dimension 2 shape: torch.Size([2, 3, 3, 4])
- Stacked along dimension 3 shape: torch.Size([2, 3, 4, 3])
- Contents of Stacked along dimension 0:
- tensor([[[[0.7199, 0.0911, 0.0740, 0.8454],
- [0.3882, 0.7100, 0.8533, 0.9854],
- [0.7674, 0.3643, 0.4862, 0.3112]],
- [[0.2545, 0.3064, 0.6618, 0.5085],
- [0.8557, 0.7248, 0.4626, 0.8404],
- [0.6944, 0.4044, 0.1186, 0.3678]]],
- [[[0.4120, 0.8468, 0.1986, 0.6609],
- [0.1452, 0.7707, 0.0474, 0.3399],
- [0.3705, 0.4415, 0.1923, 0.8661]],
- [[0.3099, 0.5840, 0.0212, 0.6477],
- [0.7680, 0.0792, 0.3609, 0.6135],
- [0.4450, 0.5942, 0.9047, 0.2399]]],
- [[[0.3059, 0.0484, 0.4267, 0.6936],
- [0.0041, 0.2334, 0.0086, 0.1341],
- [0.2003, 0.1958, 0.7369, 0.2554]],
- [[0.3188, 0.6289, 0.3392, 0.3064],
- [0.9468, 0.3915, 0.4709, 0.6216],
- [0.6450, 0.9173, 0.1603, 0.3267]]]])
- Contents of Stacked along dimension 1:
- tensor([[[[0.7199, 0.0911, 0.0740, 0.8454],
- [0.3882, 0.7100, 0.8533, 0.9854],
- [0.7674, 0.3643, 0.4862, 0.3112]],
- [[0.4120, 0.8468, 0.1986, 0.6609],
- [0.1452, 0.7707, 0.0474, 0.3399],
- [0.3705, 0.4415, 0.1923, 0.8661]],
- [[0.3059, 0.0484, 0.4267, 0.6936],
- [0.0041, 0.2334, 0.0086, 0.1341],
- [0.2003, 0.1958, 0.7369, 0.2554]]],
- [[[0.2545, 0.3064, 0.6618, 0.5085],
- [0.8557, 0.7248, 0.4626, 0.8404],
- [0.6944, 0.4044, 0.1186, 0.3678]],
- [[0.3099, 0.5840, 0.0212, 0.6477],
- [0.7680, 0.0792, 0.3609, 0.6135],
- [0.4450, 0.5942, 0.9047, 0.2399]],
- [[0.3188, 0.6289, 0.3392, 0.3064],
- [0.9468, 0.3915, 0.4709, 0.6216],
- [0.6450, 0.9173, 0.1603, 0.3267]]]])
- Contents of Stacked along dimension 2:
- tensor([[[[0.7199, 0.0911, 0.0740, 0.8454],
- [0.4120, 0.8468, 0.1986, 0.6609],
- [0.3059, 0.0484, 0.4267, 0.6936]],
- [[0.3882, 0.7100, 0.8533, 0.9854],
- [0.1452, 0.7707, 0.0474, 0.3399],
- [0.0041, 0.2334, 0.0086, 0.1341]],
- [[0.7674, 0.3643, 0.4862, 0.3112],
- [0.3705, 0.4415, 0.1923, 0.8661],
- [0.2003, 0.1958, 0.7369, 0.2554]]],
- [[[0.2545, 0.3064, 0.6618, 0.5085],
- [0.3099, 0.5840, 0.0212, 0.6477],
- [0.3188, 0.6289, 0.3392, 0.3064]],
- [[0.8557, 0.7248, 0.4626, 0.8404],
- [0.7680, 0.0792, 0.3609, 0.6135],
- [0.9468, 0.3915, 0.4709, 0.6216]],
- [[0.6944, 0.4044, 0.1186, 0.3678],
- [0.4450, 0.5942, 0.9047, 0.2399],
- [0.6450, 0.9173, 0.1603, 0.3267]]]])
- Contents of Stacked along dimension 3:
- tensor([[[[0.7199, 0.4120, 0.3059],
- [0.0911, 0.8468, 0.0484],
- [0.0740, 0.1986, 0.4267],
- [0.8454, 0.6609, 0.6936]],
- [[0.3882, 0.1452, 0.0041],
- [0.7100, 0.7707, 0.2334],
- [0.8533, 0.0474, 0.0086],
- [0.9854, 0.3399, 0.1341]],
- [[0.7674, 0.3705, 0.2003],
- [0.3643, 0.4415, 0.1958],
- [0.4862, 0.1923, 0.7369],
- [0.3112, 0.8661, 0.2554]]],
- [[[0.2545, 0.3099, 0.3188],
- [0.3064, 0.5840, 0.6289],
- [0.6618, 0.0212, 0.3392],
- [0.5085, 0.6477, 0.3064]],
- [[0.8557, 0.7680, 0.9468],
- [0.7248, 0.0792, 0.3915],
- [0.4626, 0.3609, 0.4709],
- [0.8404, 0.6135, 0.6216]],
- [[0.6944, 0.4450, 0.6450],
- [0.4044, 0.5942, 0.9173],
- [0.1186, 0.9047, 0.1603],
- [0.3678, 0.2399, 0.3267]]]])
堆叠理解起来有点绕,参数中还需要指定堆叠的维度。但从堆叠之后的形状上看,是比较好理解的,就是将新维度“插入”指定的位置。
Stacked along dimension 0 shape: torch.Size([3, 2, 3, 4])
Stacked along dimension 1 shape: torch.Size([2, 3, 3, 4])
Stacked along dimension 2 shape: torch.Size([2, 3, 3, 4])
Stacked along dimension 3 shape: torch.Size([2, 3, 4, 3])
具体堆叠的对象,针对这个用例,我是这么理解的:
dim=0,堆叠的对象是[[[]]]。
dim=1,堆叠的对象是[[]]。
dim=2,堆叠的对象是[]。
dim=3,堆叠的对象是单一元素。
14. squeeze/unsqueeze 和 permute
squeeze 用于移除张量中所有的单一维度(维度大小为 1 的维度)。unsqueeze 用于在指定位置添加一个新的维度。
permute 用于重排张量的维度顺序。比如,图片数据是宽度x高度x通道,可以重排成通道x宽度x高度。
- import torch
- x = torch.arange(1., 10.)
- print("原始张量 x:", x)
- print("原始张量的形状:", x.shape)
- x_reshaped = x.reshape(1, 9)
- print("\nx_reshaped:", x_reshaped)
- print("变换后的张量形状:", x_reshaped.shape)
- x_squeezed = x_reshaped.squeeze()
- print("\n使用squeeze移除单一维度后的张量:", x_squeezed)
- x_unsqueezed = x_squeezed.unsqueeze(dim=0)
- print("\n使用unsqueeze添加新维度后的张量:", x_unsqueezed)
- # 创建一个具有随机值的3通道图像张量 (224x224x3)
- x_original = torch.rand(size=(224, 224, 3))
- x_permuted = x_original.permute(2, 0, 1)
- print("\n原始图像张量的形状:", x_original.shape)
- print("重排维度后的图像张量形状:", x_permuted.shape)
本地输出:
- 原始张量 x: tensor([1., 2., 3., 4., 5., 6., 7., 8., 9.])
- 原始张量的形状: torch.Size([9])
- x_reshaped: tensor([[1., 2., 3., 4., 5., 6., 7., 8., 9.]])
- 变换后的张量形状: torch.Size([1, 9])
- 使用squeeze移除单一维度后的张量: tensor([1., 2., 3., 4., 5., 6., 7., 8., 9.])
- 使用unsqueeze添加新维度后的张量: tensor([[1., 2., 3., 4., 5., 6., 7., 8., 9.]])
- 原始图像张量的形状: torch.Size([224, 224, 3])
- 重排维度后的图像张量形状: torch.Size([3, 224, 224])
15. PyTorch 和 NumPy 转换
torch.from_numpy() 用于将 NumPy 数组转换成 PyTorch 张量。这个转换是内存共享的。
.numpy() 用于将 PyTorch 张量转换成 NumPy 数组。这个转换也是内存共享的。
- import torch
- import numpy as np
- # 创建一个NumPy数组
- array = np.arange(1.0, 8.0)
- tensor = torch.from_numpy(array)
- print("原始的 NumPy 数组:", array)
- print("从 NumPy 数组创建的 PyTorch 张量:", tensor)
- array[0] = 100
- print("修改后的 NumPy 数组:", array)
- print("PyTorch 张量:", tensor)
- # 创建一个PyTorch张量
- tensor = torch.ones(7)
- numpy_tensor = tensor.numpy()
- print("\n原始的 PyTorch 张量:", tensor)
- print("从 PyTorch 张量创建的 NumPy 数组:", numpy_tensor)
- print("NumPy 数组的数据类型:", numpy_tensor.dtype)
- tensor[0] = 200
- print("修改后的 PyTorch 张量:", tensor)
- print("NumPy 数组:", numpy_tensor)
本地输出:
- 原始的 NumPy 数组: [1. 2. 3. 4. 5. 6. 7.]
- 从 NumPy 数组创建的 PyTorch 张量: tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64)
- 修改后的 NumPy 数组: [100. 2. 3. 4. 5. 6. 7.]
- PyTorch 张量: tensor([100., 2., 3., 4., 5., 6., 7.], dtype=torch.float64)
- 原始的 PyTorch 张量: tensor([1., 1., 1., 1., 1., 1., 1.])
- 从 PyTorch 张量创建的 NumPy 数组: [1. 1. 1. 1. 1. 1. 1.]
- NumPy 数组的数据类型: float32
- 修改后的 PyTorch 张量: tensor([200., 1., 1., 1., 1., 1., 1.])
- NumPy 数组: [200. 1. 1. 1. 1. 1. 1.]
转换的类型是自动对应的。注意,NumPy 默认类型是 float64;PyTorch 默认类型是 float32。
16. 随机种子
在 PyTorch 中,通过设定随机种子,可以确保随机操作的可重现性。
- import torch
- # 创建两个随机张量并比较它们
- random_tensor_A = torch.rand(3, 4)
- random_tensor_B = torch.rand(3, 4)
- print("随机张量 A:\n", random_tensor_A)
- print("随机张量 B:\n", random_tensor_B)
- print("随机张量 A 和 B 是否相等:\n", random_tensor_A == random_tensor_B)
- # 设置随机种子以确保随机数生成的可重复性
- RANDOM_SEED = 42
- torch.manual_seed(RANDOM_SEED)
- random_tensor_C = torch.rand(3, 4)
- torch.manual_seed(RANDOM_SEED)
- random_tensor_D = torch.rand(3, 4)
- print("\n随机张量 C:\n", random_tensor_C)
- print("随机张量 D:\n", random_tensor_D)
- print("随机张量 C 和 D 是否相等:\n", random_tensor_C == random_tensor_D)
本地输出:
- 随机张量 A:
- tensor([[0.5061, 0.4897, 0.8705, 0.7014],
- [0.1571, 0.3166, 0.7212, 0.8622],
- [0.7175, 0.4205, 0.8970, 0.8726]])
- 随机张量 B:
- tensor([[0.5317, 0.2673, 0.6956, 0.2626],
- [0.4935, 0.6814, 0.8929, 0.3707],
- [0.4432, 0.5911, 0.1168, 0.6377]])
- 随机张量 A 和 B 是否相等:
- tensor([[False, False, False, False],
- [False, False, False, False],
- [False, False, False, False]])
- 随机张量 C:
- tensor([[0.8823, 0.9150, 0.3829, 0.9593],
- [0.3904, 0.6009, 0.2566, 0.7936],
- [0.9408, 0.1332, 0.9346, 0.5936]])
- 随机张量 D:
- tensor([[0.8823, 0.9150, 0.3829, 0.9593],
- [0.3904, 0.6009, 0.2566, 0.7936],
- [0.9408, 0.1332, 0.9346, 0.5936]])
- 随机张量 C 和 D 是否相等:
- tensor([[True, True, True, True],
- [True, True, True, True],
- [True, True, True, True]])
17. CUDA 支持
在使用 PyTorch 时,可以利用 GPU 提升计算效率。torch.cuda.is_available() 检查当前环境是否支持 CUDA。torch.cuda.device_count() 获取可用的 GPU 数量。
- import torch
- cuda_available = torch.cuda.is_available()
- print("CUDA 是否可用:", cuda_available)
- if cuda_available:
- gpu_count = torch.cuda.device_count()
- print("可用的 GPU 数量:", gpu_count)
- else:
- print("没有检测到可用的 GPU 设备")
本地输出:
- CUDA 是否可用: True
- 可用的 GPU 数量: 1
18. 数据迁移
在 PyTorch 中,数据可以在 CPU 和 GPU 之间迁移。
- import torch
- tensor = torch.tensor([1, 2, 3])
- print("原始张量:", tensor, "位于设备:", tensor.device)
- device = "cuda" if torch.cuda.is_available() else "cpu"
- print("\n使用的设备:", device)
- tensor_on_gpu = tensor.to(device)
- print("\n移至", device, "后的张量:", tensor_on_gpu)
- tensor_back_on_cpu = tensor_on_gpu.cpu()
- print("\n移回 cpu 后的张量:", tensor_back_on_cpu)
本地输出:
- 原始张量: tensor([1, 2, 3]) 位于设备: cpu
- 使用的设备: cuda
- 移至 cuda 后的张量: tensor([1, 2, 3], device='cuda:0')
- 移回 cpu 后的张量: tensor([1, 2, 3])