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

PyTorch使用-张量的创建

文章目录

  • 张量的创建
  • 1. 安装 PyTorch
  • 2. 基本创建方式
    • 2.1 torch.tensor 根据指定数据创建张量
    • 2.2. torch.Tensor 根据形状创建张量, 其也可用来创建指定数据的张量
    • 2.3. 指定类型的张量创建
      • 2.3.1. torch.IntTensor:创建整数类型张量
      • 2.3.2. torch.FloatTensor:创建浮点类型张量
      • 2.3.3. torch.DoubleTensor:创建双精度浮点类型张量
    • 2.4. 指定数据类型的其他方式
    • 2.5. 总结
  • 3. 创建线性和随机张量
    • 3.1 创建线性张量
      • 3.1.1. torch.arange:创建等间隔的整数张量
      • 3.1.2. torch.linspace:创建等间隔的浮点数张量
    • 3.2. 随机种子设置
      • 3.2.1 torch.random.manual_seed:设置随机种子
    • 3.3. 创建随机张量
      • 3.3.1. torch.randn:创建标准正态分布的随机张量
      • 3.3.2. torch.rand:创建均匀分布的随机张量
      • 3.3.3. torch.randint:创建整数随机张量
      • 3.4. 总结
  • 4. 创建全 0\1 张量
    • 4.1. 创建全1 张量
      • 4.1.1. torch.ones:创建全 1 张量
      • 4.1.2. torch.ones_like:创建与输入张量形状相同的全 1 张量
    • 4.2. 创建全 0 张量
      • 4.2.1. torch.zeros:创建全 0 张量
      • 4.2.2. torch.zeros_like:创建与输入张量形状相同的全 0 张量
    • 4.3. 创建全为指定值的张量
      • 4.3.1. torch.full:创建全为指定值的张量
      • 4.3.2. torch.full_like:创建与输入张量形状相同的全为指定值的张量
      • 4.4. 总结
  • 5. 张量元素类型转换
    • 5.1. 使用 tensor.type() 方法
    • 5.2. 使用 tensor.double() 方法
    • 5.3. 其他类型转换方法
    • 5.4. 使用 tensor.to() 方法
      • 5.4.1. 转换数据类型
      • 5.4.2. 同时转换设备和数据类型
    • 5.5. 总结

张量的创建

PyTorch 是一个广泛使用的开源深度学习框架,由 Facebook 的 AI 研究团队开发,并以其灵活性和易于使用的特性而受到许多研究者和开发者的喜爱。它将数据封装成张量(Tensor)来进行运算。PyTorch 中的张量就是元素为同一种数据类型的多维矩阵。在 PyTorch 中,张量以 “类” 的形式封装起来,对张量的一些运算、处理的方法被封装在类中。

1. 安装 PyTorch

首先,确保你已经安装了 PyTorch。你可以通过 Python 的包管理器 pip 来安装它:

pip install torch torchvision

2. 基本创建方式

torch.IntTensor、torch.FloatTensor、torch.DoubleTensor 创建指定类型的张量

2.1 torch.tensor 根据指定数据创建张量

torch.tensor 是直接从数据(如列表、元组等)创建张量的方法。它会根据输入的数据推断数据类型(dtype)。

import torch
# 从列表创建张量
data = [1, 2, 3, 4]
x = torch.tensor(data)
print(x)
print(x.dtype)  # 默认推断为 torch.int64
程序输出:
tensor([1, 2, 3, 4])
torch.int64

2.2. torch.Tensor 根据形状创建张量, 其也可用来创建指定数据的张量

torch.Tensor 是一个类,可以用来创建未初始化的张量。它接受形状(shape)作为参数,返回一个未初始化的张量。

# 创建一个 2x3 的未初始化张量
x = torch.Tensor(2, 3)
print(x)

输出:

tensor([[1.4013e-45, 0.0000e+00, 1.4013e-45],
        [0.0000e+00, 1.4013e-45, 0.0000e+00]])

注意:torch.Tensor 也可以用来创建指定数据的张量,但不推荐这种方式,因为它的行为不如 torch.tensor 直观。

# 不推荐:从列表创建张量
data = [1, 2, 3, 4]
x = torch.Tensor(data)
print(x)

输出:

tensor([1., 2., 3., 4.])

2.3. 指定类型的张量创建

PyTorch 提供了多种数据类型(dtype),可以通过以下方式创建指定类型的张量:

2.3.1. torch.IntTensor:创建整数类型张量

# 创建一个 2x2 的整数类型张量
x = torch.IntTensor([[1, 2], [3, 4]])
print(x)
print(x.dtype)  # torch.int32

输出:

tensor([[1, 2],
        [3, 4]], dtype=torch.int32)
torch.int32

2.3.2. torch.FloatTensor:创建浮点类型张量

# 创建一个 2x2 的浮点类型张量
x = torch.FloatTensor([[1, 2], [3, 4]])
print(x)
print(x.dtype)  # torch.float32

输出:

ensor([[1., 2.],
        [3., 4.]])
torch.float32

2.3.3. torch.DoubleTensor:创建双精度浮点类型张量

# 创建一个 2x2 的双精度浮点类型张量
x = torch.DoubleTensor([[1, 2], [3, 4]])
print(x)
print(x.dtype)  # torch.float64

输出:

tensor([[1., 2.],
        [3., 4.]], dtype=torch.float64)
torch.float64

2.4. 指定数据类型的其他方式

除了使用 torch.IntTensor、torch.FloatTensor 等,还可以通过 dtype 参数直接指定数据类型。

# 创建一个 2x2 的浮点类型张量
x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
print(x)
print(x.dtype)  # torch.float32

输出:

tensor([[1., 2.],
        [3., 4.]])
torch.float32

2.5. 总结

方法用途
torch.tensor(data)根据数据创建张量,自动推断数据类型。
torch.Tensor(shape)根据形状创建未初始化的张量。
torch.IntTensor(data)创建整数类型(torch.int32)的张量。
torch.FloatTensor(data)创建浮点类型(torch.float32)的张量。
torch.DoubleTensor(data)创建双精度浮点类型(torch.float64)的张量。
torch.tensor(data, dtype=…)创建指定数据类型的张量(推荐,更直观且灵活)。

3. 创建线性和随机张量

3.1 创建线性张量

3.1.1. torch.arange:创建等间隔的整数张量

torch.arange 用于创建一个从起始值到结束值(不包括结束值)的等间隔整数张量。

import torch
# 创建一个从 0 到 9 的张量
x = torch.arange(10)
print(x)

输出:

tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

可以指定起始值、结束值和步长:

# 创建一个从 2 到 8,步长为 2 的张量
x = torch.arange(2, 10, 2)
print(x)

输出:

tensor([2, 4, 6, 8])

3.1.2. torch.linspace:创建等间隔的浮点数张量

torch.linspace 用于创建一个从起始值到结束值的等间隔浮点数张量,可以指定元素的数量。

# 创建一个从 0 到 1 的 5 个等间隔元素的张量
x = torch.linspace(0, 1, 5)
print(x)

输出:

tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])

3.2. 随机种子设置

为了保证随机实验的可重复性,可以设置随机种子。

3.2.1 torch.random.manual_seed:设置随机种子

# 设置随机种子
torch.random.manual_seed(42)
# 创建一个随机张量
x = torch.randn(2, 2)
print(x)

输出:

tensor([[ 0.3367,  0.1288],
        [ 0.2345,  0.2303]])

注:每次运行代码时,生成的随机张量都会相同。

3.3. 创建随机张量

3.3.1. torch.randn:创建标准正态分布的随机张量

torch.randn 用于创建服从标准正态分布(均值为 0,方差为 1)的随机张量。

# 创建一个 2x2 的标准正态分布随机张量
x = torch.randn(2, 2)
print(x)

输出:

tensor([[-0.4032,  0.8380],
        [-1.3886, -0.2935]])

3.3.2. torch.rand:创建均匀分布的随机张量

torch.rand 用于创建在 [0, 1) 区间内均匀分布的随机张量。

# 创建一个 2x2 的均匀分布随机张量
x = torch.rand(2, 2)
print(x)

输出:

tensor([[0.1234, 0.5678],
        [0.9101, 0.2345]])

3.3.3. torch.randint:创建整数随机张量

torch.randint 用于创建指定范围内的整数随机张量。

# 创建一个 2x2 的随机整数张量,范围在 [0, 10)
x = torch.randint(0, 10, (2, 2))
print(x)

输出:

tensor([[3, 7],
        [2, 5]])

3.4. 总结

方法用途
torch.arange(start, end, step)创建等间隔的整数张量。
torch.linspace(start, end, steps)创建等间隔的浮点数张量。
torch.random.manual_seed(seed)设置随机种子,确保实验可重复。
torch.randn(shape)创建标准正态分布的随机张量。
torch.rand(shape)创建 [0, 1) 区间内均匀分布的随机张量。
torch.randint(low, high, shape)创建指定范围内的整数随机张量。

4. 创建全 0\1 张量

4.1. 创建全1 张量

4.1.1. torch.ones:创建全 1 张量

torch.ones 用于创建指定形状的全 1 张量。

import torch

# 创建一个 2x3 的全 1 张量
x = torch.ones(2, 3)
print(x)

输出:

tensor([[1., 1., 1.],
        [1., 1., 1.]])

4.1.2. torch.ones_like:创建与输入张量形状相同的全 1 张量

torch.ones_like 用于创建一个与输入张量形状相同的全 1 张量。

# 创建一个与 x 形状相同的全 1 张量
y = torch.ones_like(x)
print(y)

输出:

tensor([[1., 1., 1.],
        [1., 1., 1.]])

4.2. 创建全 0 张量

4.2.1. torch.zeros:创建全 0 张量

torch.zeros 用于创建指定形状的全 0 张量。

# 创建一个 2x3 的全 0 张量
x = torch.zeros(2, 3)
print(x)

输出:

tensor([[0., 0., 0.],
        [0., 0., 0.]])

4.2.2. torch.zeros_like:创建与输入张量形状相同的全 0 张量

torch.zeros_like 用于创建一个与输入张量形状相同的全 0 张量。

# 创建一个与 x 形状相同的全 0 张量
y = torch.zeros_like(x)
print(y)

输出:

tensor([[0., 0., 0.],
        [0., 0., 0.]])

4.3. 创建全为指定值的张量

4.3.1. torch.full:创建全为指定值的张量

torch.full 用于创建指定形状且所有元素为指定值的张量。

# 创建一个 2x3 的全为 5 的张量
x = torch.full((2, 3), 5)
print(x)

输出:

tensor([[5, 5, 5],
        [5, 5, 5]])

4.3.2. torch.full_like:创建与输入张量形状相同的全为指定值的张量

torch.full_like 用于创建一个与输入张量形状相同且所有元素为指定值的张量。

# 创建一个与 x 形状相同的全为 10 的张量
y = torch.full_like(x, 10)
print(y)

输出:

tensor([[10, 10, 10],
        [10, 10, 10]])

4.4. 总结

方法用途
torch.ones(shape)创建指定形状的全 1 张量。
torch.ones_like(input)创建与输入张量形状相同的全 1 张量。
torch.zeros(shape)创建指定形状的全 0 张量。
torch.zeros_like(input)创建与输入张量形状相同的全 0 张量。
torch.full(shape, value)创建指定形状且所有元素为指定值的张量。
torch.full_like(input, value)创建与输入张量形状相同且所有元素为指定值的张量。

5. 张量元素类型转换

5.1. 使用 tensor.type() 方法

tensor.type() 方法可以将张量转换为指定的类型。

import torch

# 创建一个浮点类型的张量
x = torch.tensor([1.0, 2.0, 3.0])
print(x.dtype)  # 默认是 torch.float32

# 转换为双精度浮点类型 (torch.float64)
x_double = x.type(torch.DoubleTensor)
print(x_double)
print(x_double.dtype)

输出:

torch.float32
tensor([1., 2., 3.], dtype=torch.float64)
torch.float64

5.2. 使用 tensor.double() 方法

tensor.double() 是 tensor.type(torch.DoubleTensor)
的简写形式,用于将张量转换为双精度浮点类型(torch.float64)。

# 转换为双精度浮点类型
x_double = x.double()
print(x_double)
print(x_double.dtype)

输出:

tensor([1., 2., 3.], dtype=torch.float64)
torch.float64

5.3. 其他类型转换方法

PyTorch 提供了多种类型转换方法,类似于 tensor.double(),可以直接调用:

方法转换为的类型
tensor.float()torch.float32
tensor.double()torch.float64
tensor.half()torch.float16
tensor.int()torch.int32
tensor.long()torch.int64
tensor.short()torch.int16
tensor.byte()torch.uint8
tensor.bool()torch.bool
示例:
# 创建一个浮点类型的张量
x = torch.tensor([1.0, 2.0, 3.0])

# 转换为整型
x_int = x.int()
print(x_int)
print(x_int.dtype)

# 转换为布尔型
x_bool = x.bool()
print(x_bool)
print(x_bool.dtype)

输出:

tensor([1, 2, 3], dtype=torch.int32)
torch.int32
tensor([True, True, True])
torch.bool

5.4. 使用 tensor.to() 方法

tensor.to() 是一个更通用的方法,可以用于设备(CPU/GPU)和类型的转换。

5.4.1. 转换数据类型

# 转换为双精度浮点类型
x_double = x.to(torch.float64)
print(x_double)
print(x_double.dtype)

输出:

tensor([1., 2., 3.], dtype=torch.float64)
torch.float64

5.4.2. 同时转换设备和数据类型

# 转换为 GPU 上的双精度浮点类型
if torch.cuda.is_available():
    x_gpu = x.to(device='cuda', dtype=torch.float64)
    print(x_gpu)
    print(x_gpu.dtype)

5.5. 总结

方法用途
tensor.type(torch.DoubleTensor)将张量转换为指定类型(如 torch.float64)。
tensor.double()将张量转换为双精度浮点类型(torch.float64)。
tensor.float()将张量转换为单精度浮点类型(torch.float32)。
tensor.int()将张量转换为整型(torch.int32)。
tensor.to(dtype=…)通用方法,支持设备转换和类型转换。

http://www.kler.cn/a/588740.html

相关文章:

  • CSS 知识点总结1
  • 【软考-架构】7、系统配置与性能评价
  • CAD球体密堆积3D插件V2.0
  • SpringBoot手动注册定时任务
  • ActiveMQ监听器在MQ重启后不再监听问题
  • Pytorch:Dataset的加载
  • 百度贴吧IP和ID是什么意思?怎么查看
  • NPU、边缘计算与算力都是什么啊?
  • [leetcode] 面试经典 150 题——篇3:滑动窗口
  • 一分钟了解深度学习
  • Lisp语言的网络管理
  • 利用Java爬虫根据关键词获取商品列表:实战指南
  • 一份C#的笔试题及答案
  • 【NLP】 4. NLP项目流程与上下文窗口大小参数的影响
  • Kafka可视化工具KafkaTool工具的使用
  • Lua语言的嵌入式调试
  • qt 自带虚拟键盘的编译使用记录
  • 深入解析 React Diff 算法:原理、优化与实践
  • C或C++中实现数据结构课程中的链表、数组、树和图
  • matlab 模糊pid实现温度控制