2023.3.31学习记录

发布时间 2023-03-31 15:19:00作者: MementoMorizx
p13 nn.Moudle的使用
import torch
from torch import nn

#面向对象编程思想
class Tudui(nn.Module):#声明一个Tudui类继承自名叫nn.Module的父类

def __init__(self) -> None:#Tuidui类中的构造方法
super().__init__() #使用super调用了父类nn.Module中的__init__构造方法

def forward(self, input):#声明一个forward方法,该方法的功能是使输入的值加1,并返回+1后的值(forward方法为python中的内置方法)
output = input + 1
return output
def a(self,input2):#声明一个a方法,该方法的功能是使输入的值加2,并返回+2后的值(a方法为自己定义的方法)
output2 = input2 + 2
return output2


#实例化类对象
x = torch.tensor(1.0) #将tensor类型的数据1.0赋值给变量x
tudui = Tudui()

#外部调用
#外部调用python中的内置方法
output = tudui(x)
print(output)
#外部调用类中的自定义方法
output2 = tudui.a(10)
print(output2)

p14土堆说卷积操作
import torch
import torch.nn.functional as F

# 输入5*5的二维矩阵
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]]

)
print(input.shape)
print(input.size)
# 定义卷积核
kernel = torch.tensor([[1, 2, 1],
[0, 1, 0],
[2, 1, 0]])
#input可理解为需要输入格式为(batchsize,channel,height,weight)
input = torch.reshape(input, (1, 1, 5, 5))
kernel = torch.reshape(kernel, (1, 1, 3, 3))

#input为输入的图片,kernel为设置的卷积核,stride为步长,padding为是否填充
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)