深度学习基础之张量(全网最全的张量入门知识之一)
1.张量的介绍以及类型
1.1介绍
说起张量,大家可能觉得遥不可及。但事实上,“张量”是数学和物理中的基础概念,而深度学习框架只是将其作为核心数据结构来实现的载体。在深度学习中,张量被广泛用于表示和处理多维数据,如图像、文本和时间序列等。理解张量的本质有助于深入掌握神经网络的工作原理和数据流动机制。
以下是关于张量在不同领域的详细解释:
(1)数学与物理学层面
定义:在数学中,张量是一个几何对象,它描述了向量空间中的线性关系。简单来说,它是标量(0阶张量)、向量(1阶张量)和矩阵(2阶张量)的高维推广。
0阶张量 = 标量 (Scalar)
1阶张量 = 向量 (Vector)
2阶张量 = 矩阵 (Matrix)
3阶及以上 = 多维数组 (Multi-dimensional Array)
应用:广义相对论(描述时空弯曲)、材料力学(描述应力和应变)等领域都大量使用张量。
(2)其他主流深度学习框架
几乎所有现代深度学习框架都内置了“张量”这一核心数据结构,只是名字或具体实现细节略有不同:
| 框架 | 核心数据结构名称 | 说明 |
|---|---|---|
| PyTorch | torch.Tensor |
直接称为 Tensor,动态图,操作直观。 |
| TensorFlow | tf.Tensor |
同样称为 Tensor,早期版本基于静态图,现在(TF 2.x)也支持动态图。 |
| JAX | jax.Array / Array |
JAX 的核心也是张量,强调函数式编程和高性能自动微分。 |
| Keras | tf.Tensor |
Keras 通常作为 TensorFlow 的高级接口,底层数据依然是 TF 的 Tensor。 |
| PaddlePaddle | paddle.Tensor |
百度开发的框架,同样使用 Tensor 概念。 |
| MindSpore | mindspore.Tensor |
华为开发的框架,核心也是 Tensor。 |
1.2类型
0维张量:标量
1维张量:向量
2维张量:矩阵
三维及以上的张量:多维张量
结论:无论你选择哪个框架,理解张量的维度(Shape)、数据类型(Dtype)、内存布局以及广播机制(Broadcasting),都是学习深度学习的必经之路。
2.张量的创建
2.1按照指定数据创建
torch.tensor([数据])
torch.Tensor([数据])
注意:按照指定数据创建的话,数据要以列表的形式传入。而且Tensor()没办法创建标量(0维张量)。
2.2按照指定形状
torch.Tensor(m,n)表示创建形状为·mxn的张量。
2.2.1创建指定的张量数据类型创建
tensor1 = torch.ShortTensor(形状) 类型是int16
tensor2 = torch.IntTensor(形状) 类型是int32
tensor3 = torch.LongTensor(形状) 类型是int64
torch.FloatTensor(形状)
torch.DoubleTensor(形状)
2.2.2创建指定值张量
t1 = torch.tensor([[3,5,6],[45,23,11]])
2.2.3创建线性张量
torch.linespace(start,end,元素个数)
torch.arange(start,end,steps)
2.2.4创建随机张量
设置随机种子:torch.random.manual_seed(11)
torch.randint(0,8,[3,4],generator=torch.manual_seed(11))
3.张量元素类型转换
3.1张量的元素类型
int16 int32 int64 float32 float64
3.2 Int16--->Int32
方法1:
torch.randint(0,8,[3,4]).to(dtype=torch.int32)
方法2:
torch.randint(0,8,[3,4]).long()
3.3Float16--->Float64
方法1:
# 创建一个 float16 类型的张量
tensor_float16 = torch.randn(3, 4).to(torch.float16)
print(f"原始类型: {tensor_float16.dtype}")
# 使用 .to() 方法转换为 float64
tensor_float64 = tensor_float16.to(torch.float64)
print(f"转换后类型: {tensor_float64.dtype}")
方法2:
# 使用 .type() 方法转换为 float64
tensor_float64_2 = tensor_float16_2.type(torch.float64)
print(f"转换后类型: {tensor_float64_2.dtype}")
.type(dtype): 这是较老的方式,专门用于改变数据类型。虽然功能上 .to() 可以完全替代它,但在教学或对比时,.type() 常被列为第二种方法。
4.张量的运算
加减乘除
import torch
# 创建两个相同的张量
a = torch.tensor([[1, 2, 3], [4, 5, 6]]) b = torch.tensor([[7, 8, 9], [10, 11, 12]])
print("张量 a:",a) print("\n张量 b:",b)
# 加法
print("\n加法 (a + b):")
print(a + b)
# 减法 print("\n减法 (a - b):")
print(a - b)
# 乘法(元素级)
print(a * b)
# 除法
print(a / b)
# 幂运算
print(a ** 2)
指数对数平方根
# 创建一个正数张量 c = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0])
# 自然指数 e^x
print("\n自然指数 (torch.exp(c)):")
# 以e为底的对数 ln(x)
print(torch.log(c))
# 以10为底的对数 log10(x)
print(torch.log10(c))
# 平方根 sqrt(x)
print(torch.sqrt(c))
# 绝对值
print(torch.abs(c))
点乘
# 点乘(逐元素相乘)
print("\n点乘 (d * e):")
print(d * e)# 使用 torch.mul() 函数
print("\n使用 torch.mul():")
print(torch.mul(d, e))
矩阵乘法
print("\n矩阵乘法 (f @ g 或 torch.matmul(f, g)):")
print(f @ g)
print(torch.matmul(f, g))# 使用 torch.mm() (仅适用于二维矩阵)
print("\n使用 torch.mm():")
print(torch.mm(f, g))
张量的函数运算
# 各种数学函数
print("\n正弦 (torch.sin(h)):")
print(torch.sin(h))print("\n余弦 (torch.cos(h)):")
print(torch.cos(h))print("\n正切 (torch.tan(h)):")
print(torch.tan(h))print("\n双曲正弦 (torch.sinh(h)):")
print(torch.sinh(h))print("\n双曲余弦 (torch.cosh(h)):")
print(torch.cosh(h))# 其他常用函数
print("\n四舍五入 (torch.round(h)):")
print(torch.round(h))print("\n向下取整 (torch.floor(h)):")
print(torch.floor(h))print("\n向上取整 (torch.ceil(h)):")
print(torch.ceil(h))print("\n最大值 (torch.max(h)):")
print(torch.max(h))print("\n最小值 (torch.min(h)):")
print(torch.min(h))print("\n均值 (torch.mean(h)):")
print(torch.mean(h))print("\n标准差 (torch.std(h)):")
print(torch.std(h))print("\n求和 (torch.sum(h)):")
print(torch.sum(h))
5.张量的索引操作
5.1索引切片操作
这里以实例入手:
torch.random.manual_seed(11)
# 1.随机生成数据 生成4x5的0-10的随机整数张量
tensor = torch.randint(0, 11, [5, 5])
# print(f'tenser-->\n{tensor}')
# 2.简单行列索引的使用
# # 返回第一行的数据
# print(tensor[0])
# # 返回第一列的数据 tensor[行,列]
# print(tensor[:, 0])
5.2多维索引操作
# 生成3x4x5的0-10的随机整数张量
tensor_3d = torch.randint(0, 11, (3, 4, 5))
print("原始三维张量 (3x4x5) 形状:", tensor_3d.shape)# # 获取0轴上的第一个数据
# 0轴是第一个维度,取 index 0
# 结果是一个 4x5 的二维张量
dim0_first = tensor_3d[0]
print("\n 10. 获取0轴上的第一个数据 (形状变为 4x5):")
print(dim0_first)# # 获取1轴上的第一个数
# 1轴是第二个维度,取 index 0
# 结果是一个 3x5 的二维张量 (保留了0轴和2轴)
dim1_first = tensor_3d[:, 0, :]
print("\n11. 获取1轴上的第一个数 (保留0轴和2轴,形状变为 3x5):")
print(dim1_first)
5.3列表索引操作
# 列表索引的使用
# 2.a.返回(1,0)(2,4)两个位置的元素
# print(tensor[[1, 2], [0, 4]])
# print(tensor[[3, 2, 0], [2, 0, 1]])
# b.返回 0,3,4行的3,4列共6个元素
# print(tensor[[[0],[3],[4]],[3,4]])
5.4布尔索引操作
# 第三列大于5的 行数据 需求倒推法
# 第三列大于5
# print(tensor[:, 3] >5)
# print(tensor[tensor[:, 3] > 5, :])
# print(tensor[[1,2,3], :])# 第2行大于5的 列数据
# print(tensor[:, tensor[2, :] > 5])
# 第2列大于2的 行数据 前2行# print(tensor[tensor[:, 2] > 2, :][:2])
更多推荐


所有评论(0)