深度学习基础:Tensor(张量)的创建方法详解

文章目录

    • 一、什么是张量(Tensor)?
    • 二、张量的创建方法
      • [1️⃣ 直接创建张量(从列表或数据生成)](#1️⃣ 直接创建张量(从列表或数据生成))
      • [2️⃣ 使用 `torch.zeros()`、`torch.ones()`、`torch.full()` 创建固定值张量](#2️⃣ 使用 torch.zeros()torch.ones()torch.full() 创建固定值张量)
      • [3️⃣ 使用 `torch.arange()`、`torch.linspace()` 创建序列张量](#3️⃣ 使用 torch.arange()torch.linspace() 创建序列张量)
      • [4️⃣ 使用 `torch.rand()`、`torch.randn()` 创建随机张量](#4️⃣ 使用 torch.rand()torch.randn() 创建随机张量)
      • [5️⃣ 使用 `torch.eye()` 创建单位矩阵](#5️⃣ 使用 torch.eye() 创建单位矩阵)
      • [6️⃣ 从 NumPy 数组创建张量](#6️⃣ 从 NumPy 数组创建张量)
      • [7️⃣ 创建与现有张量形状相同的新张量](#7️⃣ 创建与现有张量形状相同的新张量)
    • 三、张量创建总结表
    • [📚 参考资料](#📚 参考资料)

一、什么是张量(Tensor)?

简单来说,张量就是多维数组(multi-dimensional array)

在 PyTorch 中,torch.Tensor 是一个包含数值的多维容器,可以存放在 CPU 或 GPU 上。

具体内容请参考深度学习中的张量(Tensor)入门-CSDN博客

种类 示例 维度
标量(Scalar) torch.tensor(5) 0D
向量(Vector) torch.tensor([1,2,3]) 1D
矩阵(Matrix) torch.tensor([[1,2],[3,4]]) 2D
三维及以上张量 torch.randn(2,3,4) 3D+

二、张量的创建方法

在 PyTorch 中,有多种方式可以创建张量。

下面按类型详细介绍。


1️⃣ 直接创建张量(从列表或数据生成)

  1. 最基础的方式是使用 torch.tensor() 直接从 Python 列表或嵌套列表创建。
python 复制代码
import torch

# 从列表创建张量
x = torch.tensor([1, 2, 3])
print(x)

# 从嵌套列表创建二维张量
m = torch.tensor([[1, 2], [3, 4]])
print(m)

注意

  • 默认数据类型为 torch.float32torch.int64(取决于输入类型)。
  • 可以通过 dtype 参数指定类型:
  1. 也可以使用 torch.Tensor(size) 创建指定形状的张量
python 复制代码
import torch

# 创建指定形状的张量,默认类型为float32
tensor1 = torch.Tensor(3, 2, 4)
print(tensor1)
print(tensor1.dtype)

# 也可以用来创建指定内容的张量
tensor2 = torch.Tensor([[1, 2, 3, 4], [5, 6, 7, 8]])
print(tensor2)
  1. 下边是以上两种方式创建指定类型的张量、

可通过torch.IntTensor()torch.FloatTensor()等创建。

或在torch.tensor()中通过dtype参数指定类型。

python 复制代码
import torch

# 创建int16类型的张量
tensor1 = torch.ShortTensor(2, 2)
tensor2 = torch.tensor([1, 2, 3], dtype=torch.int16)
print(tensor1, tensor1.dtype)
print(tensor2, tensor1.dtype)

# 创建int32类型的张量
tensor1 = torch.IntTensor(2, 3)
tensor2 = torch.tensor([3, 4, 5], dtype=torch.int32)
print(tensor1)
print(tensor2)

# 元素类型不匹配则会进行类型转换
tensor1 = torch.IntTensor([1.1, 2.2, 3.6])
tensor2 = torch.tensor([3.1, 2.2, 1.6], dtype=torch.int32)
print(tensor1)
print(tensor2)

# 创建float32类型的张量
tensor1 = torch.FloatTensor([7, 8, 9])
tensor2 = torch.tensor([1, 2, 3], dtype=torch.float32)
print(tensor1, tensor1.dtype)
print(tensor2, tensor1.dtype)

# 创建float64类型的张量
tensor1 = torch.DoubleTensor(2, 3, 1)
tensor2 = torch.tensor([1, 2, 3], dtype=torch.float64)
print(tensor1)
print(tensor2)

2️⃣ 使用 torch.zeros()torch.ones()torch.full() 创建固定值张量

这类函数非常常用,常用于初始化权重、偏置等。

python 复制代码
# 全零张量
z = torch.zeros((2, 3))
print(z)

# 全一张量
o = torch.ones((2, 3))
print(o)

# 固定值张量
f = torch.full((2, 3), 7)
print(f)

3️⃣ 使用 torch.arange()torch.linspace() 创建序列张量

适合生成规律性的数值序列,是一种指定区间的张量创建。

python 复制代码
# arange: 从 start 到 end(不含 end),步长 step
a = torch.arange(0, 10, 2)
print(a)  # [0, 2, 4, 6, 8]

# linspace: 从 start 到 end,均匀生成 num 个数
b = torch.linspace(0, 1, steps=5)
print(b)  # [0., 0.25, 0.5, 0.75, 1.]

4️⃣ 使用 torch.rand()torch.randn() 创建随机张量

随机张量是深度学习中最常见的初始化方式。

python 复制代码
# [0, 1) 均匀分布
u = torch.rand((2, 3))
print(u)

# 标准正态分布(均值0,方差1),n即normal,代表正态分布
n = torch.randn((2, 3))
print(n)

如果需要指定分布参数,可以使用:

python 复制代码
# 自定义均值和方差
normal = torch.normal(mean=0, std=1, size=(3, 3))

5️⃣ 使用 torch.eye() 创建单位矩阵

在矩阵计算(如线性代数)中非常常用。

python 复制代码
I = torch.eye(3)
print(I)
# 输出:
# tensor([[1., 0., 0.],
#         [0., 1., 0.],
#         [0., 0., 1.]])

6️⃣ 从 NumPy 数组创建张量

PyTorch 与 NumPy 可以方便地相互转换。

python 复制代码
import numpy as np

# NumPy -> Tensor
np_arr = np.array([[1, 2], [3, 4]])
t = torch.from_numpy(np_arr)
print(t)

# Tensor -> NumPy
back = t.numpy()
print(back)

这在数据预处理阶段尤其常见。


7️⃣ 创建与现有张量形状相同的新张量

可以使用以下方法快速创建"形状一致"的张量:

python 复制代码
x = torch.tensor([[1, 2, 3], [4, 5, 6]])

# 与 x 形状相同的全零张量
z = torch.zeros_like(x)

# 与 x 形状相同的全一张量
o = torch.ones_like(x)

# 与 x 形状相同的随机张量
r = torch.rand_like(x, dtype=torch.float)

三、张量创建总结表

方法 功能 示例
torch.tensor(data) 从列表创建张量 torch.tensor([[1,2],[3,4]])
torch.zeros(size) 创建全零张量 torch.zeros((3,3))
torch.ones(size) 创建全一张量 torch.ones((2,4))
torch.full(size, val) 创建固定值张量 torch.full((2,2), 9)
torch.arange(start, end, step) 按步长创建序列 torch.arange(0, 10, 2)
torch.linspace(start, end, steps) 均匀取样序列 torch.linspace(0, 1, 5)
torch.rand(size) 均匀随机分布 torch.rand((2,3))
torch.randn(size) 标准正态分布 torch.randn((2,3))
torch.eye(n) 单位矩阵 torch.eye(3)
torch.from_numpy(arr) 从 NumPy 创建 torch.from_numpy(np_arr)
torch.zeros_like(t) 与张量形状相同 torch.zeros_like(x)

📚 参考资料

相关推荐
白白要坚持3 分钟前
本地部署jina-bert
人工智能·bert·jina
救救孩子把7 分钟前
51-机器学习与大模型开发数学教程-4-13 EM算法与混合模型
人工智能·算法·机器学习
Fuly102413 分钟前
多模态大模型应用技术栈
人工智能·深度学习·计算机视觉
Brduino脑机接口技术答疑19 分钟前
TDCA 算法在 SSVEP 场景中的训练必要性
人工智能·算法·机器学习·脑机接口
悟道心29 分钟前
1.自然语言处理NLP - 入门
人工智能·自然语言处理
雪花desu37 分钟前
深度解析RAG(检索增强生成)技术
人工智能·深度学习·语言模型·chatgpt·langchain
咚咚王者1 小时前
人工智能之数学基础 离散数学:第四章 离散概率
人工智能
阿标在干嘛1 小时前
科力辰平台:作为一个科技查新平台,其核心能力边界在哪里?
人工智能·科技
徽4401 小时前
农田植被目标检测数据标注与模型训练总结3
人工智能·目标检测·目标跟踪
冒泡的肥皂1 小时前
25年AI我得DEMO老师
人工智能·后端