首页 > 其他分享 >111

111

时间:2023-12-07 11:12:41浏览次数:34  
标签:kernel nn self 111 out channel size

import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange

# Borrowed from ''Improving image restoration by revisiting global information aggregation''
# --------------------------------------------------------------------------------
train_size = (1, 3, 256, 256)


class AvgPool2d(nn.Module):
    def __init__(self, kernel_size=None, base_size=None, auto_pad=True, fast_imp=False):
        super().__init__()
        self.kernel_size = kernel_size
        self.base_size = base_size
        self.auto_pad = auto_pad

        # only used for fast implementation
        self.fast_imp = fast_imp
        self.rs = [5, 4, 3, 2, 1]
        self.max_r1 = self.rs[0]
        self.max_r2 = self.rs[0]

    def extra_repr(self) -> str:
        return 'kernel_size={}, base_size={}, stride={}, fast_imp={}'.format(
            self.kernel_size, self.base_size, self.kernel_size, self.fast_imp
        )

    def forward(self, x):
        if self.kernel_size is None and self.base_size:
            if isinstance(self.base_size, int):
                self.base_size = (self.base_size, self.base_size)
            self.kernel_size = list(self.base_size)
            self.kernel_size[0] = x.shape[2] * self.base_size[0] // train_size[-2]
            self.kernel_size[1] = x.shape[3] * self.base_size[1] // train_size[-1]

            # only used for fast implementation
            self.max_r1 = max(1, self.rs[0] * x.shape[2] // train_size[-2])
            self.max_r2 = max(1, self.rs[0] * x.shape[3] // train_size[-1])

        if self.fast_imp:  # Non-equivalent implementation but faster
            h, w = x.shape[2:]
            if self.kernel_size[0] >= h and self.kernel_size[1] >= w:
                out = F.adaptive_avg_pool2d(x, 1)
            else:
                r1 = [r for r in self.rs if h % r == 0][0]
                r2 = [r for r in self.rs if w % r == 0][0]
                r1 = min(self.max_r1, r1)
                r2 = min(self.max_r2, r2)
                s = x[:, :, ::r1, ::r2].cumsum(dim=-1).cumsum(dim=-2)
                n, c, h, w = s.shape
                k1, k2 = min(h - 1, self.kernel_size[0] // r1), min(w - 1, self.kernel_size[1] // r2)
                out = (s[:, :, :-k1, :-k2] - s[:, :, :-k1, k2:] - s[:, :, k1:, :-k2] + s[:, :, k1:, k2:]) / (k1 * k2)
                out = torch.nn.functional.interpolate(out, scale_factor=(r1, r2))
        else:
            n, c, h, w = x.shape
            s = x.cumsum(dim=-1).cumsum(dim=-2)
            s = torch.nn.functional.pad(s, (1, 0, 1, 0))  # pad 0 for convenience
            k1, k2 = min(h, self.kernel_size[0]), min(w, self.kernel_size[1])
            s1, s2, s3, s4 = s[:, :, :-k1, :-k2], s[:, :, :-k1, k2:], s[:, :, k1:, :-k2], s[:, :, k1:, k2:]
            out = s4 + s1 - s2 - s3
            out = out / (k1 * k2)

        if self.auto_pad:
            n, c, h, w = x.shape
            _h, _w = out.shape[2:]
            pad2d = ((w - _w) // 2, (w - _w + 1) // 2, (h - _h) // 2, (h - _h + 1) // 2)
            out = torch.nn.functional.pad(out, pad2d, mode='replicate')

        return out


# --------------------------------------------------------------------------------


class BasicConv(nn.Module):
    def __init__(self, in_channel, out_channel, kernel_size, stride, bias=True, norm=False, relu=True, transpose=False):
        super(BasicConv, self).__init__()
        if bias and norm:
            bias = False

        padding = kernel_size // 2
        layers = list()
        if transpose:
            padding = kernel_size // 2 - 1
            layers.append(
                nn.ConvTranspose2d(in_channel, out_channel, kernel_size, padding=padding, stride=stride, bias=bias))
        else:
            layers.append(nn.Conv2d(in_channel, out_channel, kernel_size, padding=padding, stride=stride, bias=bias))
        if norm:
            layers.append(nn.BatchNorm2d(out_channel))
        if relu:
            layers.append(nn.GELU())
        self.main = nn.Sequential(*layers)

    def forward(self, x):
        return self.main(x)


class Gap(nn.Module):
    def __init__(self, in_channel, mode) -> None:
        super().__init__()

        self.fscale_d = nn.Parameter(torch.zeros(in_channel), requires_grad=True)
        self.fscale_h = nn.Parameter(torch.zeros(in_channel), requires_grad=True)
        if mode == 'train':
            self.gap = nn.AdaptiveAvgPool2d((1, 1))
        elif mode == '500epoch':
            self.gap = AvgPool2d(base_size=246)

    def forward(self, x):
        x_d = self.gap(x)
        x_h = (x - x_d) * (self.fscale_h[None, :, None, None] + 1.)
        x_d = x_d * self.fscale_d[None, :, None, None]
        return x_d + x_h


# class YYBlock(nn.Module):
#     def __init__(self, in_channel=3, out_channel=20, relu_slope=0.2):
#         super(YYBlock, self).__init__()
#
#         self.spatialConv = nn.Sequential(*[
#             nn.Conv2d(in_channel, out_channel, kernel_size=3, padding=1, bias=True),
#             nn.LeakyReLU(relu_slope, inplace=False),
#             nn.Conv2d(out_channel, out_channel, kernel_size=3, padding=1, bias=True),
#             nn.LeakyReLU(relu_slope, inplace=False)
#         ])
#
#         self.identity = nn.Conv2d(in_channel, out_channel, 1, 1, 0)
#
#         self.fftConv2 = nn.Sequential(*[
#             nn.Conv2d(out_channel, out_channel, 1, 1, 0),
#             nn.LeakyReLU(relu_slope, inplace=False),
#             nn.Conv2d(out_channel, out_channel, 1, 1, 0)
#         ])
#
#         self.fusion = nn.Conv2d(out_channel * 2, out_channel, 1, 1, 0)
#
#
#     def forward(self, x1):
#         spatial_out = self.spatialConv(x1)
#         identity_out = self.identity(x1)
#         out = spatial_out + identity_out
#
#         x_fft = torch.fft.rfft2(out, norm='backward')
#         x_amp = torch.abs(x_fft)
#         x_phase = torch.angle(x_fft)
#
#         enhanced_phase = self.fftConv2(x_phase)
#         enhanced_amp = self.fftConv2(x_amp)
#         # x_fft_out1 = torch.fft.irfft2(x_amp * torch.exp(1j * enhanced_phase), norm='backward')
#         x_fft_out2 = torch.fft.irfft2(enhanced_amp * torch.exp(1j * x_phase), norm='backward')
#
#         # out = self.fusion(torch.cat([out, x_fft_out2], dim=1))
#
#         return x_fft_out2

class SpaBlock(nn.Module):
    def __init__(self, in_channel=3, out_channel=20, relu_slope=0.2):
        super(SpaBlock, self).__init__()
        self.identity = nn.Conv2d(in_channel, out_channel, 1, 1, 0)
        self.conv1 = BasicConv(in_channel, out_channel, kernel_size=3, stride=1, relu=True)

        self.spatialConv = nn.Sequential(*[
            # nn.Conv2d(in_channel, out_channel, kernel_size=3, padding=1, bias=True),
            # nn.GELU(),
            nn.Conv2d(out_channel, out_channel, kernel_size=3, padding=1, bias=True),
            nn.LeakyReLU(relu_slope, inplace=False),
            nn.Conv2d(out_channel, out_channel, kernel_size=3, padding=1, bias=True),
            nn.LeakyReLU(relu_slope, inplace=False)
        ])

    def forward(self, x):
        conv1_out = self.conv1(x)
        spa_out = self.spatialConv(conv1_out)
        iden_out = self.identity(conv1_out)
        out = iden_out + spa_out

        return out


class FreqBlock(nn.Module):
    def __init__(self, in_channel=3, out_channel=20, relu_slope=0.2):
        super(FreqBlock, self).__init__()
        self.freqConv = nn.Sequential(*[
            nn.Conv2d(out_channel, out_channel, 1, 1, 0),
            nn.LeakyReLU(relu_slope, inplace=False),
            nn.Conv2d(out_channel, out_channel, 1, 1, 0)
        ])

    def forward(self, x):
        x_fft = torch.fft.rfft2(x, norm='backward')
        x_amp = torch.abs(x_fft)
        x_phase = torch.angle(x_fft)

        # enhanced_phase = self.fftConv2(x_phase)
        enhanced_amp = self.freqConv(x_amp)
        x_fft_out2 = torch.fft.irfft2(enhanced_amp * torch.exp(1j * x_phase), norm='backward')

        return x_fft_out2


class ResBlock(nn.Module):
    def __init__(self, in_channel, out_channel, mode, filter=False):
        super(ResBlock, self).__init__()
        self.spaBlock = SpaBlock(in_channel, out_channel)
        self.freqBlock = FreqBlock(in_channel, out_channel)

    def forward(self, x):
        out = self.spaBlock(x)
        out = self.freqBlock(out)
        out = out + x

        return out



# class ResBlock(nn.Module):
#     def __init__(self, in_channel, out_channel, mode, filter=False):
#         super(ResBlock, self).__init__()
#         self.conv1 = BasicConv(in_channel, out_channel, kernel_size=3, stride=1, relu=False)
#
#         self.yyBlock = YYBlock(in_channel, out_channel, relu_slope=0.2)
#         self.filter = filter
#
#     def forward(self, x):
#         out = self.conv1(x)
#
#         out = self.yyBlock(out)
#
#         out = out + x
#         return out
View Code

 

标签:kernel,nn,self,111,out,channel,size
From: https://www.cnblogs.com/yyhappy/p/17881248.html

相关文章

  • 搭建DG备库Recover database报错ORA-19909、ORA-01110
    一、问题现象客户环境LinuxOracle11.2.0.4两节点RAC主库,2节点备库;需要对这个客户的数据库使用dg切换进行迁移;第一轮搭建ADG完成后,failoverDG备库变成测试库给开发应用人员进行测试;第二轮正式切换之前,搭建重建ADG环境,restoredatabase正常,recoverdatabase报错ThuOct......
  • 20211105李宜时信息安全系统设计与实现学习笔记12
    20211105李宜时信息安全系统设计与实现学习笔记121.引言背景介绍:介绍MySQL数据库及其在业界的普及和应用,解释为何在Linux环境下学习MySQL是重要的。学习目标:明确学习MySQL的目标,比如理解数据库原理,掌握基本操作,或者成为数据库管理员。2.安装和配置安装步骤:详细描述在不......
  • Linux命令(111)之groupadd
    linux命令之groupadd1.groupadd介绍linux命令groupadd是用来创建新的用户组,用户组信息会被添加到系统文件(/etc/group)中。2.groupadd用法groupadd[参数]GroupNamegroupadd常用参数参数说明-g指定用户组的gid号-r创建系统工作组-f如果组已经存在则成功退出3.实例3.1.创建普......
  • P8111 [Cnoi2021] 区间
    [Cnoi2021]区间LuoguP8111题目背景Cirno有一个区间\([a,b](1\lea\leb\len)\),而你的任务是在规定的次数内帮Rumia猜出这个区间。每次,你可向Cirno询问一个数字\(k\),而Cirno会告诉你这个数字与区间\([a,b]\)的关系。题目描述为了猜到这个区间,你需要实现一个函......
  • 苹果iPhone因没有存储空间而死机和不断重启,重启白苹果黑底,恢复模式更新系统报错1110,解
    参考自:https://www.bilibili.com/video/BV1Mr4y1X7cT/?spm_id_from=333.337.search-card.all.click&vd_source=869b36c3961d4a89a184a469bc7589bb手机苹果iPhone,存储满,提示重启后白苹果,无法进入系统。操作方法:1、mac雷电接手机后,进入DFU,短按一下音量加键并松开,立刻再短按音量减......
  • 20211128《信息安全系统设计与实现》第十四章学习笔记
    一、任务内容自学教材第14章,提交学习笔记(10分)1.知识点归纳以及自己最有收获的内容,选择至少2个知识点利用chatgpt等工具进行苏格拉底挑战,并提交过程截图,提示过程参考下面内容(4分)“我在学***X知识点,请你以苏格拉底的方式对我进行提问,一次一个问题”核心是要求GPT:“请你以苏格......
  • 202311127
    C/S结构用户界面设计 【实验编号】10003809547j 图形用户界面设计【实验学时】8学时【实验环境】l 所需硬件环境为微机;l 所需软件环境为MicrosoftVisualStudio2013【实验内容】本次做的C/S框架的信息管理系统是一种比较经典的信息管理系统,实现了对于人员的的......
  • 20231117上机编程[高可靠在线视频]
    某电信公司推出高可靠的在线视频业务。为了保证可靠性,公司针对不同视频类型,准备了不同的专用网络通道,并对指定视频类型服务进行通道分配。一个用户在一个时段只能使用一个视频服务,可以多次申请。请实现以下功能:VideoService(int[]channels,int[]charge) :初始化系统channel......
  • 111
    首先将原区间分块(设块的大小是T)先处理处每一个数字的vector再处理一个num数组,表示一连串子块之间的出现了偶数次的数字的个数。复杂度为\(O((N/T)^2)\)对于每一个询问如果询问的端点再同一个块里面,暴力循环记录每一个数字的出现次数(cnt数组)输出答案,然后再暴力循环把每一个数字......
  • FS2111 是一款低静态电流、高效率、PFM 模式控制的同步升压变换器
    干电池升压芯片是一种能够将3V、3.3V、4.5V、5V等电压升压至所需电压的芯片。这种芯片具有高效率、低功耗、小体积、轻重量等特点,广泛应用于各种需要升压的领域,如手电筒、数码相机、蓝牙耳机等。干电池升压芯片的升压输出范围一般在3V-5V之间可调,可以根据实际需求进行调节。在升压......