pytorch深度学习笔记18

目录

摘要

1.张量创建

基本张量创建

指定区间的张量创建

按数值填充张量

随机张量创建

2.张量元素类型转换

Tensor与ndarray转换

Tensor与标量转换

3.张量数值计算

基本运算

哈达玛积(元素级乘法)

矩阵乘法运算


摘要

本篇文章继续学习尚硅谷深度学习教程,学习内容是张量创建相关基本函数,类型转换相关基本函数以及张量数值计算基本函数。

1.张量创建

Tensor(张量)是PyTorch的核心数据结构。张量在不同学科中有不同的意义,在深度学习中张量表示一个多维数组,是标量、向量、矩阵的拓展。如一个RGB图像的数组就是一个三维张量,第1维是图像的高,第2维是图像的宽,第3维是图像的颜色通道。

基本张量创建

torch.tensor(data)创建指定内容的张量

python 复制代码
import torch
import numpy as np

# 创建标量张量
tensor1 = torch.tensor(10)
print(tensor1)

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

# 使用numpy创建张量
tensor3 = torch.tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
print(tensor3)

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)

创建指定类型的张量

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

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

python 复制代码
import torch

# 创建int32类型的张量
tensor1 = torch.IntTensor(2, 3)
tensor2 = torch.tensor([1, 2, 3], 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)

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

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

# 创建float32类型的张量
tensor1 = torch.FloatTensor([9, 8, 7])
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)
指定区间的张量创建

torch.arange(start, end, step)在区间内按步长创建张量

python 复制代码
import torch

# torch.arange(start, end, step) 在区间[start,end)中创建步长为step的张量
tensor1 = torch.arange(10, 30, 2)
print(tensor1)

# torch.arange(end) 创建区间为[0,end),步长为1的张量
tensor2 = torch.arange(6)
print(tensor2)

torch.linspace(start, end, steps)在区间内按元素数量创建张量

python 复制代码
import torch

# torch.linspace(start, end, steps) 在区间按元素数量创建张量
tensor1 = torch.linspace(10, 30, 5)
print(tensor1)

torch.logspace(start, end, steps, base)在指数区间内按指定底数创建张量

python 复制代码
import torch

# torch.logspace(start, end, steps, base) 在区间[start,end]之间生成steps个数,并以base为底,区间内的数为指数创建张量
tensor1 = torch.logspace(1, 3, 3, 2)
print(tensor1)
按数值填充张量
  • torch.zeros(size)创建指定形状的全0张量
  • torch.ones(size)创建指定形状的全1张量
  • torch.full(size, value)创建指定形状的按指定值填充的张量
  • torch.empty(size)创建指定形状的未初始化的张量
  • torch.zeros_like(input)创建与给定张量形状相同的全0张量
  • torch.ones_like(input)创建与给定张量形状相同的全1张量
  • torch.full_like(input, value)创建与给定张量形状相同的按指定值填充的张量
  • torch.empty_like(input)创建与给定张量形状相同的未初始化的张量
  • torch.eye(n, [m])创建单位矩阵
python 复制代码
import torch

# torch.zeros(size) 创建指定形状的全0张量
tensor1 = torch.zeros(2, 3)
print(tensor1)

# torch.ones_like(input) 创建与给定张量形状相同的全1张量
tensor2 = torch.ones_like(tensor1)
print(tensor2)

# torch.full(size,fill_value) 创建指定形状的按指定值填充的张量
tensor1 = torch.full((2, 3), 6)
print(tensor1)

# torch.empty_like(input) 创建与给定张量形状相同的未初始化的张量
tensor2 = torch.empty_like(tensor3)
print(tensor2)

# torch.eye(n) 创建n*n的单位矩阵
tensor1 = torch.eye(3)
print(tensor1)

# torch.eye(n, m) 按指定的行和列创建
tensor2 = torch.eye(3, 4)
print(tensor2)
随机张量创建
  • torch.rand(size)创建在[0,1)上均匀分布的,指定形状的张量
  • torch.randint(low, high, size)创建在[low,high)上均匀分布的,指定形状的张量
  • torch.randn(size)创建标准正态分布的,指定形状的张量
  • torch.normal(mean,std,size)创建自定义正态分布的,指定形状的张量
  • torch.rand_like(input)创建在[0,1)上均匀分布的,与给定张量形状相同的张量
  • torch.randint_like(input, low, high)创建在[low,high)上均匀分布的,与给定张量形状相同的张量
  • torch.randn_like(input)创建标准正态分布的,与给定张量形状相同的张量
  • torch.randperm(n)生成从0到n-1的随机排列,类似洗牌
  • torch.random.initial_seed()查看随机数种子
  • torch.manual_seed(seed)设置随机数种子
python 复制代码
import torch

# torch.rand(size) 创建在[0,1)上均匀分布的,指定形状的张量
tensor1 = torch.rand(2, 3)
print(tensor1)

# torch.rand_like(input) 创建在[0,1)上均匀分布的,与给定张量形状相同的张量
tensor2 = torch.randint_like(tensor1, 1, 10)
print(tensor2)

# torch.randn(size) 创建标准正态分布的,指定形状的张量
tensor1 = torch.randn(4, 2)
print(tensor1)

# torch.normal(mean,std,size) 创建自定义正态分布的,指定形状的张量。mean为均值,std为标准差
tensor2 = torch.normal(5, 1, tensor1.shape)
print(tensor2)

# torch.randperm(n) 生成从0到n-1的随机排列
tensor1 = torch.randperm(10)
print(tensor1)

# 查看随机数种子
print(torch.random.initial_seed())
# 设置随机数种子
torch.manual_seed(42)
print(torch.random.initial_seed())

2.张量元素类型转换

Tensor.type(dtype)修改张量的类型

python 复制代码
import torch

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

# 使用type方法修改张量的类型
tensor1 = tensor1.type(torch.float32)
print(tensor1, tensor1.dtype)

Tensor.double()等修改张量的类型

python 复制代码
import torch

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

# 使用double方法修改张量的类型
tensor1 = tensor1.double()
print(tensor1)
# 使用long方法修改张量的类型
tensor1 = tensor1.long()
print(tensor1, tensor1.dtype)
Tensor与ndarray转换

Tensor.numpy()将Tensor转换为ndarray,共享内存。使用copy()避免共享内存

python 复制代码
import torch

# 使用numpy()方法将Tensor转换为ndarray,共享内存
tensor1 = torch.rand(3, 2)
numpy_array = tensor1.numpy()
print(tensor1)
print(numpy_array)
print(type(tensor1), type(numpy_array))
print()
tensor1[:, 0] = 4
print(tensor1)
print(numpy_array)
print()

# 使用copy()方法避免共享内存
numpy_array = tensor1.numpy().copy()
tensor1[:, 0] = -1
print(tensor1)
print(numpy_array)

torch.from_numpy(ndarray)将ndarray转换为Tensor,共享内存。使用copy()避免共享内存

python 复制代码
import torch
import numpy as np

# 使用from_numpy()方法将ndarray转换为Tensor,共享内存
numpy_array = np.random.randn(3)
tensor1 = torch.from_numpy(numpy_array)
print(numpy_array)
print(tensor1)
print()
numpy_array[0] = 100
print(numpy_array)
print(tensor1)
print()

# 使用copy()方法避免共享内存
tensor1 = torch.from_numpy(numpy_array.copy())
numpy_array[0] = -1
print(numpy_array)
print(tensor1)

torch.tensor(ndarray)将ndarray转换为Tensor,不共享内存

python 复制代码
import torch
import numpy as np

# 使用torch.tensor()将ndarray转换为Tensor
numpy_array = np.random.randn(3)
tensor1 = torch.tensor(numpy_array)
print(numpy_array)
print(tensor1)
print()
numpy_array[0] = 100
print(numpy_array)
print(tensor1)
Tensor与标量转换

若张量中只有1个元素,Tensor.item()可提取张量中元素为标量

python 复制代码
import torch

tensor1 = torch.tensor(1)
print(tensor1)
print(tensor1.item())

3.张量数值计算

基本运算

​​​​​​​四则运算

  • +、-、*、/加减乘除
  • add()、sub()、mul()、div()加减乘除,不改变原数据
  • add_()、sub_()、mul_()、div_()加减乘除、修改原数据
python 复制代码
import torch

tensor1 = torch.randint(1, 9, (2, 3))
print(tensor1)
print(tensor1 + 10)
print()

# add(),不修改原数据
print(tensor1.add(10))
print(tensor1)
print()

# add_(),修改原数据
print(tensor1.add_(10))
print(tensor1)

​​​​​​​-、neg()、neg_()取负

python 复制代码
import torch

tensor1 = torch.tensor([1, 2, 3])
print(-tensor1)
print()

print(tensor1.neg())
print(tensor1)
print()

print(tensor1.neg_())
print(tensor1)

**、pow()、pow_()求幂

python 复制代码
import torch

tensor1 = torch.tensor([1, 2, 3])
print(tensor1**2)
print()

print(tensor1.pow(2))
print(tensor1)
print()

print(tensor1.pow_(2))
print(tensor1)

sqrt()、sqrt_()求平方根

python 复制代码
import torch

tensor1 = torch.tensor([1.0, 2.0, 3.0])
print(tensor1.sqrt())
print(tensor1)
print()

print(tensor1.sqrt_())
print(tensor1)

​​​​​​​exp()、exp_()以e为底数求幂

python 复制代码
import torch

tensor1 = torch.tensor([1.0, 2.0, 3.0])
print(2.71828183**tensor1)
print()

print(tensor1.exp())
print(tensor1)
print()

print(tensor1.exp_())
print(tensor1)

log()、log_()以e为底求对数

python 复制代码
import torch

tensor1 = torch.tensor([1.0, 2.0, 3.0])
print(tensor1.log())
print(tensor1)
print()

print(tensor1.log_())
print(tensor1)
​​​​​​​哈达玛积(元素级乘法)

两个矩阵对应位置元素相乘称为哈达玛积(Hadamard product)。

使用*、mul()实现两个形状相同的张量之间对位相乘。

python 复制代码
import torch

tensor1 = torch.tensor([[1, 2], [3, 4]])
tensor2 = torch.tensor([[1, 2], [3, 4]])
print(tensor1 * tensor2)
print(tensor1.mul(tensor2))
矩阵乘法运算

mm()严格用于二维矩阵相乘。

@、matmul()支持多维张量,按最后两个维度做矩阵乘法,其他维度相同,或者至少一个张量对应维度为1,广播后进行运算

python 复制代码
import torch

# 2维矩阵的矩阵乘法
tensor1 = torch.tensor([[1, 2, 3], [4, 5, 6]])
tensor2 = torch.tensor([[1, 2], [3, 4], [5, 6]])
print(tensor1)
print(tensor2)
print(tensor1.mm(tensor2))
print(tensor1 @ tensor2)
print(tensor1.matmul(tensor2))
print()

# 3维张量的矩阵乘法
tensor1 = torch.tensor([[[1, 2, 3], [4, 5, 6]], [[6, 5, 4], [3, 2, 1]]])
tensor2 = torch.tensor([[[1, 2], [3, 4], [5, 6]], [[6, 5], [4, 3], [2, 1]]])
print(tensor1)
print(tensor2)
print(tensor1 @ tensor2)
print(tensor1.matmul(tensor2))
相关推荐
hetao17338372 小时前
2026-01-22~23 hetao1733837 的刷题笔记
c++·笔记·算法
lixin5565562 小时前
基于神经网络的音乐生成增强器
java·人工智能·pytorch·python·深度学习·语言模型
curry____3032 小时前
数据结构学习笔记
数据结构·笔记·学习
爱吃肉的鹏2 小时前
树莓派上部署YOLOv5:从零实现实时目标检测
深度学习·yolo·树莓派
哥布林学者2 小时前
吴恩达深度学习课程五:自然语言处理 第二周:词嵌入(六)情绪分类和词嵌入除偏
深度学习·ai
向前V2 小时前
Flutter for OpenHarmony轻量级开源记事本App实战:笔记编辑器
开发语言·笔记·python·flutter·游戏·开源·编辑器
snow_star_dream3 小时前
(笔记)VSC python应用--函数补全注释添加
笔记·python
songyuc3 小时前
【SAR】旋转框定义法学习笔记
笔记·学习
Wu_Dylan3 小时前
液态神经网络系列(四) | 一条 PyTorch 从零搭建 LTC 细胞
pytorch·神经网络