当前位置: 首页 > news >正文

PyTorch 张量学习

PyTorch 张量学习

文章目录

  • PyTorch 张量学习
    • 什么是张量?
    • 张量的特点
    • 基础示例
      • 创建一维张量
      • 从NumPy数组创建张量
      • 创建2D张量(矩阵)
    • 张量的属性
      • 属性使用示例
    • 张量的操作
      • 基础操作
      • 形状操作
      • 综合操作示例
    • 张量与 NumPy 的互操作
    • 总结

什么是张量?

张量(Tensor)是PyTorch中的核心数据结构,可以理解为多维数组或矩阵的扩展。

张量的特点

  1. 多维性:张量可以有多个维度

    • 0维张量:标量(单个数字)
    • 1维张量:向量
    • 2维张量:矩阵
    • 3维及以上:更高维数组
  2. 数据类型统一:张量中的所有元素必须是相同的数据类型

  3. GPU支持:张量可以在CPU或GPU上进行计算

  4. 自动求导:PyTorch张量支持自动微分,这对深度学习至关重要

基础示例

创建一维张量

import torch# 创建一维张量
tensor = torch.tensor([10, 20, 30])
print(tensor)

从NumPy数组创建张量

import numpy as np
import torch# NumPy数组转张量
numpy_array = np.array([5, 15, 25])
tensor = torch.from_numpy(numpy_array)
print(tensor)

创建2D张量(矩阵)

2D张量(二维张量)就是矩阵,它有两个维度:行和列。

import torch# 创建4x5矩阵
tensor_2d = torch.tensor([[1, 3, 5, 7, 9],[2, 4, 6, 8, 10],[11, 13, 15, 17, 19],[12, 14, 16, 18, 20]
])
print("2D Tensor:", tensor_2d)
print("Shape:", tensor_2d.shape)

张量的属性

属性说明示例
.shape获取张量的形状tensor.shape
.size()获取张量的形状tensor.size()
.dtype获取张量的数据类型tensor.dtype
.device查看张量所在的设备 (CPU/GPU)tensor.device
.dim()获取张量的维度数tensor.dim()
.requires_grad是否启用梯度计算tensor.requires_grad
.numel()获取张量中的元素总数tensor.numel()
.is_cuda检查张量是否在 GPU 上tensor.is_cuda
.T获取张量的转置(适用于 2D 张量)tensor.T
.item()获取单元素张量的值tensor.item()
.is_contiguous()检查张量是否连续存储tensor.is_contiguous()

属性使用示例

import torch# 创建2x3张量
tensor = torch.tensor([[7, 8, 9], [10, 11, 12]], dtype=torch.float32)# 基本属性
print("Tensor:", tensor)
print("Shape:", tensor.shape)
print("Size:", tensor.size())
print("Data Type:", tensor.dtype)
print("Device:", tensor.device)
print("Dimensions:", tensor.dim())
print("Total Elements:", tensor.numel())# 高级属性
print("Requires Grad:", tensor.requires_grad)
print("Is CUDA:", tensor.is_cuda)
print("Is Contiguous:", tensor.is_contiguous())# 获取单元素值
single_value = torch.tensor(42)
print("Single Element:", single_value.item())# 转置
tensor_T = tensor.T
print("Transposed:", tensor_T)

张量的操作

基础操作

操作说明示例代码
+, -, *, /元素级加法、减法、乘法、除法z = x + y
torch.matmul(x, y)矩阵乘法z = torch.matmul(x, y)
torch.dot(x, y)向量点积(仅适用于 1D 张量)z = torch.dot(x, y)
torch.sum(x)求和z = torch.sum(x)
torch.mean(x)求均值z = torch.mean(x)
torch.max(x)求最大值z = torch.max(x)
torch.min(x)求最小值z = torch.min(x)
torch.argmax(x, dim)返回最大值的索引(指定维度)z = torch.argmax(x, dim=1)
torch.softmax(x, dim)计算 softmax(指定维度)z = torch.softmax(x, dim=1)

形状操作

操作说明示例代码
x.view(shape)改变张量的形状(不改变数据)z = x.view(3, 4)
x.reshape(shape)类似于 view,但更灵活z = x.reshape(3, 4)
x.t()转置矩阵z = x.t()
x.unsqueeze(dim)在指定维度添加一个维度z = x.unsqueeze(0)
x.squeeze(dim)去掉指定维度为 1 的维度z = x.squeeze(0)
torch.cat((x, y), dim)按指定维度连接多个张量z = torch.cat((x, y), dim=1)

综合操作示例

import torch# 创建2x3张量
tensor = torch.tensor([[15, 25, 35], [45, 55, 65]], dtype=torch.float32)
print("原始张量:", tensor)# 1. 索引和切片
print("\n索引和切片:")
print("第一行:", tensor[0])
print("第一行第一列:", tensor[0, 0])
print("第二列:", tensor[:, 1])# 2. 形状变换
print("\n形状变换:")
reshaped = tensor.view(3, 2)
print("改变形状:", reshaped)
flattened = tensor.flatten()
print("展平:", flattened)# 3. 数学运算
print("\n数学运算:")
print("加5:", tensor + 5)
print("乘3:", tensor * 3)
print("求和:", tensor.sum().item())# 4. 张量操作
print("\n张量操作:")
tensor2 = torch.tensor([[2, 2, 2], [2, 2, 2]], dtype=torch.float32)
print("矩阵乘法:", torch.matmul(tensor, tensor2.T))# 5. 条件筛选
print("\n条件筛选:")
print("大于30:", tensor[tensor > 30])

张量与 NumPy 的互操作

操作说明示例代码
torch.from_numpy(ndarray)将 NumPy 数组转换为张量x = torch.from_numpy(np_array)
x.numpy()将张量转换为 NumPy 数组(仅限 CPU 张量)np_array = x.numpy()

总结

本指南涵盖了PyTorch张量的基础知识,包括创建、属性、操作以及与NumPy的互操作。张量是深度学习的核心概念,熟练掌握张量操作是学习PyTorch的重要基础。

http://www.dtcms.com/a/482594.html

相关文章:

  • Network Radar for Mac 网络扫描管理软件
  • 公司 网站制作个人网站开发盈利模式
  • 公明网站制作中卫网站建设哪家好
  • 注塑机ai视觉检测 智能AI视觉检测介绍
  • MySQL8数据库高级特性(下)
  • 系统架构设计师备考第38天——系统架构评估
  • 使用Spring Boot构建Web服务层
  • nano-vllm-0
  • 网站链接怎么做网络规划的内容是什么
  • Android studio 高效使用
  • 提升SEO效果的长尾关键词优化策略与实践分享
  • VScode 中执行 npm 报错的问题
  • 上市的网站设计公司wordpress 强密码 弱
  • 建设电子网站试卷深圳h5开发
  • Java冻结和取消冻结Excel中的行列:让你的数据处理更高效
  • EXCEL如何匹配数据。EXCEL如何自动填入数据。EXCEL如何将另一表格数据匹配进某一表格内。大量数据如何自动复制粘贴。VLOOKUP函数
  • excel拆分单元格?【图文详解】excel单元格批量拆分?多种excel单元格数据拆分方法?
  • 突破Excel局限!SpreadJS让电子表格“活”起来
  • apache poi excel 字体数量限制
  • 关于网站平台建设调研的函青团智慧团建登录入口
  • 金冠钳在牙体预备不足病例中的精细调整与应用策略
  • 怎么查看ttf格式的内容
  • 身体与智能的共舞:具身智能基础知识全解析
  • (论文速读)DEA-Net:基于细节增强卷积和内容引导注意力的单幅图像去雾
  • 网站建设行业赚钱么燕郊做网站的
  • 58同城一样的网站怎样建设眉山手机网站建设
  • Docker快速入门——Windowns系统下Docker安装(2025最新理解与完整,附带WSL1如何升级为WSL2)
  • PortSwigger靶场之CSRF vulnerability with no defenses通关秘籍
  • 企业网站介绍网站开启伪静态需要编写什么代码
  • 玩转Docker Swarm