卷积操作 —— P17 小土堆

本文介绍了如何使用PyTorch库中的convolution操作,包括设置输入矩阵、调整卷积核形状、设置stride和padding,以及演示了不同参数对输出结果的影响。

1.设置输入矩阵和卷积核

2.利用reshape改变 x 的shape以满足input的参数

3.调用conv2d,并查看输出结果

4.stride:核每次移动的步数

5.padding:在输入的边上填充数据

完整代码


convolution

官方文档

1.设置输入矩阵和卷积核

import torch

# 二维矩阵的输入
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需要是这种shape 

input:输入

weight:核

stride:核每次移动的步数

2.利用reshape改变 x 的shape以满足input的参数

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

3.调用conv2d,并查看输出结果

import torch.nn.functional as F
output = F.conv2d(input1, kernel, stride=1)
print(output)

输出

4.stride:核每次移动的步数

stride=1时:

stride=2时:

5.padding:在输入的边上填充数据

完整代码

import torch
import torch.nn.functional as F

# 二维矩阵的输入
input1 = 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]])

input1 = torch.reshape(input1, (1, 1, 5, 5))
kernel = torch.reshape(kernel, (1, 1, 3, 3))

# print(input1.shape)  # 输出input和kernel的shape
# print(kernel.shape)  # 满足conv2d的参数要求

# stride=1
output = F.conv2d(input1, kernel, stride=1)
print(output)
# stride=2
output2 = F.conv2d(input1, kernel, stride=2)
print(output2)
# padding
output3 = F.conv2d(input1, kernel, stride=1, padding=1)
print(output3)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值