PyTorch2 Python深度学习 - 张量(Tensor)的定义与操作

锋哥原创的PyTorch2 Python深度学习视频教程:

https://www.bilibili.com/video/BV1eqxNzXEYc

课程介绍

​基于前面的机器学习Scikit-learn,深度学习Tensorflow2课程,我们继续讲解深度学习PyTorch2,所以有些机器学习,深度学习基本概念就不再重复讲解,大家务必学习好前面两个课程。本课程主要讲解基于PyTorch2的深度学习核心知识,主要讲解包括PyTorch2框架入门知识,环境搭建,张量,自动微分,数据加载与预处理,模型训练与优化,以及卷积神经网络(CNN),循环神经网络(RNN),生成对抗网络(GAN),模型保存与加载等。

PyTorch2 Python深度学习 - 张量(Tensor)的定义与操作

张量是一种特殊的数据结构,与数组和矩阵非常相似。在 PyTorch2 中,我们使用张量来定义模型的输入和输出,以及模型的参数。

1,张量的定义

张量是一个具有相同数据类型的元素的多维矩阵。张量的维度被称为"秩"(rank),张量的形状(shape)决定了它的维度。例如:

  • 标量:零维张量(0D)

  • 向量:一维张量(1D)

  • 矩阵:二维张量(2D)

  • 多维数组:三维或更高维的张量(3D+)

2,创建张量

可以通过多种方式来创建张量,常见的有从列表创建,使用 torch.zeros 创建全零张量,使用 torch.ones 创建全一张量,使用 torch.rand 创建随机张量,从 NumPy 数组转换,下面是示例:

复制代码
import torch
​
# 从 Python 列表创建一个一维张量
tensor_1d = torch.tensor([1, 2, 3, 4, 5])
print(tensor_1d)  # 输出:tensor([1, 2, 3, 4, 5])
​
# 从嵌套列表创建二维张量
tensor_2d = torch.tensor([[1, 2], [3, 4], [5, 6]])
print(tensor_2d)  # 输出:tensor([[1, 2], [3, 4], [5, 6]])
​
# 创建一个形状为 (2, 3) 的全零张量
tensor_zeros = torch.zeros(2, 3)
print(tensor_zeros)  # 输出:tensor([[0., 0., 0.], [0., 0., 0.]])
​
# 创建一个形状为 (3, 3) 的全一张量
tensor_ones = torch.ones(3, 3)
print(tensor_ones)  # 输出:tensor([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]])
​
# 创建一个形状为 (2, 2) 的随机张量,元素值在 [0, 1) 范围内  torch.randn() 是 PyTorch 中用于生成服从标准正态分布(均值为 0,标准差为 1)的随机张量的函数。
tensor_rand = torch.rand(2, 2)
print(tensor_rand)  # 输出:tensor([[0.1353, 0.7184], [0.5225, 0.8931]])
​
import numpy as np
​
# 创建一个 NumPy 数组
np_array = np.array([1, 2, 3])
​
# 将 NumPy 数组转换为 PyTorch 张量
tensor_from_numpy = torch.tensor(np_array)
print(tensor_from_numpy)  # 输出:tensor([1, 2, 3])

运行输出:

复制代码
tensor([1, 2, 3, 4, 5])
tensor([[1, 2],
        [3, 4],
        [5, 6]])
tensor([[0., 0., 0.],
        [0., 0., 0.]])
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
tensor([[0.5516, 0.5451],
        [0.2829, 0.1066]])
tensor([1, 2, 3])
3,张量的常见操作

张量的常见操作有张量加法,张量乘法,张量维度变换,张量转置,张量拼接,张量切片等。下面是示例:

复制代码
import torch
​
# 两个张量相加
tensor_a = torch.tensor([1, 2, 3])
tensor_b = torch.tensor([4, 5, 6])
sum_tensor = tensor_a + tensor_b
print(sum_tensor)  # 输出:tensor([5, 7, 9])
​
# 张量元素级别的乘法
product_tensor = tensor_a * tensor_b
print(product_tensor)  # 输出:tensor([4, 10, 18])
​
# 矩阵乘法
matrix_a = torch.tensor([[1, 2], [3, 4]])
matrix_b = torch.tensor([[5, 6], [7, 8]])
matrix_product = torch.matmul(matrix_a, matrix_b)
print(matrix_product)
​
# 改变张量的形状(例如,1D → 2D)
tensor_1d = torch.tensor([1, 2, 3, 4, 5, 6])
reshaped_tensor = tensor_1d.view(2, 3)  # 变换为2行3列的矩阵
print(reshaped_tensor)  # 输出:tensor([[1, 2, 3], [4, 5, 6]])
​
# 对一个二维张量进行转置
tensor_2d = torch.tensor([[1, 2], [3, 4], [5, 6]])
transposed_tensor = tensor_2d.T
print(transposed_tensor)  # 输出:tensor([[1, 3, 5], [2, 4, 6]])
​
# 按维度拼接两个张量
tensor_a = torch.tensor([1, 2])
tensor_b = torch.tensor([3, 4])
concatenated_tensor = torch.cat((tensor_a, tensor_b), dim=0)
print(concatenated_tensor)  # 输出:tensor([1, 2, 3, 4])
​
# 获取张量的切片
tensor = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(tensor)
slice_tensor = tensor[1:, 1:]
print(slice_tensor)  # 输出:tensor([[5, 6], [8, 9]])

运行输出:

复制代码
tensor([5, 7, 9])
tensor([ 4, 10, 18])
tensor([[19, 22],
        [43, 50]])
tensor([[1, 2, 3],
        [4, 5, 6]])
tensor([[1, 3, 5],
        [2, 4, 6]])
tensor([1, 2, 3, 4])
tensor([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])
tensor([[5, 6],
        [8, 9]])
4,张量的常见属性
  • tensor.shape: 返回张量的形状(即维度)

  • tensor.size(): 返回张量的尺寸,和 .shape 类似

  • tensor.device: 返回张量所在的设备(CPU 或 GPU)

  • tensor.dtype: 返回张量的数据类型

示例:

复制代码
import torch
​
tensor_2d = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
print(tensor_2d.shape)  # 输出:torch.Size([2, 2])
print(tensor_2d.device)  # 输出:cpu
print(tensor_2d.dtype)  # 输出:torch.float32

运行输出:

复制代码
torch.Size([2, 2])
cpu
torch.float32
相关推荐
weixin_440730502 分钟前
playwright实战-渠道应用操作
开发语言·前端·python
asdzx673 分钟前
Python 解析 Excel 数据、图片与图表的实现方案
python·excel
砚底藏山河4 分钟前
存储选型实战:CSV-SQLite-MySQL同机基准(魔码量化实战 #02)
java·数据库·python·金融·maven
陈年老古董8 分钟前
Python模拟MapReduce分治思想 | 从单文件统计到大文件拆分聚合 学习笔记
开发语言·hadoop·笔记·python·学习
quantdash_cc8 分钟前
数据 API 的稳定性应该如何长期监控?从量化数据监控体系到 QuantDash 实践
开发语言·python·数据分析·量化交易·股票数据·quantdash
水龙吟啸10 分钟前
华为研发岗AI方向9.9机考题复盘&分析
人工智能·python·算法·华为
AI人工智能+11 分钟前
炫彩活体检测利用手机屏幕发出动态彩色光,通过分析人脸皮肤对红、绿、蓝光的次表面散射特性,区分真人与照片、视频、3D面具等伪造物
人工智能·深度学习·人脸识别·人脸活体检测·炫彩活体检测
nanawinona13 分钟前
先跑通小流程,再扩展量化功能
人工智能·python
hongyucai14 分钟前
一个碗引发的血案
python·几何学·拓扑学
佳児素花痴╮20 分钟前
C++速通2
开发语言·c++·算法