Skip to content

Commit 8f12a39

Browse files
committed
添加第6章python代码
1 parent ee04897 commit 8f12a39

File tree

9 files changed

+444
-1
lines changed

9 files changed

+444
-1
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,7 @@ __pycache__/
99
Thumbs.db
1010

1111

12+
.vscode/
13+
.idea/
1214

13-
15+
*.pth

pytorch-06/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
data/

pytorch-06/README.md

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
2+
3+
## 1 使用net.py
4+
```bash
5+
Accuracy of the network on the 10000 test images : 59 %
6+
[10, 2000] loss: 0.801
7+
Accuracy of the network on the 10000 test images : 61 %
8+
[10, 4000] loss: 0.845
9+
Accuracy of the network on the 10000 test images : 62 %
10+
[10, 6000] loss: 0.859
11+
Accuracy of the network on the 10000 test images : 60 %
12+
[10, 8000] loss: 0.876
13+
Accuracy of the network on the 10000 test images : 61 %
14+
[10, 10000] loss: 0.885
15+
Accuracy of the network on the 10000 test images : 61 %
16+
[10, 12000] loss: 0.881
17+
Accuracy of the network on the 10000 test images : 62 %
18+
Finished Training
19+
GroundTruth: cat ship ship plane
20+
Accuracy of plane : 73 %
21+
Accuracy of car : 78 %
22+
Accuracy of bird : 47 %
23+
Accuracy of cat : 47 %
24+
Accuracy of deer : 55 %
25+
Accuracy of dog : 52 %
26+
Accuracy of frog : 74 %
27+
Accuracy of horse : 67 %
28+
Accuracy of ship : 66 %
29+
Accuracy of truck : 61 %
30+
```
31+
32+
33+
34+
## 2 使用cnn_net.py
35+
```bash
36+
[10, 2000] loss: 0.291
37+
Accuracy of the network on the 10000 test images : 68 %
38+
[10, 4000] loss: 0.321
39+
Accuracy of the network on the 10000 test images : 69 %
40+
[10, 6000] loss: 0.353
41+
Accuracy of the network on the 10000 test images : 68 %
42+
[10, 8000] loss: 0.398
43+
Accuracy of the network on the 10000 test images : 67 %
44+
[10, 10000] loss: 0.445
45+
Accuracy of the network on the 10000 test images : 67 %
46+
[10, 12000] loss: 0.438
47+
Accuracy of the network on the 10000 test images : 68 %
48+
Finished Training
49+
GroundTruth: cat ship ship plane
50+
Accuracy of plane : 62 %
51+
Accuracy of car : 77 %
52+
Accuracy of bird : 58 %
53+
Accuracy of cat : 51 %
54+
Accuracy of deer : 65 %
55+
Accuracy of dog : 61 %
56+
Accuracy of frog : 80 %
57+
Accuracy of horse : 70 %
58+
Accuracy of ship : 80 %
59+
Accuracy of truck : 80 %
60+
```
61+
62+
## 3 使用net_gap.py
63+
```bash
64+
[10, 2000] loss: 1.008
65+
Accuracy of the network on the 10000 test images : 62 %
66+
[10, 4000] loss: 0.990
67+
Accuracy of the network on the 10000 test images : 64 %
68+
[10, 6000] loss: 0.993
69+
Accuracy of the network on the 10000 test images : 63 %
70+
[10, 8000] loss: 0.978
71+
Accuracy of the network on the 10000 test images : 64 %
72+
[10, 10000] loss: 0.991
73+
Accuracy of the network on the 10000 test images : 63 %
74+
[10, 12000] loss: 0.998
75+
Accuracy of the network on the 10000 test images : 64 %
76+
Finished Training
77+
Accuracy of plane : 76 %
78+
Accuracy of car : 84 %
79+
Accuracy of bird : 42 %
80+
Accuracy of cat : 25 %
81+
Accuracy of deer : 41 %
82+
Accuracy of dog : 65 %
83+
Accuracy of frog : 84 %
84+
Accuracy of horse : 56 %
85+
Accuracy of ship : 74 %
86+
Accuracy of truck : 72 %
87+
```
88+
89+
90+
## 4 vgg.py
91+
```bash
92+
Accuracy of the network on the 10000 test images : 82 %
93+
[10, 2000] loss: 0.190
94+
Accuracy of the network on the 10000 test images : 81 %
95+
[10, 4000] loss: 0.201
96+
Accuracy of the network on the 10000 test images : 82 %
97+
[10, 6000] loss: 0.214
98+
Accuracy of the network on the 10000 test images : 82 %
99+
[10, 8000] loss: 0.210
100+
Accuracy of the network on the 10000 test images : 82 %
101+
[10, 10000] loss: 0.215
102+
Accuracy of the network on the 10000 test images : 81 %
103+
[10, 12000] loss: 0.229
104+
Accuracy of the network on the 10000 test images : 81 %
105+
Finished Training
106+
Accuracy of plane : 77 %
107+
Accuracy of car : 94 %
108+
Accuracy of bird : 74 %
109+
Accuracy of cat : 58 %
110+
Accuracy of deer : 86 %
111+
Accuracy of dog : 78 %
112+
Accuracy of frog : 89 %
113+
Accuracy of horse : 87 %
114+
Accuracy of ship : 90 %
115+
Accuracy of truck : 87 %
116+
```
117+

pytorch-06/cifar.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
2+
import torch.nn as nn
3+
4+
from load_data import *
5+
# from net import *
6+
# from cnn_net import *
7+
from net_gap import *
8+
net = Net()
9+
# from vgg import VGG
10+
# net = VGG('VGG16')
11+
12+
13+
def val():
14+
correct = 0
15+
total = 0
16+
with torch.no_grad():
17+
for data in testloader:
18+
images, labels = data
19+
outputs = net(images)
20+
_, predicted = torch.max(outputs.data, 1)
21+
# print(images.size(), labels.size(), predicted.size())
22+
total += labels.size(0)
23+
correct += (predicted == labels).sum().item()
24+
print('Accuracy of the network on the 10000 test images : %d %%' %(100 * correct/total))
25+
26+
import torch.optim as optim
27+
28+
29+
def train():
30+
criterion = nn.CrossEntropyLoss()
31+
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
32+
33+
for epoch in range(10): # loop over the dataset multiple times
34+
running_loss = 0.0
35+
for i, data in enumerate(trainloader, 0):
36+
# get the inputs; data is a list of [inputs, labels]
37+
inputs, labels = data
38+
39+
# zero the parameter gradients
40+
optimizer.zero_grad()
41+
42+
# forward + backward + optimize
43+
outputs = net(inputs)
44+
loss = criterion(outputs, labels)
45+
loss.backward()
46+
optimizer.step()
47+
48+
# print statistics
49+
running_loss += loss.item()
50+
if i % 2000 == 1999: # print every 2000 mini-batches
51+
print('[%d, %5d] loss: %.3f' %
52+
(epoch + 1, i + 1, running_loss / 2000))
53+
running_loss = 0.0
54+
55+
val()
56+
print('Finished Training')
57+
58+
train()
59+
60+
PATH = './cifar_net.pth'
61+
torch.save(net.state_dict(), PATH)
62+
63+
64+
65+
66+
# dataiter = iter(testloader)
67+
# images, labels = dataiter.next()
68+
69+
# # print images
70+
# imshow(torchvision.utils.make_grid(images))
71+
# print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
72+
73+
class_correct = list(0. for i in range(10))
74+
class_total = list(0. for i in range(10))
75+
with torch.no_grad():
76+
for data in testloader:
77+
images, labels = data
78+
outputs = net(images)
79+
_, predicted = torch.max(outputs, 1)
80+
c = (predicted == labels).squeeze()
81+
for i in range(4):
82+
label = labels[i]
83+
class_correct[label] += c[i].item()
84+
class_total[label] += 1
85+
86+
87+
for i in range(10):
88+
print('Accuracy of %5s : %2d %%' % (
89+
classes[i], 100 * class_correct[i] / class_total[i]))
90+

pytorch-06/cnn_net.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
2+
import torch.nn as nn
3+
import torch.nn.functional as F
4+
5+
6+
class Net(nn.Module):
7+
def __init__(self):
8+
super(Net, self).__init__()
9+
self.conv1 = nn.Conv2d(3, 16, 5)
10+
self.pool = nn.MaxPool2d(2, 2)
11+
self.conv2 = nn.Conv2d(16, 36, 3)
12+
self.fc1 = nn.Linear(1296, 128) # 1296 = 6 * 6 * 36
13+
self.fc2 = nn.Linear(128, 10)
14+
15+
def forward(self, x):
16+
x = self.pool(F.relu(self.conv1(x)))
17+
x = self.pool(F.relu(self.conv2(x)))
18+
x = x.view(-1, 36 * 6 * 6)
19+
x = F.relu(self.fc1(x))
20+
x = F.relu(self.fc2(x))
21+
return x
22+
23+
24+
def init_weigths(net):
25+
for m in net.modules():
26+
if isinstance(m, nn.Conv2d):
27+
nn.init.normal_(m.weight)
28+
nn.init.xavier_normal_(m.weight)
29+
nn.init.kaiming_normal_(m.weight)
30+
nn.init.constant_(m.bias, 0)
31+
elif isinstance(m, nn.Linear):
32+
nn.init.normal_(m.weight)
33+
34+
35+
def main():
36+
net = Net()
37+
print("查看网络结构:")
38+
print(net)
39+
40+
print("查看网络前几层:")
41+
print(nn.Sequential(*list(net.children()))[:4])
42+
43+
44+
if __name__ == '__main__':
45+
main()

pytorch-06/load_data.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
2+
3+
import torch
4+
import torchvision
5+
import torchvision.transforms as transforms
6+
7+
transform = transforms.Compose(
8+
[transforms.ToTensor(),
9+
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
10+
11+
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
12+
download=True, transform=transform)
13+
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
14+
shuffle=True, num_workers=2)
15+
16+
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
17+
download=True, transform=transform)
18+
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
19+
shuffle=False, num_workers=2)
20+
21+
classes = ('plane', 'car', 'bird', 'cat',
22+
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
23+
24+
25+
import matplotlib.pyplot as plt
26+
import numpy as np
27+
28+
# functions to show an image
29+
30+
31+
def imshow(img):
32+
img = img / 2 + 0.5 # unnormalize
33+
npimg = img.numpy()
34+
plt.imshow(np.transpose(npimg, (1, 2, 0)))
35+
plt.show()
36+
37+
38+
def main():
39+
# get some random training images
40+
dataiter = iter(trainloader)
41+
images, labels = dataiter.next()
42+
43+
# show images
44+
imshow(torchvision.utils.make_grid(images))
45+
# print labels
46+
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))
47+
48+
49+
50+
if __name__ == '__main__':
51+
main()

pytorch-06/net.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
2+
import torch.nn as nn
3+
import torch.nn.functional as F
4+
5+
6+
class Net(nn.Module):
7+
def __init__(self):
8+
super(Net, self).__init__()
9+
self.conv1 = nn.Conv2d(3, 6, 5)
10+
self.pool = nn.MaxPool2d(2, 2)
11+
self.conv2 = nn.Conv2d(6, 16, 5)
12+
self.fc1 = nn.Linear(16 * 5 * 5, 120)
13+
self.fc2 = nn.Linear(120, 84)
14+
self.fc3 = nn.Linear(84, 10)
15+
16+
def forward(self, x):
17+
x = self.pool(F.relu(self.conv1(x)))
18+
x = self.pool(F.relu(self.conv2(x)))
19+
x = x.view(-1, 16 * 5 * 5)
20+
x = F.relu(self.fc1(x))
21+
x = F.relu(self.fc2(x))
22+
x = self.fc3(x)
23+
return x
24+
25+
26+
def init_weigths(net):
27+
for m in net.modules():
28+
if isinstance(m, nn.Conv2d):
29+
nn.init.normal_(m.weight)
30+
nn.init.xavier_normal_(m.weight)
31+
nn.init.kaiming_normal_(m.weight)
32+
nn.init.constant_(m.bias, 0)
33+
elif isinstance(m, nn.Linear):
34+
nn.init.normal_(m.weight)
35+
36+
37+
def main():
38+
net = Net()
39+
print("查看网络结构:")
40+
print(net)
41+
42+
print("查看网络前几层:")
43+
print(nn.Sequential(*list(net.children()))[:4])
44+
45+
46+
if __name__ == '__main__':
47+
main()

0 commit comments

Comments
 (0)