神经网络的基本骨架 nn.module 与卷积操作

复制代码
import torch
from torch import nn


class Tudui(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, input):
        output = input + 1
        return output
    def __call__(self, input):
        return self.forward(input)

tudui = Tudui()
x = torch.tensor(1.0)
output = tudui(x)
print(output)

疑问:tudui = Tudui()

output=tudui(x) 为何写成output = Tudui(x)就会报错

PyTorch 的标准做法(先创建实例,再调用实例)

  • tudui = Tudui() 创建了 Tudui 类的一个实例。
  • 这个实例可以被多次使用,而不需要每次都创建新的对象。
  • 写 output = Tudui(x) 时,Python 实际上在做两件事:
    a) 创建 Tudui 类的实例
    b) 尝试用 x 作为参数调用这个新创建的实例

卷积操作

复制代码
import torch
import torch.nn.functional as F

input = torch.tensor([[1, 2, 0, 3, 1],
                      [0, 1, 2, 3, 1],
                      [1, 2, 1, 0, 0],
                      [5, 2, 3, 1, 1],
                      [2, 1, 0, 1, 1]])

kernel = torch.tensor([[1, 2, 1],
                       [0, 1, 0],
                       [2, 1, 0]])

input = torch.reshape(input,shape=(1,1,5,5))
kernel = torch.reshape(kernel, (1, 1, 3, 3))

print(input.shape)
print(kernel.shape)

output = F.conv2d(input, kernel, stride=1)
print(output)

output2 = F.conv2d(input, kernel, stride=2)
print(output2)

output3 = F.conv2d(input, kernel, stride=1, padding=1)
print(output3)

padding = 1 就是 在原卷积层周围一圈补0

相关推荐
aneasystone本尊几秒前
学习大模型训练的监督微调:SFT 与 LoRA
人工智能
lucas_AI2 分钟前
Mira Murati 公司第二代模型来了:Inkling 2 Small 首日闭门、下周开源,AA Index 直接冲到 31
人工智能
byte轻骑兵2 分钟前
【LMP】规范精讲[13]: 参数的户口本、公钥的集装箱与出厂的兜底值
人工智能·网络协议·人机交互·lmp·蓝牙链路管理
天天被压力3 分钟前
【A股分钟级高频数据完全手册 #03】股票历史1分钟K线数据接口怎么用:Pro版批量拉取与本地缓存
java·人工智能·python
lucas_AI9 分钟前
INT4 提速 2 倍的真相:batch 一大就「穿帮」,9B–20B 模型量化部署实测盘点
人工智能
深蓝AI3 小时前
Gemini 4 Carbon 登顶却买不到:59 分拿下智能指数第一,单任务 7.76 美元,幻觉率从 4% 涨到 11%
人工智能·程序员
云-缩影9 小时前
文生图技术落地:从广告到游戏,哪些场景真的能用
人工智能·游戏
冬奇Lab12 小时前
一天一个开源项目(第254篇):NVIDIA Auto Ontology —— 给数据 Agent 搭一层「可认证的语义层」,答不了就老实说答不了
人工智能
其实防守也摸鱼12 小时前
个人学习 Pwn 思路:从基础到漏洞利用的进阶路径
大数据·前端·人工智能·chrome·算法·安全·网络安全