张量视图(Tensor Views)

文章目录

  • 前言
    • 1.torch.as_strided()
    • 2.torch.detach()
    • 3.torch.diagonal()
    • 4.torch.expand()
    • 5.torch.movedim()
    • 6.torch.narrow()
    • 7.torch.permute()
    • 8.torch.select()
    • 9.torch.squeeze()
    • 10.torch.transpose()
    • 11.torch.t()
    • 12.torch.real和torch.imag
    • 13.torch.unflatten()
    • 14.torch.unsqueeze()
    • 15.torch.view()
    • 16.torch.unbind()
    • 17.torch.split()
    • 18.torch.chunk()


前言

张量视图(Tensor Views)是 PyTorch 中的一个重要概念。视图是指与原始张量共享相同底层数据的新张量,但具有不同的形状或步幅。

通过创建张量视图,我们可以在不复制数据的情况下对张量进行形状变换、切片和其他操作,从而实现快速且内存高效的操作。


1.torch.as_strided()

  使用 torch.as_strided 函数创建新的张量,这个新视图与原张量共享内存,但可以以不同的步幅访问这些数据。

import torch# 创建一个输入张量
input = torch.tensor([1, 2, 3, 4, 5, 6])
output = torch.as_strided(input, size=(3, 2), stride=(2, 1))# 打印输入张量和输出张量
print("Input tensor:")
print(input)print("Output tensor:")
print(output)
Input tensor:
tensor([1, 2, 3, 4, 5, 6])
Output tensor:
tensor([[1, 2],[3, 4],[5, 6]])

2.torch.detach()

 当使用 torch.detach() 函数时,它会创建一个新的张量,该张量与原始张量共享相同的数据,但不共享计算图的梯度。这使得新张量可以被用作不需要梯度的中间结果或者被用于与原始张量相互独立的计算。

import torch# 创建一个需要梯度的张量
x = torch.tensor([2.0, 3.0], requires_grad=True)# 进行一些操作,并分离计算图
y = x + 1
z = y * 2
z_detached = z.detach()# 查看张量的梯度信息
print(x.requires_grad)  # 输出: True
print(y.requires_grad)  # 输出: True
print(z.requires_grad)  # 输出: True
print(z_detached.requires_grad)  # 输出: False

3.torch.diagonal()

  用于提取张量的对角线元素。

torch.diagonal(input, offset=0, dim1=0, dim2=1)
"""
参数说明:input:输入张量。
offset:对角线的偏移量,表示从主对角线的偏移量,默认为0(主对角线)。
dim1:起始维度。
dim2:结束维度。
"""
import torch# 创建一个二维张量
x = torch.tensor([[1, 2, 3],[4, 5, 6],[7, 8, 9]])# 提取主对角线的元素
diagonal = torch.diagonal(x)print(diagonal)  # 输出: tensor([1, 5, 9])# 提取副对角线的元素
diagonal_offset = torch.diagonal(x, offset=1)print(diagonal_offset)  # 输出: tensor([2, 6])# 提取指定维度的对角线元素
diagonal_dim = torch.diagonal(x, dim1=1, dim2=0)print(diagonal_dim)  # 输出: tensor([1, 5, 9])

4.torch.expand()

  torch.expand() 是 PyTorch 中的一个函数,用于扩展张量的形状。

torch.expand(input, size)
"""
参数说明:input:输入张量。
size:扩展后的目标形状,可以是一个元组或列表。
"""
import torch# 创建一个一维张量
x = torch.tensor([1, 2, 3])# 扩展张量的形状
expanded = torch.expand(x, (2, 3))print(expanded)
# 输出:
# tensor([[1, 2, 3, 1, 2, 3, 1, 2, 3],
#         [1, 2, 3, 1, 2, 3, 1, 2, 3]])# 创建一个二维张量
y = torch.tensor([[1],[2]])# 扩展张量的形状
expanded_2 = torch.expand(y, (2, 3))print(expanded_2)
# 输出:
# tensor([[1, 1, 1],
#         [2, 2, 2],
#         [1, 1, 1],
#         [2, 2, 2]])

5.torch.movedim()

  torch.movedim() 是 PyTorch 中的一个函数,用于移动张量的维度顺序。

torch.movedim(input, source, destination)
"""
参数说明:input:输入张量。
source:原始维度或维度的序列。
destination:目标维度或维度的序列。
"""
import torch# 创建一个三维张量
x = torch.tensor([[[1, 2],[3, 4]],[[5, 6],[7, 8]]])# 移动张量的维度顺序
moved = torch.movedim(x, source=[0, 1, 2], destination=[2, 1, 0])print(moved.shape)  # 输出: torch.Size([2, 2, 2])
print(moved)
# tensor([[[1, 5],
#          [3, 7]],#         [[2, 6],
#          [4, 8]]])

6.torch.narrow()

  torch.narrow() 是 PyTorch 中的一个函数,用于沿指定维度缩小张量,通过选择一定范围的索引来实现。

torch.narrow(input, dim, start, length)
"""
参数说明:input:输入张量。
dim:要缩小的维度。
start:缩小范围的起始索引。
length:缩小范围的长度。
"""
import torch# 创建一个张量
x = torch.tensor([[1, 2, 3],[4, 5, 6],[7, 8, 9]])# 沿着维度0进行缩小
narrowed = torch.narrow(x, 0, 1, 2)print(narrowed)
# 输出:
# tensor([[4, 5, 6],
#         [7, 8, 9]])

7.torch.permute()

torch.permute() 是 PyTorch 中的一个函数,用于对张量进行维度重排。

torch.permute(*dims)
"""
参数说明:*dims:要重排的维度顺序,可以是一个整数序列或多个整数参数。
"""
import torch# 创建一个三维张量
x = torch.tensor([[[1, 2, 3],[4, 5, 6]],[[7, 8, 9],[10, 11, 12]]])# 对张量进行维度重排
permuted = torch.permute(x, [0, 2, 1])
#permuted = x.permute(0,2,1)
print(permuted.shape)  # 输出: torch.Size([2, 3, 2])
print(permuted)
# 输出:
# tensor([[[ 1,  4],
#          [ 2,  5],
#          [ 3,  6]],
# 
#         [[ 7, 10],
#          [ 8, 11],
#          [ 9, 12]]])

8.torch.select()

torch.select() 是 PyTorch 中的一个函数,用于按照指定的条件选择张量中的元素。

torch.select(input, dim, index)
"""
参数说明:input:输入张量。
dim:要选择的维度。
index:要选择的索引。
"""
import torch# 创建一个二维张量
x = torch.tensor([[1, 2, 3],[4, 5, 6],[7, 8, 9]])# 在维度0上选择索引为1的元素
selected = torch.select(x, 0, 1)print(selected)
# 输出:
# tensor([4, 5, 6])

9.torch.squeeze()

  torch.squeeze() 是 PyTorch 中的一个函数,用于去除张量中尺寸为 1 的维度。

torch.squeeze(input, dim=None)
"""
参数说明:input:输入张量。
dim(可选):指定要挤压的维度。如果指定了 dim,则只会挤压该维度上的尺寸为 1 的维度;如果未指定 dim,则会挤压所有尺寸为 1 的维度
"""
import torch# 创建一个具有尺寸为 1 的维度的张量
x = torch.tensor([[[1, 2, 3]]])# 去除尺寸为 1 的维度
squeezed = torch.squeeze(x)
x = x.squeeze()
print(x.shape)  # 输出: torch.Size([3])
print(x)
# 输出:
# tensor([1, 2, 3])

10.torch.transpose()

  torch.transpose() 是 PyTorch 中的一个函数,用于对张量进行转置操作,即交换维度的顺序。

torch.transpose() 和 torch.permute() 都是用于改变张量的维度顺序,但它们之间有一些区别。

  • 参数形式:torch.transpose() 函数接受两个参数 dim0 和 dim1,用于指定要交换的维度索引。而torch.permute() 函数接受一个可变数量的参数 *dims,用于指定新的维度顺序。
  • 功能范围:torch.transpose() 只能实现维度之间的交换,即将指定的两个维度进行交换。而 torch.permute()可以实现更灵活的维度重新排列,可以同时对多个维度进行重排,不仅仅是交换。
  • 维度顺序:torch.transpose() 只能交换两个维度的顺序,无法改变其他维度的顺序。而 torch.permute()可以在任意维度上进行重排,允许灵活地改变维度的顺序。
import torch# 创建一个三维张量
x = torch.tensor([[[1, 2, 3],[4, 5, 6]],[[7, 8, 9],[10, 11, 12]]])# 使用 torch.transpose() 进行维度交换
transposed = torch.transpose(x, 0, 2)# 使用 torch.permute() 进行维度重排
permuted = x.permute(2, 1, 0)print(transposed.shape)  # 输出: torch.Size([3, 2, 2])
print(transposed)
# 输出:
# tensor([[[ 1,  4],
#          [ 7, 10]],
#
#         [[ 2,  5],
#          [ 8, 11]],
#
#         [[ 3,  6],
#          [ 9, 12]]])print(permuted.shape)  # 输出: torch.Size([3, 2, 2])
print(permuted)
# 输出:
# tensor([[[ 1,  4],
#          [ 7, 10]],
#
#         [[ 2,  5],
#          [ 8, 11]],
#
#         [[ 3,  6],
#          [ 9, 12]]])

11.torch.t()

  该函数期望输入为 2 维或更低维的张量,并将维度 0 和维度 1 进行转置。0 维和 1 维张量将按原样返回。当输入为 2 维张量时,这等价于 transpose(input, 0, 1)。

import torch# 创建一个二维张量
x = torch.tensor([[1, 2, 3],[4, 5, 6]])# 对张量进行转置操作
transposed = torch.t(x)print(transposed.shape)  # 输出: torch.Size([3, 2])
print(transposed)
# 输出:
# tensor([[1, 4],
#         [2, 5],
#         [3, 6]])
import torch# 创建一个一维张量
x = torch.tensor([1, 2, 3, 4, 5])# 对张量进行转置操作
transposed = torch.t(x)print(transposed.shape)  # 输出: torch.Size([5])
print(transposed)
# 输出:
# tensor([1, 2, 3, 4, 5])

12.torch.real和torch.imag

  torch.real() 函数用于提取复数张量中的实部部分。

import torch# 创建一个复数张量
x = torch.tensor([1+2j, 3+4j, 5+6j])# 提取复数张量的实部
real_part = torch.real(x)print(real_part.shape)  # 输出: torch.Size([3])
print(real_part)
# 输出:
# tensor([1., 3., 5.])
import torch# 创建一个复数张量
x = torch.tensor([1+2j, 3+4j, 5+6j])# 分别提取复数张量的实部和虚部
real_part = x.real
imag_part = x.imagprint(real_part.shape)  # 输出: torch.Size([3])
print(real_part)
# 输出:
# tensor([1., 3., 5.], dtype=torch.float32)print(imag_part.shape)  # 输出: torch.Size([3])
print(imag_part)
# 输出:
# tensor([2., 4., 6.], dtype=torch.float32)

13.torch.unflatten()

  torch.unflatten() 函数用于将给定的维度展平的张量恢复成原始的形状。

torch.unflatten(dim, input_sizes)
"""
参数说明:
dim:指定要展平的维度。
input_sizes:一个元组或列表,指定原始张量在指定维度上的各个子张量的大小。
"""
import torch# 创建一个展平的张量
x = torch.tensor([1, 2, 3, 4, 5, 6])# 恢复成原始形状
unflattened = torch.unflatten(x,0, (2, 3))print(unflattened.shape)  # 输出: torch.Size([2, 3])
print(unflattened)
# 输出:
# tensor([[1, 2, 3],
#         [4, 5, 6]])

14.torch.unsqueeze()

  torch.unsqueeze() 函数用于在指定的维度上增加一个维度,从而扩展张量的形状。

torch.unsqueeze(input, dim)
"""
参数说明:
input:输入张量。
dim:指定要扩展的维度索引。
"""
import torch# 创建一个二维张量
x = torch.tensor([[1, 2, 3],[4, 5, 6]])# 在维度 1 上增加一个维度
expanded = torch.unsqueeze(x, dim=1)print(expanded.shape)  # 输出: torch.Size([2, 1, 3])
print(expanded)
# 输出:
# tensor([[[1, 2, 3]],
#         [[4, 5, 6]]])

15.torch.view()

  torch.view() 是 PyTorch 中用于调整张量形状的函数,它允许你重新定义张量的维度和大小,而不改变原始数据。

torch.view(*shape)
"""
参数说明:
shape:一个整数元组或多个整数参数,用于指定新张量的形状。
"""
import torch# 创建一个张量
x = torch.tensor([[1, 2, 3],[4, 5, 6]])# 改变张量的形状
reshaped = x.view(3, 2)print(reshaped.shape)  # 输出: torch.Size([3, 2])
print(reshaped)
# 输出:
# tensor([[1, 2],
#         [3, 4],
#         [5, 6]])

16.torch.unbind()

  torch.unbind() 函数用于按维度将张量拆分为多个张量序列。

torch.unbind(input, dim=0)
"""
参数说明:
input:输入张量。
dim:指定的维度,沿该维度进行拆分。默认值为 0。
"""
import torch# 创建一个张量
x = torch.tensor([[1, 2, 3],[4, 5, 6]])# 按维度 1 拆分张量
unpacked = torch.unbind(x, dim=1)print(len(unpacked))  # 输出: 3
print(unpacked[0])  # 输出: tensor([1, 4])
print(unpacked[1])  # 输出: tensor([2, 5])
print(unpacked[2])  # 输出: tensor([3, 6])
import torch# 创建一个张量
x = torch.tensor([[1, 2, 3],[4, 5, 6]])# 按维度 0 拆分张量
unpacked = torch.unbind(x, dim=0)print(len(unpacked))  # 输出: 2
print(unpacked[0])  # 输出: tensor([1, 2, 3])
print(unpacked[1])  # 输出: tensor([4, 5, 6])

17.torch.split()

  torch.split() 函数用于按指定维度将张量分割为多个子张量。

torch.split(tensor, split_size_or_sections, dim=0)
"""
tensor:输入张量。
split_size_or_sections:指定分割的大小(整数)或分割的位置(整数列表)。
dim:指定的维度,沿该维度进行分割。默认值为 0。
"""
import torch# 创建一个张量
x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8])# 按维度 0 使用整数列表分割张量
splits = torch.split(x, split_size_or_sections=[2, 3, 1, 2], dim=0)print(len(splits))  # 输出: 4
print(splits[0])  # 输出: tensor([1, 2])
print(splits[1])  # 输出: tensor([3, 4, 5])
print(splits[2])  # 输出: tensor([6])
print(splits[3])  # 输出: tensor([7, 8])
import torch# 创建一个张量
x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8])# 按维度 0 分割张量
splits = torch.split(x, split_size_or_sections=3, dim=0)print(len(splits))  # 输出: 3
print(splits[0])  # 输出: tensor([1, 2, 3])
print(splits[1])  # 输出: tensor([4, 5, 6])
print(splits[2])  # 输出: tensor([7, 8])

18.torch.chunk()

  torch.chunk() 函数用于按指定维度将张量分割为多个块(chunks)。

torch.chunk(tensor, chunks, dim=0)
"""
参数说明:
tensor:输入张量。
chunks:要分割的块数。
dim:指定的维度,沿该维度进行分割。默认值为 0。
"""
import torch# 创建一个张量
x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8])# 按维度 0 分割张量为两个块
chunks = torch.chunk(x, chunks=2, dim=0)print(len(chunks))  # 输出: 2
print(chunks[0])  # 输出: tensor([1, 2, 3, 4])
print(chunks[1])  # 输出: tensor([5, 6, 7, 8])
import torch# 创建一个二维张量
x = torch.tensor([[1, 2, 3],[4, 5, 6]])# 按维度 1 分割张量为三个块
chunks = torch.chunk(x, chunks=3, dim=1)print(len(chunks))  # 输出: 3
print(chunks[0])  # 输出: tensor([[1],#         [4]])
print(chunks[1])  # 输出: tensor([[2],#         [5]])
print(chunks[2])  # 输出: tensor([[3],#         [6]])

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/842272.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Redis教程(二十):Redis中Lua脚本的使用

Lua脚本 Lua 脚本主要在于提供一种强大且灵活的方式来扩展和定制应用程序的功能。在不同的场景和平台上,Lua 脚本的作用各不相同,以下是一些主要的用途: 嵌入式脚本 Lua 最初设计的目的就是作为一个嵌入到应用程序中的脚本语言。这使得应用开发者可以提供一种途径,让最…

Flutter 中的 LinearProgressIndicator 小部件:全面指南

Flutter 中的 LinearProgressIndicator 小部件:全面指南 在用户界面设计中,进度指示器是提供用户等待反馈的重要元素。Flutter 提供了多种进度指示器组件,其中 LinearProgressIndicator 用于展示水平的进度条。本文将详细介绍 LinearProgres…

【React】二次封装Antd的Table组件

使用Table并不难,但是每次使用都会伴随着很大一部分逻辑,如loding效果、表格分页筛选排序、调接口完毕后赋值等等,使用方法基本一致,所以可以将他们二次封装,从而减少代码量,提升代码可读性。 二次封装表格…

5.29高通技术分享抢先看 | 2024高通边缘智能创新应用大赛公开课

火力全开!2024高通边缘智能创新应用大赛首期公开课将在5月29日晚上8点炫酷启动! 届时,来自大赛主办方高通技术公司的产品市场总监李骏捷和高级资深工程师李万俊将于云端聚首,带来一场关于边缘智能的前沿技术对话。 各位参赛者及…

预防侵权知识丨什么是图形商标?怎么用产品图片进行图形商标查询检索?

图形商标查询检索是跨境电商预防侵权中重要的一环,但是有很多卖家对图形商标不太了解,也不知道怎么进行图形商标的查询检索。所以,我们一起来看下。 一、什么是图形商标 图形商标是商标的一种,指的是由几何图形或其它事物图案构…

网络流量监控指标有哪些?

目录 什么是网络流量监控? 关键网络流量监控指标 带宽利用率 网络延迟(Latency) 抖动(Jitter) 丢包率(Packet Loss Rate) 吞吐量(Throughput) 会话数量&#xff0…

深入理解C++智能指针系列(三)

引言 在现代软件开发中,内存管理是一个核心主题,特别是在使用C这类需要手动管理内存的语言时。智能指针作为一种高效的工具,能够简化内存管理的复杂性。本文将讨论如何利用 std::unique_ptr 来封装复杂的内存管理任务,特别是在涉…

30秒学会一个ChatGpt-4o小技巧 --- 照片漫画化

文章目录 选择照片修改图片 选择照片 先选择自己的一张照片 当然首先你得能够访问ChatGpt-4o, 图片生成能力只有ChatGpt-4才有 所以我们先登录到 国内能够使用的ChatGpt网站: 我要超级GPT 然后把图片上传,再写提示词:请帮我把这种照片按照日系动漫风…

vue根据登录存储的性别来改变背景图

根据登录成功之后&#xff0c;并把信息存入到本地&#xff0c;在个人页面中&#xff0c;并取出来&#xff0c;并渲染它&#xff0c;这是一个根据存储的性别来渲染个人页面的背景图&#xff0c;男女性别不同&#xff0c;背景图也不一样。 template: <div class"top"…

IT 行业的现状剖析与未来展望:商业与技术的交织

今日&#xff0c;我无意间看到 CSDN 的创作话题&#xff1a;“我眼中的 IT 行业现状与未来趋势”&#xff0c;这引发了我对 IT 行业的深入思考。以下是我的一些个人见解&#xff0c;希望能得到大家的指正和交流&#xff0c;共同进步。 IT 行业的现状与未来趋势&#xff0c;这个…

云服务器有啥用?如何拥有一台自己的云服务器?

你们平时都把珍贵的学习资料藏在哪里&#xff1f; 你们是否也遇到过学习资料丢失&#xff0c;或者放在网盘被人发现的问题&#xff1f; 云服务器作为一种灵活、高效、可扩展的计算资源&#xff0c;为用户提供了强大的计算能力和存储空间。所以我们可以尝试通过云服务器来搭建…

【Gtest使用说明】

主要测试的代码 #include <gtest/gtest.h> int add(int a, int b) {return a b; } TEST(MathTest, Add) {EXPECT_EQ(3, add(1, 2));EXPECT_EQ(9, add(2, 3));} int main(int argc, char **argv) {::testing::InitGoogleTest(&argc, argv);return RUN_ALL_TESTS(); …

821. 字符的最短距离 - 力扣

1. 题目 给你一个字符串 s 和一个字符 c &#xff0c;且 c 是 s 中出现过的字符。 返回一个整数数组 answer &#xff0c;其中 answer.length s.length 且 answer[i] 是 s 中从下标 i 到离它 最近 的字符 c 的 距离 。 两个下标 i 和 j 之间的 距离 为 abs(i - j) &#xff0c…

代码随想录算法训练营day36 | 1005.K次取反后最大化的数组和、134. 加油站、135. 分发糖果

1005.K次取反后最大化的数组和 分几步做&#xff0c;思路清晰 按绝对值从大到小的顺序进行排序从前向后遍历&#xff0c;遇到负数将其变为正数&#xff0c;同时K--如果K还大于0&#xff0c;那么反复转变数值最小的元素&#xff0c;将K用完求和 class Solution:def largestSu…

el-transfer和el-tree进行结合搞一个树形穿梭框

由于业务需求需要在穿梭框里使用树形结构&#xff0c;但是本身element里并不支持&#xff0c;于是参考了别的大佬发的文章作为思路及后续自己新增了一些处理功能。 目录 1.拷贝代码放到自己的项目目录中 2.改造el-transfer的源码 3.修改tree-transfer-panel.vue文件 4.修改…

数据挖掘实战-基于余弦相似度的印度美食推荐系统

&#x1f935;‍♂️ 个人主页&#xff1a;艾派森的个人主页 ✍&#x1f3fb;作者简介&#xff1a;Python学习者 &#x1f40b; 希望大家多多支持&#xff0c;我们一起进步&#xff01;&#x1f604; 如果文章对你有帮助的话&#xff0c; 欢迎评论 &#x1f4ac;点赞&#x1f4…

【模版方法设计模式】

文章目录 模板方法设计模式模板方法的设计原则模板方法设计模式组成部分代码实现抽象类实现具体实现类执行 模板方法设计模式 模版方法设计模式&#xff08;Template Method Pattern&#xff09;是一种行为设计模式&#xff0c;它定义了一个操作中的算法骨架&#xff0c;而将一…

最最最重要的集群参数配置(上)no.7

我希望通过两期内容把这些重要的配置讲清楚。严格来说这些配置并不单单指Kafka服务器端的配置&#xff0c;其中既有Broker端参数&#xff0c;也有主题&#xff08;后面我用我们更熟悉的Topic表示&#xff09;级别的参数、JVM端参数和操作系统级别的参数。 需要你注意的是&…

MATLAB导入导出Excel的方法|读与写Excel的命令|附例程的github下载链接

前言 前段时间遇到一个需求&#xff1a;导出变量到Excel里面&#xff0c;这里给出一些命令&#xff0c;同时给一个示例供大家参考。 MATLAB读/写Excel的命令 在MATLAB中&#xff0c;可以使用以下命令来读写Excel文件&#xff1a; 读取Excel文件&#xff1a; xlsread(filen…

Java EE-Spring AOP 面向切面编程

Spring AOP https://www.cnblogs.com/joy99/p/10941543.html 超级详细版&#xff1a;Chapter 6. 使用Spring进行面向切面编程&#xff08;AOP&#xff09; AOP 原理 面向切面 ( Aspect Orient Programming ) 面向切面编程&#xff0c;是面向对象编程(OOP) 的一种补充。 在…