卷积和add、sub、mean等的转换

news2024/9/20 7:09:01

文章目录

  • 一、1*1卷积
  • 二、1*1卷积代替sum
    • 1.torch.sum用法
    • 2. 1*1卷积代替sum
  • 三、1*1卷积代替mean
    • 1.torch.mean用法
    • 2. 卷积代替mean
  • 三、卷积代替add


一、1*1卷积

1*1卷积的主要作用有以下几点:

  • 降维( dimension reductionality )。比如,一张500 * 500且厚度depth为100的图片在20个filter上做11的卷积,那么结果的大小为500500*20。
  • 加入非线性。卷积层之后经过激励层,1*1的卷积在前一层的学习表示上添加了非线性激励提升网络的表达能力;

二、1*1卷积代替sum

  • 限定条件1:sum在通道做累加
  • 限定条件2:卷积核大小是1*1,权重是全1矩阵。

1.torch.sum用法

torch.sum() 函数用于计算张量中元素的总和。

torch.sum(input, dim=None, keepdim=False, dtype=None)
"""
input:输入张量,包含要进行求和操作的元素。
dim:指定在哪个维度上进行求和操作。如果不指定,则对整个张量的所有元素进行求和。
keepdim:默认为 False,如果设置为 True,则保持输出张量中的求和维度。
dtype:指定输出张量的数据类型。
"""
import torch

# 创建一个示例张量
x = torch.tensor([
    [[1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 10, 11, 12]],
    
    [[13, 14, 15, 16],
     [17, 18, 19, 20],
     [21, 22, 23, 24]]
])

# 沿着不同维度进行求和操作
sum_dim0 = torch.sum(x, dim=0)
sum_dim1 = torch.sum(x, dim=1)
sum_dim2 = torch.sum(x, dim=2)

print("Original tensor:")
print(x)

print("\nSum along dimension 0:")
print(sum_dim0)

print("\nSum along dimension 1:")
print(sum_dim1)

print("\nSum along dimension 2:")
print(sum_dim2)
Original tensor:
shape: torch.Size([2, 3, 4])
tensor([[[ 1,  2,  3,  4],
         [ 5,  6,  7,  8],
         [ 9, 10, 11, 12]],

        [[13, 14, 15, 16],
         [17, 18, 19, 20],
         [21, 22, 23, 24]]])

Sum along dimension 0:
shape: torch.Size([3, 4])
tensor([[14, 16, 18, 20],
        [22, 24, 26, 28],
        [30, 32, 34, 36]])

Sum along dimension 1:
shape: torch.Size([2, 4])
tensor([[15, 18, 21, 24],
        [51, 54, 57, 60]])

Sum along dimension 2:
shape: torch.Size([2, 3])
tensor([[10, 26, 42],
        [58, 74, 90]])

2. 1*1卷积代替sum

import torch
import torch.nn.functional as F
# 定义输入张量
input_tensor = torch.randn(1, 376,1, 376)
# 定义权重张量
weight = torch.ones(1, 376, 1, 1, dtype=torch.float32)
conv_result = F.conv2d(input_tensor, weight, stride=1, padding=0, groups=1)
conv_result = conv_result.squeeze(-1)
print("Original input tensor shape:", input_tensor.shape)
print("Convolution result shape:", conv_result.shape)
print("Convolution result:", conv_result)
# 对比使用 torch.sum 进行验证
sum_result = torch.sum(input_tensor, dim=1, keepdim=True)
print("Sum result:", sum_result)

三、1*1卷积代替mean

  • 限定条件1:计算整个张量的平均值,不指定维度参数
  • 限定条件2:权重矩阵全1

1.torch.mean用法

import torch

# 创建一个示例张量
x = torch.tensor([[1.0, 2.0], [3.0, 4.0]])

# 计算整个张量的平均值
mean_all = torch.mean(x)

# 沿着指定的维度计算平均值
mean_dim0 = torch.mean(x, dim=0)
mean_dim1 = torch.mean(x, dim=1)

# 打印张量及其形状
print("Tensor x:")
print(x)
print("Shape of tensor x:", x.shape)

print("\nMean of all elements in x:")
print(mean_all)

print("\nMean along dimension 0:")
print(mean_dim0)
print("Shape of mean along dim 0:", mean_dim0.shape)

print("\nMean along dimension 1:")
print(mean_dim1)
print("Shape of mean along dim 1:", mean_dim1.shape)
Tensor x:
tensor([[1., 2.],
        [3., 4.]])
Shape of tensor x: torch.Size([2, 2])

Mean of all elements in x:
tensor(2.5000)

Mean along dimension 0:
tensor([2., 3.])
Shape of mean along dim 0: torch.Size([2])

Mean along dimension 1:
tensor([1.5000, 3.5000])
Shape of mean along dim 1: torch.Size([2])

2. 卷积代替mean

import torch
import torch.nn.functional as F
import numpy as np
# 定义输入张量
input_tensor = torch.randn(1, 1, 6, 20)
# 将输入张量重塑为 (N, H, 6, 20)
# 定义权重张量
weight = torch.ones(1, 1, 6, 20, dtype=torch.float32) / 120
# 使用卷积操作模拟平均
# 卷积核尺寸为 (1, 1, 6, 20),步长为 1
conv_result = F.conv2d(input_tensor, weight, stride=1, padding=0, groups=1)
# 将卷积结果重塑为 (N, H, 1)
conv_result = conv_result.squeeze(-1)
print("Original input tensor shape:", input_tensor.shape)
print("Reshaped input tensor shape:", input_tensor.shape)
print("Convolution result shape:", conv_result.shape)
print("Convolution result:", conv_result)
# 对比使用 torch.mean 进行验证
mean_result = torch.mean(input_tensor)
print("Mean result:", mean_result)
Original input tensor shape: torch.Size([1, 1, 6, 20])
Reshaped input tensor shape: torch.Size([1, 1, 6, 20])
Convolution result shape: torch.Size([1, 1, 1])
Convolution result: tensor([[[-0.0269]]])
Mean result: tensor(-0.0269)

三、卷积代替add

单位矩阵(Identity Matrix)在卷积中可以用作一种特殊的卷积核,其效果类似于对输入进行无操作(相当于恒等变换)。

import torch
import torch.nn.functional as F
import numpy as np

# 定义输入张量
lsh = torch.randn(1, 120, 376, 376)
rsh = torch.randn(1, 1, 376, 376)
add_result = torch.add(lsh, rsh)
print("Original add result:", add_result)

# 定义广播和卷积函数
def process_add(lsh, rsh):
    lsh_shape = lsh.shape
    rsh_shape = rsh.shape
    
    if rsh_shape[1] == 1 and lsh_shape[1] != 1:
        weight = np.ones(lsh_shape[1], 'float32').reshape(lsh_shape[1], 1, 1, 1)
        weight = torch.tensor(weight)
        rsh = F.conv2d(rsh, weight, stride=1, padding=0, groups=1)
    

    conv_input = torch.cat([lsh, rsh], dim=1)

    
    weight_param = np.eye(120, dtype='float32').reshape(120, 120, 1, 1)
    import pdb; pdb.set_trace()
    weight_param = np.concatenate([weight_param, weight_param], axis=1)

    weight_param = torch.tensor(weight_param)
    
    new_conv = F.conv2d(conv_input, weight_param, stride=1, padding=0, dilation=[1, 1])
    new_conv = new_conv.view(1, 120, 376, 376)
    
    return new_conv

# 处理加法操作
result = process_add(lsh, rsh)
# 打印结果
print("Original lsh shape:", lsh.shape)
print("Original rsh shape:", rsh.shape)
print("Processed result shape:", result.shape)
print("Processed result:", result)

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

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

相关文章

独立站冷启动SOP之市场和竞品调研1.0丨出海笔记

大家好,我是出海笔记Club的创始人Alan,过去半年我们做了15期的操盘手面对面,主要围绕的是跨境电商独立站的冷启动,基本上大部分方法和路径我们都覆盖到了。 我把目的,调研内容和可以使用的工具都罗列出来,…

Golang | Leetcode Golang题解之第417题太平洋大西洋水流问题

题目: 题解: type pair struct{ x, y int } var dirs []pair{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}func pacificAtlantic(heights [][]int) (ans [][]int) {m, n : len(heights), len(heights[0])pacific : make([][]bool, m)atlantic : make([][]bool, …

如何使用 maxwell 同步到 redis?

文章目录 1、MaxwellListener2、MxwObject1. 使用Maxwell捕获MySQL变更2. 将Maxwell的输出连接到消息系统3. 从消息系统读取数据并同步到Redis注意事项 1、MaxwellListener package com.atguigu.tingshu.album.listener;import com.alibaba.fastjson.JSON; import org.apache.…

【RabbitMQ】重试机制、TTL

重试机制 在消息从Broker到消费者的传递过程中,可能会遇到各种问题,如网络故障、服务不可用、资源不足等,这些问题都可能导致消息处理失败。为了解决这些问题,RabbitMQ提供了重试机制,允许消息在处理失败之后重新发送…

汇编语言的基本指令及基本使用操作

一、立即数 立即数判断规则: 如果某个数的数值范围是0~255之间,那么这个数一定是立即数; 把某个数展开成2进制,这个数的最高位1至最低位1之间的二进制数序列的位数不能超过8位; 这个数的二进制序列的右边必须为偶数个…

Java-Day02学习

Java-Day02 一维数组 1.声明数组 int[ ] a; //声明数组时不规定数组长度 2.分配空间 a new int[5]; //分配空间: 告诉计算机分配几个连续的空间。eg:scores new int[30]; avgAge new int[6]; name new String[30]; 3.赋值 a [0] 8; //向分配的格子里放数…

结构体易忘点

结构体初始化 当我们去初始化一个结构体的时候,我们常常会按变量顺序初始化,但其实也可以不按顺序,同时也可以部分数据初始化。 结构体对齐 结构体里面的成员有一定的对齐规则,他不是每一个空间都存着有效数据的,有些…

大型语言模型 (LLM) 劫持攻击不断升级,导致每天损失超过 100,000 美元

Sysdig 威胁研究团队 (TRT) 报告称,LLMjacking(大型语言模型劫持)事件急剧增加,攻击者通过窃取的云凭证非法访问大型语言模型 (LLM)。 这一趋势反映了 LLM 访问黑市的不断增长,攻击者的动机包括个人使用和规避禁令和制…

小米机型“工程固件” 小米13工程资源预览 写入以及nv损坏修复

目前各大品牌机型中。可以录数于小米机型的工程固件最全 最多。这个也由于小米机型的加密机制比较特殊 。每款新机型发布后不久。工程包就会出现。从小米5起始以及红米note4起始都有工程固件。另外在维修行业中。米系机型更换cpu都需要先写入对应的绑定包。然后才可以写入官方m…

C++竞赛初阶L1-16-第七单元-字符串(36~37课)559: T456513 统计数字字符个数

题目内容 输入一行字符,统计出其中数字字符的个数。 输入格式 一行字符串,总长度不超过 255。 输出格式 输出为 1 行,输出字符串里面数字字符的个数。 样例 1 输入 Today is 2021-03-27 样例 1 输出 8 程序代码输出: #i…

idea多模块启动

文章目录 idea多模块启动2018版本的idea2019版本的idea idea多模块启动 2018版本的idea 1.首先看一下view> Tool Windows下有没有Run Dashboard 如果有,点击一下底部的窗口就会出现 如果不存在,执行下一步 2.查看自己项目的工作空间位置 点击 File&…

获取参数

获取querystring参数 querystring 指的是URL中 ? 后面携带的参数,例如:http://127.0.0.1:9090/web?query杨超越。 获取请求的querystring参数的方法如下: 方法1: Query package main// querystringimport ("github.com/…

如何通过IntelliJ IDEA 创建HTML项目

1、什么是IDEA? IntelliJ IDEA 是 JetBrains 开发的一款集成开发环境(IDE),主要用于 Java 编程,但也支持其他编程语言如 Kotlin、Groovy 和 Scala。它的特点包括智能代码补全、代码重构、集成版本控制、调试工具和丰富的插件支持。IDEA 提供了一个直观的用户界面,帮助开发…

ffmpeg面向对象——参数配置秘密探索及其设计模式

ffmpeg支持很多参数配置——拉流配置推流配置等等——那么庞大繁杂的配置项,如果是你,该如何实现呢? 其实看过一点点源码(不用全部)后发现,就是它的实现也是遵循一个朴素的思想——所谓“大道至简”&#x…

用 Delphi 实现一个基本的网页邮件抓取和发送功能

如何用 Delphi 实现一个基本的网页邮件抓取和发送功能。以下示例仅作为概念验证,实际应用中需要考虑更多的细节和技术问题。 示例:从简单网页抓取邮件并发送 1. 环境准备 假设你已经安装了 Delphi,并且安装了 Indy 组件库。Indy 是一个用于…

用Python提取PowerPoint演示文稿中的音频和视频

将多种格式的媒体内容进行重新利用(如PowerPoint演示中的音频和视频)是非常有价值的。无论是创建独立的音频文件、提取视频以便在线分发,还是为了未来的使用需求进行资料归档,从演示文稿中提取这些媒体文件可以为多媒体内容的多次…

linux 系统是如何收发数据包

目录 1. 背景 1.1 协议栈的构成 1. 应用层: 2. Socket 层: 3. 传输层 (TCP/UDP): 4. 网络层 (IP): 5. 数据链路层 (MAC): 6. 物理层 (网卡驱动): 1.2 数据包的组成 2. 接收网络数据包的流程 2.1 数据包接收流程概述 2.2 详细步骤说明 2.2.1 网卡接收数据包 2.2.2…

JVM 虚拟机的编译器、类加载过程、类加载器有哪些?

JVM 虚拟机的编译器 编译器可以分为:前端编译器、JIT 编译器、AOT编译器。 前端编译器:源代码 --> 字节码 在Java语言中,JDK安装目录中的javac就是编译器。它负责将Java源代码编译为字节码。因为处于编译的前期,javac也叫做前…

C语言 | Leetcode C语言题解之第417题太平洋大西洋水流问题

题目: 题解: static const int dirs[4][2] {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};void bfs(int row, int col, bool ** ocean, const int ** heights, int m, int n) {if (ocean[row][col]) {return;}ocean[row][col] true;int * queue (int *)malloc…

如何安装和注册 GitLab Runner

如何安装和注册 GitLab Runner GitLab Runner 是一个用于运行 GitLab CI/CD (Continuous Integration/Continuous Deployment) 作业。它是一个与 GitLab 配合使用的应用程序,可以在本地或云中运行。Runner 可以执行不同类型的作业,例如编译代码、运行测…