0%

深度学习——nn.Module的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

import torch
import torch.nn.functional as F

# 测试covolution的工作机制

# 输入数据
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]
])

# 查看输入是否符合要求
print(input.shape)
print(kernel.shape)

# 不符合数据要求的使用reshape函数行转换
input = torch.reshape(input, (1, 1, 5, 5))
kernel = torch.reshape(kernel, (1, 1, 3, 3))

# 查看转换后的数据格式,符合要求
print(input.shape)
print(kernel.shape)

# 设置stride卷积参数查看卷积结果
output = F.conv2d(input, kernel, stride=1)
# 查看卷积结果
print(output)

# 设置padding参数
output = F.conv2d(input, kernel, stride=1, padding=1)
# 查看卷积结果
print(output)