Skip to content

Commit 6eb15ea

Browse files
author
wz
committed
feature: add gpu support for alexnet
1 parent da17b7c commit 6eb15ea

File tree

4 files changed

+47
-24
lines changed

4 files changed

+47
-24
lines changed

pytorch_learning/Test2_alexnet/model.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,23 @@ def __init__(self, num_classes=1000, init_weights=False):
88
self.features = nn.Sequential(
99
nn.Conv2d(3, 48, kernel_size=11, stride=4, padding=2), # input[3, 224, 224] output[48, 55, 55]
1010
nn.ReLU(inplace=True),
11-
nn.MaxPool2d(kernel_size=3, stride=2), # output[48, 27, 27]
12-
nn.Conv2d(48, 128, kernel_size=5, padding=2), # output[128, 27, 27]
11+
nn.MaxPool2d(kernel_size=3, stride=2), # output[48, 27, 27]
12+
nn.Conv2d(48, 128, kernel_size=5, padding=2), # output[128, 27, 27]
1313
nn.ReLU(inplace=True),
14-
nn.MaxPool2d(kernel_size=3, stride=2), # output[128, 13, 13]
15-
nn.Conv2d(128, 192, kernel_size=3, padding=1), # output[192, 13, 13]
14+
nn.MaxPool2d(kernel_size=3, stride=2), # output[128, 13, 13]
15+
nn.Conv2d(128, 192, kernel_size=3, padding=1), # output[192, 13, 13]
1616
nn.ReLU(inplace=True),
17-
nn.Conv2d(192, 192, kernel_size=3, padding=1), # output[192, 13, 13]
17+
nn.Conv2d(192, 192, kernel_size=3, padding=1), # output[192, 13, 13]
1818
nn.ReLU(inplace=True),
19-
nn.Conv2d(192, 128, kernel_size=3, padding=1), # output[128, 13, 13]
19+
nn.Conv2d(192, 128, kernel_size=3, padding=1), # output[128, 13, 13]
2020
nn.ReLU(inplace=True),
21-
nn.MaxPool2d(kernel_size=3, stride=2), # output[128, 6, 6]
21+
nn.MaxPool2d(kernel_size=3, stride=2), # output[128, 6, 6]
2222
)
2323
self.classifier = nn.Sequential(
24-
nn.Dropout(p=0.2),
24+
nn.Dropout(p=0.5),
2525
nn.Linear(128 * 6 * 6, 2048),
2626
nn.ReLU(inplace=True),
27-
nn.Dropout(p=0.2),
27+
nn.Dropout(p=0.5),
2828
nn.Linear(2048, 2048),
2929
nn.ReLU(inplace=True),
3030
nn.Linear(2048, num_classes),

pytorch_learning/Test2_alexnet/predict.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,5 @@
3737
output = torch.squeeze(model(img))
3838
predict = torch.softmax(output, dim=0)
3939
predict_cla = torch.argmax(predict).numpy()
40-
print(class_indict[str(predict_cla)])
40+
print(class_indict[str(predict_cla)], predict[predict_cla].item())
4141
plt.show()

pytorch_learning/Test2_alexnet/train.py

+28-12
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
from model import AlexNet
88
import os
99
import json
10+
import time
11+
12+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
1013

1114
data_transform = {
1215
"train": transforms.Compose([transforms.RandomResizedCrop(224),
@@ -31,17 +34,17 @@
3134
with open('class_indices.json', 'w') as json_file:
3235
json_file.write(json_str)
3336

34-
batch_size = 32
37+
batch_size = 64
3538
train_loader = torch.utils.data.DataLoader(train_dataset,
3639
batch_size=batch_size, shuffle=True,
37-
num_workers=0)
40+
num_workers=16)
3841

3942
validate_dataset = datasets.ImageFolder(root=image_path + "/val",
4043
transform=data_transform["val"])
4144
val_num = len(validate_dataset)
4245
validate_loader = torch.utils.data.DataLoader(validate_dataset,
4346
batch_size=batch_size, shuffle=False,
44-
num_workers=0)
47+
num_workers=16)
4548

4649
# test_data_iter = iter(validate_loader)
4750
# test_image, test_label = test_data_iter.next()
@@ -54,40 +57,53 @@
5457

5558

5659
net = AlexNet(num_classes=5, init_weights=True)
60+
61+
net.to(device)
5762
loss_function = nn.CrossEntropyLoss()
5863
pata = list(net.parameters())
59-
optimizer = optim.Adam(net.parameters(), lr=0.0005)
64+
optimizer = optim.Adam(net.parameters(), lr=0.0002)
6065

61-
for epoch in range(10):
66+
save_path = './AlexNet.pth'
67+
best_acc = 0.0
68+
for epoch in range(15):
6269
# train
6370
net.train()
6471
running_loss = 0.0
72+
t1 = time.perf_counter()
6573
for step, data in enumerate(train_loader, start=0):
6674
images, labels = data
6775
# imshow(torchvision.utils.make_grid(images))
6876
# print(' '.join('%5s' % flower_set[labels[j]] for j in range(8)))
6977
optimizer.zero_grad()
70-
outputs = net(images)
71-
loss = loss_function(outputs, labels)
78+
outputs = net(images.to(device))
79+
loss = loss_function(outputs, labels.to(device))
7280
loss.backward()
7381
optimizer.step()
7482

7583
# print statistics
7684
running_loss += loss.item()
85+
# print train process
86+
rate = (step + 1) / len(train_loader)
87+
a = "*" * int(rate * 50)
88+
b = "." * int((1 - rate) * 50)
89+
print("\rtrain loss: {:^3.0f}%[{}->{}]{:.3f}".format(int(rate * 100), a, b, loss), end="")
90+
print()
91+
print(time.perf_counter()-t1)
7792

7893
# validate
7994
net.eval()
8095
acc = 0.0 # accumulate accurate number / epoch
8196
with torch.no_grad():
8297
for data_test in validate_loader:
8398
test_images, test_labels = data_test
84-
outputs = net(test_images)
99+
outputs = net(test_images.to(device))
85100
predict_y = torch.max(outputs, dim=1)[1]
86-
acc += (predict_y == test_labels).sum().item()
101+
acc += (predict_y == test_labels.to(device)).sum().item()
102+
accurate_test = acc / val_num
103+
if accurate_test > best_acc:
104+
best_acc = accurate_test
105+
torch.save(net.state_dict(), save_path)
87106
print('[epoch %d] train_loss: %.3f test_accuracy: %.3f' %
88107
(epoch + 1, running_loss / step, acc / val_num))
89108

90-
91109
print('Finished Training')
92-
save_path = './AlexNet.pth'
93-
torch.save(net.state_dict(), save_path)

summary_problem.md

+9-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## Tensorflow2.1 GPU安装与Pytorch1.3 GPU安装
2+
参考我之前写的博文:[Centos7 安装Tensorflow2.1 GPU以及Pytorch1.3 GPU(CUDA10.1)](https://blog.csdn.net/qq_37541097/article/details/103933366)
3+
4+
15
## keras functional api训练的模型权重与subclassed训练的模型权重能否混用 [tensorflow2.0.0]
26
强烈不建议混用,即使两个模型的名称结构完全一致也不要混用,里面有坑,用什么方法训练的模型就载入相应的模型权重
37

@@ -16,6 +20,9 @@ model.build((batch_size, height, width, channel))
1620
* 安装graphviz,并添加相关环境变量
1721
参考连接:https://github.com/XifengGuo/CapsNet-Keras/issues/7
1822

19-
## 为什么每计算一个batch,就需要调用一次optimizer.zero_grad()
23+
## 为什么每计算一个batch,就需要调用一次optimizer.zero_grad() [Pytorch1.3]
2024
如果不清除历史梯度,就会对计算的历史梯度进行累加(通过这个特性你能够变相实现一个很大batch数值的训练)
21-
参考链接:https://www.zhihu.com/question/303070254
25+
参考链接:https://www.zhihu.com/question/303070254
26+
27+
## Pytorch1.3 ImportError: cannot import name 'PILLOW_VERSION' [Pytorch1.3]
28+
pillow版本过高导致,安装版本号小于7.0.0即可

0 commit comments

Comments
 (0)