基本数据操作关于torch
引入 PyTorch
import torch
创建张量
# 创建一个形状为 (2, 3) 的张量,元素为随机数
x = torch.rand(2, 3)
print("随机张量 x:")
print(x)
# 创建一个形状为 (2, 3) 的张量,元素全为零
y = torch.zeros(2, 3)
print("\n零张量 y:")
print(y)
# 创建一个形状为 (2, 3) 的张量,元素全为一
z = torch.ones(2, 3)
print("\n单位张量 z:")
print(z)
# 从 Python 列表创建张量
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
print("\n从列表创建的张量 a:")
print(a)
查看张量的属性
print("\n张量 a 的形状:", a.shape)
print("张量 a 的数据类型:", a.dtype)
print("张量 a 所在的设备:", a.device)
改变张量的形状而不改变数量
X = a.reshape(3, 2)
X
基本运算
加 减 乘 求幂
# 创建两个张量
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])
# 使用加法操作
z = x + y
print("\n加法结果 z = x + y:")
print(z)
z = x - y
print("\n减法结果 z = x - y:")
print(z)
z = x * y
print("\n逐元素乘法结果 z = x * y:")
print(z)
z= x ** y # **是求幂
print("\n逐元素求幂结果 z = x ** y:")
print(z)
指数运算
torch.exp(x)
矩阵乘法(每一行*每一列对应数字相加)
# 创建两个矩阵
a = torch.tensor([[1, 2], [3, 4]])
b = torch.tensor([[5, 6], [7, 8]])
# 矩阵乘法
c = torch.matmul(a, b)
print("\n矩阵乘法结果 c = a @ b:")
print(c)
转置
# 创建一个矩阵
a = torch.tensor([[1, 2], [3, 4]])
print("\n原始矩阵 a:")
print(a)
# 转置矩阵
a_t = a.t()
print("\n转置矩阵 a_t:")
print(a_t)
索引
# 创建一个矩阵
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
print("\n原始矩阵 a:")
print(a)
# 获取第一行
row = a[0]
print("\n第一行:", row)
# 获取第二列
col = a[:, 1]
print("\n第二列:", col)
切片
# 创建一个矩阵
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("\n原始矩阵 a:")
print(a)
# 获取第一行到第二行,第一列到第二列的子矩阵
sub_matrix = a[0:2, 0:2]
print("\n子矩阵 sub_matrix:")
print(sub_matrix)
改变形状
# 创建一个张量
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
print("\n原始张量 a:")
print(a)
# 改变形状为 (3, 2)
a_reshaped = a.view(3, 2)
print("\n改变形状后的张量 a_reshaped:")
print(a_reshaped)
展平
# 创建一个张量
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
print("\n原始张量 a:")
print(a)
# 展平张量
a_flattened = a.view(-1)
print("\n展平后的张量 a_flattened:")
print(a_flattened)
拼接 0是行 1是列
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1)
逻辑运算
广播机制
# 创建两个张量
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
y = torch.tensor([10, 20, 30])
# 广播加法
z = x + y
print("\n广播加法结果 z = x + y:")
print(z)
广播机制允许不同形状的张量进行操作。PyTorch 会自动扩展较小的张量以匹配较大的张量。
使用gpu 在 PyTorch 中,可以通过 .to()
方法将张量或模型移动到 GPU:
# 检查是否有可用的 GPU
if torch.cuda.is_available():
device = torch.device("cuda")
print("使用 GPU")
else:
device = torch.device("cpu")
print("使用 CPU")
# 创建一个张量
x = torch.tensor([1, 2, 3])
print("\n原始张量 x 在", x.device)
# 将张量移动到 GPU
x = x.to(device)
print("移动到", x.device, "后的张量 x:")
print(x)
判断gpu是否启动
import torch
# 检查是否有可用的 GPU
if torch.cuda.is_available():
print("GPU 已启用,设备名称为:", torch.cuda.get_device_name(0))
else:
print("未启用 GPU,当前使用 CPU")
张量的自动求导
# 创建一个张量并设置 requires_grad=True
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
print("\n张量 x 需要计算梯度:", x.requires_grad)
# 对张量进行操作
y = x * x
print("\n操作后的张量 y = x * x:")
print(y)
# 对 y 求和
z = y.sum()
print("\n求和后的张量 z = y.sum():")
print(z)
# 反向传播
z.backward()
print("\n反向传播后,张量 x 的梯度:")
print(x.grad)