-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mytrain.py
143 lines (112 loc) · 4.66 KB
/
Mytrain.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import torch
from torch import nn
from MyLeNet import MyNet
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from torchvision import transforms
import os
import time
import datetime
from MyData import MyDataSet
checkpoints_dir = "D:\\PythonProject\\LeNet\\checkpoints"
new_data_path = "D:\\PythonProject\\LeNet\\newdata"
# 将数据转化为tensor
data_transform = transforms.Compose([
transforms.ToTensor()
])
# 加载训练数据集
train_dataset = MyDataSet(new_data_path, mode='train')
train_dataloader = DataLoader(dataset=train_dataset, batch_size=4, shuffle=True)
# 加载测试数据集
val_dataset = MyDataSet(new_data_path, mode='val')
val_dataloader = DataLoader(dataset=val_dataset, batch_size=4, shuffle=True)
# 如果有显卡,可以转到GPU
device = "cuda" if torch.cuda.is_available() else "cpu"
# 调用MyNet模型,将模型数据转到GPU
model = MyNet().to(device)
# model.load_state_dict(torch.load("D:\\PythonProject\\LeNet\\checkpoints\\best_model.pt"))
# 定义损失函数
loss_fn = nn.CrossEntropyLoss()
# 定义一个优化器
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3, momentum=0.9)
# 学习率每隔十轮,变为原来的0.1
lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)
# 定义训练函数
def train(dataloader, model, loss_fn, optimizer):
loss, current, n = 0.0, 0.0, 0
for batch, (x, y) in enumerate(dataloader):
# 前向传播
x, y = x.to(device), y.to(device)
output = model(x)
cur_loss = loss_fn(output, y)
_, pred = torch.max(output, dim=1)
cur_acc = torch.sum(y == pred) / output.shape[0]
optimizer.zero_grad()
cur_loss.backward()
optimizer.step()
loss += cur_loss.item()
current += cur_acc.item()
n = n + 1
print("train loss: " + str(loss / n))
print("train acc: " + str(current / n))
log_file = open(os.path.join(checkpoints_dir, "log.txt"), "a+")
log_file.write("Epoch %d | loss = %.3f | current = %.3f\n" % (epoch, loss / n, current / n))
log_file.flush()
log_file.close()
def val(dataloader, model, loss_fn):
model.eval()
loss, current, n = 0.0, 0.0, 0
with torch.no_grad():
for batch, (x, y) in enumerate(dataloader):
# 前向传播
x, y = x.to(device), y.to(device)
output = model(x)
cur_loss = loss_fn(output, y)
_, pred = torch.max(output, dim=1)
cur_acc = torch.sum(y == pred) / output.shape[0]
loss += cur_loss.item()
current += cur_acc.item()
n = n + 1
print("val loss: " + str(loss / n))
print("val acc: " + str(current / n))
log_file = open(os.path.join(checkpoints_dir, "log.txt"), "a+")
log_file.write("Epoch %d | loss = %.3f | current = %.3f\n" % (epoch, loss / n, current / n))
log_file.flush()
log_file.close()
return loss / n
# 开始训练
if __name__ == '__main__':
if not os.path.exists(checkpoints_dir):
os.mkdir(checkpoints_dir)
epochs = 10
max_loss = 1
for epoch in range(epochs):
print("\nepoch: %d" % (epoch + 1))
with open(os.path.join(checkpoints_dir, "log.txt"), "a+") as log_file:
# strftime(),格式化输出时间
localtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 打印训练时间
log_file.write(localtime)
log_file.write("\n======================training epoch %d======================\n" % (epoch + 1))
t1 = time.time()
train(train_dataloader, model, loss_fn, optimizer)
t2 = time.time()
print("Training consumes %.2f second" % (t2 - t1))
with open(os.path.join(checkpoints_dir, "log.txt"), "a+") as log_file:
log_file.write("Training consumes %.2f second\n" % (t2 - t1))
with open(os.path.join(checkpoints_dir, "log.txt"), "a+") as log_file:
log_file.write("\n======================validate epoch %d======================\n" % (epoch + 1))
t1 = time.time()
a = val(val_dataloader, model, loss_fn)
t2 = time.time()
print("Validation consumes %.2f second" % (t2 - t1))
with open(os.path.join(checkpoints_dir, "log.txt"), "a+") as log_file:
log_file.write("Validation consumes %.2f second\n\n" % (t2 - t1))
# 保存最好的模型权重
if a < max_loss:
folder = 'checkpoints'
if not os.path.exists(folder):
os.mkdir('checkpoints')
max_loss = a
print("save best model\n")
torch.save(model.state_dict(), 'checkpoints/newbest_model.pt')
print("Done!!!")