PyTorch 基础学习(4)- 张量的类型

PyTorch 支持多种 CPU 和 GPU 张量类型。

张量类型

数据类型CPU 张量GPU 张量
32 位浮点数torch.FloatTensortorch.cuda.FloatTensor
64 位浮点数torch.DoubleTensortorch.cuda.DoubleTensor
16 位浮点数N/Atorch.cuda.HalfTensor
8 位整数(无符号)torch.ByteTensortorch.cuda.ByteTensor
8 位整数(有符号)torch.CharTensortorch.cuda.CharTensor
16 位整数(有符号)torch.ShortTensortorch.cuda.ShortTensor
32 位整数(有符号)torch.IntTensortorch.cuda.IntTensor
64 位整数(有符号)torch.LongTensortorch.cuda.LongTensor

创建张量

  1. 从 Python 列表创建:

    import torch
    x = torch.FloatTensor([[1, 2, 3], [4, 5, 6]])
    print(x)
    # 输出:
    # 1  2  3
    # 4  5  6
    
  2. 创建空张量:

    y = torch.IntTensor(2, 4).zero_()
    print(y)
    # 输出:
    # 0  0  0  0
    # 0  0  0  0
    

精度调整

调整精度在计算中非常重要:

  • 内存使用: 精度越高,占用的内存越多。
  • 计算速度: 较低精度的计算通常更快。
  • 数值稳定性: 某些算法在低精度下可能不够稳定。
调整精度的方法
  • 使用特定数据类型: 例如,torch.FloatTensor(32 位浮点)或 torch.DoubleTensor(64 位浮点)。

  • 转换函数: 使用 .float().double().half() 方法转换张量精度。

    x = torch.tensor([1.0, 2.0, 3.0])
    x_double = x.double()  # 转换为 64 位浮点
    x_half = x.half()      # 转换为 16 位浮点
    

CPU 和 GPU 张量类型的使用区别

  1. 计算能力:

    • CPU 张量: 适合一般计算任务。
    • GPU 张量: 适合大规模并行计算,如深度学习。
  2. 数据传输:

    • GPU 张量需要从 CPU 内存转移到 GPU 内存。
  3. 使用方式:

    • 在 GPU 上创建张量时,使用 torch.cuda 模块。例如,tensor.to('cuda') 将张量移动到 GPU。

示例:

import torch

# 在 CPU 上创建张量
x_cpu = torch.tensor([1.0, 2.0, 3.0])

# 将张量移动到 GPU
x_gpu = x_cpu.to('cuda')

# 在 GPU 上创建张量
y_gpu = torch.tensor([4.0, 5.0, 6.0], device='cuda')

# 张量运算
z_gpu = x_gpu + y_gpu

重塑张量

使用 view() 改变张量的形状而不改变其数据:

x = torch.randn(4, 4)
y = x.view(16)   # 展平
z = x.view(-1, 8)  # 重塑为 2x8

张量的复制与移动

  • 复制到 GPU:

    x = x.cuda()
    
  • 复制到 CPU:

    x = x.cpu()
    

转换为 NumPy

使用 numpy() 将 PyTorch 张量转换为 NumPy 数组:

a = torch.ones(5)
b = a.numpy()

应用实例:多项式回归

import torch
import torch.nn as nn
import matplotlib.pyplot as plt

# 生成一些非线性数据
x = torch.linspace(-3, 3, 100).reshape(-1, 1)  # 输入特征
y = x ** 3 + 2 * x ** 2 + 3 * x + torch.randn(x.size()) * 5  # 目标变量,带有噪声的多项式关系


# 定义多项式回归模型
class PolynomialRegressionModel(nn.Module):
    def __init__(self, degree):
        super(PolynomialRegressionModel, self).__init__()
        # 定义线性层,输入为多项式的各个项
        self.poly = nn.Linear(degree, 1)

    def forward(self, x):
        # 获取多项式特征
        x_poly = self.polynomial_features(x)
        # 进行线性变换
        return self.poly(x_poly)

    def polynomial_features(self, x):
        # 生成多项式特征,例如 x, x^2, x^3
        x_poly = torch.cat([x ** i for i in range(1, self.poly.in_features + 1)], dim=1)
        return x_poly


# 初始化模型、损失函数和优化器
degree = 3  # 多项式的阶数
model = PolynomialRegressionModel(degree)
criterion = nn.MSELoss()  # 使用均方误差作为损失函数
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)  # 使用随机梯度下降优化器

# 训练模型
epochs = 1000
for epoch in range(epochs):
    model.train()  # 设置模型为训练模式

    # 前向传播:通过模型获取预测输出
    outputs = model(x)
    loss = criterion(outputs, y)  # 计算损失

    # 反向传播和优化
    optimizer.zero_grad()  # 清除上一步的梯度
    loss.backward()  # 计算梯度
    optimizer.step()  # 更新模型参数

    # 添加梯度裁剪
    torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)

    # 每隔100个epoch打印一次损失
    if (epoch + 1) % 100 == 0:
        print(f'Epoch [{epoch + 1}/{epochs}], Loss: {loss.item():.4f}')

# 可视化结果
model.eval()  # 设置模型为评估模式
with torch.no_grad():  # 关闭梯度计算
    predicted = model(x)  # 获取模型预测
    plt.scatter(x.numpy(), y.numpy(), label='Original Data')  # 绘制原始数据点
    plt.plot(x.numpy(), predicted.numpy(), label='Fitted Line', color='red')  # 绘制拟合曲线
    plt.legend()
    plt.show()  # 显示图形

总结

PyTorch 的 torch.Tensor 类提供了一种在 CPU 和 GPU 上高效处理多维数据的方法,支持各种数学运算。掌握这些基本操作将帮助你在深度学习和其他科学计算中更好地利用 PyTorch。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值