example

1
2
3
4
5
6
7
8
9
10
11
12
import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 20, 5)
self.conv2 = nn.Conv2d(20, 20, 5)

def forward(self, x):
x = F.relu(self.conv1(x))
return F.relu(self.conv2(x))

最简单的神经网络

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
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Pytorch_learn
@File :nn.module.py
@IDE :PyCharm
@Author :咋
@Date :2023/7/2 16:19
"""
import torch
from torch.nn import Module
import torch.nn as nn
import torch.nn.functional as F

class MyModule(Module):
def __init__(self):
super().__init__()
# self.conv1 = nn.Conv2d(1, 20, 5)
# self.conv2 = nn.Conv2d(20, 20, 5)

def forward(self, x):
# x = F.relu(self.conv1(x))
return x+1

x = torch.tensor(1) #创建一个tensor1

model = MyModule() # 实例化模型

output = model(x) # callback

print(output)
# print(modle.forward(x))

神经网络实战

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
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Pytorch_learn
@File :nn.module.py
@IDE :PyCharm
@Author :咋
@Date :2023/7/2 16:19
"""
import torch
from torch.nn import Module
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from torchvision import transforms
class MyModule(Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 20, 5)
self.conv2 = nn.Conv2d(20, 20, 5)

def forward(self, x):
x = F.relu(self.conv1(x))
return x



image_path = "test.jpg"
image = Image.open(image_path).convert("L")
tran_tensor = transforms.ToTensor()
image_tensor = tran_tensor(image)


image_tensor = image_tensor.unsqueeze(0)
print(image_tensor.shape)
model = MyModule() # 实例化模型

output = model(image_tensor) # callback

print(output)
# print(modle.forward(x))
  • unsqueeze(0)可以添加维度,其中0为维度的索引
  • 也可以用一个torch.reshape(-1,3,28,28)去改变大小,-1表示让他自己计算。