神经网络的基本骨架 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

相关推荐
港股研究社5 小时前
餐饮IPO冰封期,袁记食品的“供应链平台”启示
大数据·人工智能·物联网
重生之我是小技6 小时前
2026 年 YouTube 与其他平台运营测评:流量、变现与内容生态全解析
大数据·人工智能
小蒋观天下6 小时前
两轮车检测AI摄像头:场景分化下的行业竞争与卡位机遇
人工智能·安全·计算机视觉·语音识别·ai大模型
无忧智库6 小时前
做AI短剧的工具有哪些?按环节拆分工具链与提示词准备方法
人工智能
小徐xxx6 小时前
各种卷积操作的介绍
深度学习·医学图像处理·医学图像分割·卷积
小宋10216 小时前
SQL + RAG 混合问答实战:结构化指标与文档证据如何统一路由
java·jvm·人工智能·sql
Tartly6 小时前
本地跑大模型,数据不用出内网|NUC 16 Pro
大数据·人工智能
小朱爱编程1236 小时前
当 AI 开始研发下一代 AI:“智能爆炸”离我们还有多远?
人工智能·深度学习
每周报刊6 小时前
智能手表健康监测实测:心率、血氧数据靠谱吗?
人工智能·智能手表