-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_model.cpp
327 lines (313 loc) · 14.8 KB
/
train_model.cpp
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
//
// Created by Dengweiwei on 2021/11/16.
//
#include "train_model.h"
using namespace std::chrono;
dww::TASK_CAT dww::get_task_cat(const std::string &filename) {
const std::string& temp = task.at(filename);
if(temp == "multi-class")
return MULTI_CLASS;
else if(temp == "multi-label, binary-class")
return MULTI_LABEL_BINARY_CLASS;
else if(temp == "binary-class")
return BINARY_CLASS;
else
return ORDINAL_REGRESSION;
}
void dww::train_1_channel_model(const std::string& filename,int64_t epoch,int64_t batch,double lr){
std::string path = "../parameters/conv_unit/" + filename;
std::ofstream log_file(path,ios_base::trunc);
assert(log_file.is_open() && "File doesn't open!");
log_file << "Dataset " << filename << " : " << '\n';
log_file << "Train Samples : " << samples.at(filename).at("train")
<< " | Val Samples : " << samples.at(filename).at("val")
<< " | Test Samples : " << samples.at(filename).at("test") << '\n';
using std::chrono::high_resolution_clock;
TORCH_MODULE(Test_1_1_CHAN_Model);
torch::Device device = torch::cuda::is_available() ? torch::kCUDA : torch::kCPU;
// 根据数据集 filename 的标签个数,定义针对该数据集的卷积神经网络
int64_t label_sz = label_num.at(filename);
bool is_multi_label_binary_class = task.at(filename) == "multi-label, binary-class";
Test_1_1_CHAN_Model OneCNet(label_sz);
log_file << "Network Model: ";
log_file << OneCNet << '\n';
// 使用 GPU 进行训练
OneCNet->to(device);
// 获取 filename 数据集中的 TRIN、VAL、TEST 数据集
dww::MedDataSet all_data(filename);
// 获取训练数据集
dww::MedDataSetLoader train_data(all_data,dww::DATA_CAT::TRIN,batch);
// 获取 Valuation 数据集
dww::MedDataSetLoader val_data(all_data,dww::DATA_CAT::VAL,2 * batch);
// 测试数据集用来进行 Inference 操作
// 使用随机梯度下降优化算法
torch::optim::SGD optimizer(OneCNet->parameters(),torch::optim::SGDOptions(lr));
high_resolution_clock::time_point start = high_resolution_clock::now();
double total_acc = 0.0;
for(size_t ep = 1; ep <= epoch; ++ep) {
log_file << "\t Epoch : " << ep;
train_1_channel(*OneCNet,optimizer,train_data,device,is_multi_label_binary_class);
double acc = val_1_channel(*OneCNet,val_data,device,is_multi_label_binary_class);
total_acc += acc;
log_file << "\tAcc : " << acc*100 << "%\n";
}
high_resolution_clock::time_point end = high_resolution_clock::now();
double time_consume = duration_cast<duration<double>>(end - start).count();
total_acc /= epoch;
log_file << "\tEpoch: " << epoch
<<"\tBatch: " << batch
<< "\tlr: " << lr
<< "\tTime Consume: " << time_consume << " seconds"
<< "\tAverage Acc: " << total_acc * 100 << "%\n";
std::string param_path = "../model/conv_unit/";
for(auto pair : OneCNet->named_parameters()){
std::string sub_path = filename;
sub_path += "/";
std::string temp = pair.key();
size_t pos = temp.find_first_of('.');
temp[pos] = '_';
sub_path += temp;
sub_path += ".pt";
torch::save(pair.value(),param_path + sub_path);
}
log_file << "\n\n";
log_file.flush();
log_file.close();
}
void dww::train_mnist_model(const std::string& filename,int64_t epoch,int64_t batch,double lr){
TORCH_MODULE(MNISTSimpleModel);
torch::Device device = torch::cuda::is_available() ? torch::kCUDA : torch::kCPU;
// 根据数据集 filename 的标签个数,定义针对该数据集的卷积神经网络
int64_t label_sz = 10;
MNISTSimpleModel OneCNet(label_sz);
// 使用 GPU 进行训练
OneCNet->to(device);
// 获取 MNIST 数据中的 TRIN、TEST 数据集
dww::MNISTDataSet all_data("mnist");
// 获取 TRAIN 数据集
dww::MNISTDataSetLoader train_data(all_data,dww::DATA_CAT::TRIN,batch);
// 获取 TEST 数据集
dww::MNISTDataSetLoader test_data(all_data,dww::DATA_CAT::TEST,2 * batch);
// 使用随机梯度下降优化算法
torch::optim::SGD optimizer(OneCNet->parameters(),torch::optim::SGDOptions(lr));
for(int64_t ep = 1; ep <= epoch; ++ep){
std::cout << "Epoch : " << ep << "\n";
train_1_channel(*OneCNet,optimizer,train_data,device);
double acc = val_1_channel(*OneCNet,test_data,device);
std::cout << "\tAcc : " << acc*100 << "%\n";
}
}
void dww::train_1_channel(BaseModelImpl& model,
torch::optim::Optimizer& optimizer,
dww::BaseDataLoader& train_data,
const torch::Device& device,bool is_multi_label_binary_class){
int64_t batch_num = train_data.get_batch_num();
model.train();
for(int64_t sz = 0; sz < batch_num; ++sz){
optimizer.zero_grad();
torch::Tensor image = train_data.images[sz].to(device);
torch::Tensor label = train_data.labels[sz].to(device);
torch::Tensor predict = model.forward(image);
torch::Tensor loss = is_multi_label_binary_class ? torch::binary_cross_entropy_with_logits(predict,label) : torch::cross_entropy_loss(predict,label);
loss.backward();
optimizer.step();
std::cout << "\t[" << sz+1 << "/" << batch_num << "],Loss : " << loss.item<double>() << "\n";
}
}
double dww::val_1_channel(BaseModelImpl& model,dww::BaseDataLoader& val_data,
const torch::Device& device,bool is_multi_label_binary_class){
int64_t samples_num = val_data.samples_num;
int64_t batch_num = val_data.get_batch_num();
int64_t correct = 0;
model.eval();
for(int64_t sz = 0; sz < batch_num; ++sz){
torch::Tensor image = val_data.images[sz].to(device);
torch::Tensor label = val_data.labels[sz].to(device);
int64_t batch_size = label.size(0);
torch::Tensor predict = model.forward(image);
torch::Tensor cmp;
cmp = is_multi_label_binary_class ? predict.argmax(1) - label.argmax(1) : predict.argmax(1) - label;
correct += (batch_size - cmp.count_nonzero().item<int64_t>());
}
return static_cast<double>(correct) / static_cast<double>(samples_num);
}
void dww::train_LeNet_model(const std::string& filename,int64_t epoch,int64_t batch,double lr){
std::string path = "../parameters/lenet/" + filename;
std::ofstream log_file(path,ios_base::trunc);
assert(log_file.is_open() && "File doesn't open!");
log_file << "Dataset " << filename << " : " << '\n';
log_file << "Train Samples : " << samples.at(filename).at("train")
<< " | Val Samples : " << samples.at(filename).at("val")
<< " | Test Samples : " << samples.at(filename).at("test") << '\n';
using std::chrono::high_resolution_clock;
TORCH_MODULE(LeNet);
torch::Device device = torch::cuda::is_available() ? torch::kCUDA : torch::kCPU;
// 根据数据集 filename 的标签个数,定义针对该数据集的卷积神经网络
int64_t label_sz = label_num.at(filename);
bool is_multi_label_binary_class = task.at(filename) == "multi-label, binary-class";
LeNet OneCNet(label_sz);
log_file << "Network Model: ";
log_file << OneCNet << '\n';
// 使用 GPU 进行训练
OneCNet->to(device);
// 获取 filename 数据集中的 TRIN、VAL、TEST 数据集
dww::MedDataSet all_data(filename);
// 获取训练数据集
dww::MedDataSetLoader train_data(all_data,dww::DATA_CAT::TRIN,batch);
// 获取 Valuation 数据集
dww::MedDataSetLoader val_data(all_data,dww::DATA_CAT::VAL,2 * batch);
// 测试数据集用来进行 Inference 操作
// 使用随机梯度下降优化算法
torch::optim::SGD optimizer(OneCNet->parameters(),torch::optim::SGDOptions(lr));
high_resolution_clock::time_point start = high_resolution_clock::now();
double total_acc = 0.0;
for(size_t ep = 1; ep <= epoch; ++ep) {
log_file << "\t Epoch : " << ep;
train_1_channel(*OneCNet,optimizer,train_data,device,is_multi_label_binary_class);
double acc = val_1_channel(*OneCNet,val_data,device,is_multi_label_binary_class);
total_acc += acc;
log_file << "\tAcc : " << acc*100 << "%\n";
}
high_resolution_clock::time_point end = high_resolution_clock::now();
double time_consume = duration_cast<duration<double>>(end - start).count();
total_acc /= epoch;
log_file << "\tEpoch: " << epoch
<<"\tBatch: " << batch
<< "\tlr: " << lr
<< "\tTime Consume: " << time_consume << " seconds"
<< "\tAverage Acc: " << total_acc * 100 << "%\n";
std::string param_path = "../model/lenet/";
for(auto pair : OneCNet->named_parameters()){
std::string sub_path = filename;
sub_path += "/";
std::string temp = pair.key();
size_t pos = temp.find_first_of('.');
temp[pos] = '_';
sub_path += temp;
sub_path += ".pt";
torch::save(pair.value(),param_path + sub_path);
}
log_file << "\n\n";
log_file.flush();
log_file.close();
}
void dww::train_CryptoNets_model(const std::string& filename,int64_t epoch,int64_t batch,double lr){
std::string path = "../parameters/cryptonets/" + filename;
std::ofstream log_file(path,ios_base::trunc);
assert(log_file.is_open() && "File doesn't open!");
log_file << "Dataset " << filename << " : " << '\n';
log_file << "Train Samples : " << samples.at(filename).at("train")
<< " | Val Samples : " << samples.at(filename).at("val")
<< " | Test Samples : " << samples.at(filename).at("test") << '\n';
using std::chrono::high_resolution_clock;
TORCH_MODULE(CryptoNets);
torch::Device device = torch::cuda::is_available() ? torch::kCUDA : torch::kCPU;
// 根据数据集 filename 的标签个数,定义针对该数据集的卷积神经网络
int64_t label_sz = label_num.at(filename);
bool is_multi_label_binary_class = task.at(filename) == "multi-label, binary-class";
CryptoNets OneCNet(label_sz);
log_file << "Network Model: ";
log_file << OneCNet << '\n';
// 使用 GPU 进行训练
OneCNet->to(device);
// 获取 filename 数据集中的 TRIN、VAL、TEST 数据集
dww::MedDataSet all_data(filename);
// 获取训练数据集
dww::MedDataSetLoader train_data(all_data,dww::DATA_CAT::TRIN,batch);
// 获取 Valuation 数据集
dww::MedDataSetLoader val_data(all_data,dww::DATA_CAT::VAL,2 * batch);
// 测试数据集用来进行 Inference 操作
// 使用随机梯度下降优化算法
torch::optim::SGD optimizer(OneCNet->parameters(),torch::optim::SGDOptions(lr));
high_resolution_clock::time_point start = high_resolution_clock::now();
double total_acc = 0.0;
for(size_t ep = 1; ep <= epoch; ++ep) {
log_file << "\t Epoch : " << ep;
train_1_channel(*OneCNet,optimizer,train_data,device,is_multi_label_binary_class);
double acc = val_1_channel(*OneCNet,val_data,device,is_multi_label_binary_class);
total_acc += acc;
log_file << "\tAcc : " << acc*100 << "%\n";
}
high_resolution_clock::time_point end = high_resolution_clock::now();
double time_consume = duration_cast<duration<double>>(end - start).count();
total_acc /= epoch;
log_file << "\tEpoch: " << epoch
<<"\tBatch: " << batch
<< "\tlr: " << lr
<< "\tTime Consume: " << time_consume << " seconds"
<< "\tAverage Acc: " << total_acc * 100 << "%\n";
std::string param_path = "../model/cryptonets/";
for(auto pair : OneCNet->named_parameters()){
std::string sub_path = filename;
sub_path += "/";
std::string temp = pair.key();
size_t pos = temp.find_first_of('.');
temp[pos] = '_';
sub_path += temp;
sub_path += ".pt";
torch::save(pair.value(),param_path + sub_path);
}
log_file << "\n\n";
log_file.flush();
log_file.close();
}
void dww::train_LoLaDense_model(const std::string& filename,int64_t epoch,int64_t batch,double lr){
std::string path = "../parameters/loladense/" + filename;
std::ofstream log_file(path,ios_base::trunc);
assert(log_file.is_open() && "File doesn't open!");
log_file << "Dataset " << filename << " : " << '\n';
log_file << "Train Samples : " << samples.at(filename).at("train")
<< " | Val Samples : " << samples.at(filename).at("val")
<< " | Test Samples : " << samples.at(filename).at("test") << '\n';
using std::chrono::high_resolution_clock;
TORCH_MODULE(LoLaDense);
torch::Device device = torch::cuda::is_available() ? torch::kCUDA : torch::kCPU;
// 根据数据集 filename 的标签个数,定义针对该数据集的卷积神经网络
int64_t label_sz = label_num.at(filename);
bool is_multi_label_binary_class = task.at(filename) == "multi-label, binary-class";
LoLaDense OneCNet(label_sz);
log_file << "Network Model: ";
log_file << OneCNet << '\n';
// 使用 GPU 进行训练
OneCNet->to(device);
// 获取 filename 数据集中的 TRIN、VAL、TEST 数据集
dww::MedDataSet all_data(filename);
// 获取训练数据集
dww::MedDataSetLoader train_data(all_data,dww::DATA_CAT::TRIN,batch);
// 获取 Valuation 数据集
dww::MedDataSetLoader val_data(all_data,dww::DATA_CAT::VAL,2 * batch);
// 测试数据集用来进行 Inference 操作
// 使用随机梯度下降优化算法
torch::optim::SGD optimizer(OneCNet->parameters(),torch::optim::SGDOptions(lr));
high_resolution_clock::time_point start = high_resolution_clock::now();
double total_acc = 0.0;
for(size_t ep = 1; ep <= epoch; ++ep) {
log_file << "\t Epoch : " << ep;
train_1_channel(*OneCNet,optimizer,train_data,device,is_multi_label_binary_class);
double acc = val_1_channel(*OneCNet,val_data,device,is_multi_label_binary_class);
total_acc += acc;
log_file << "\tAcc : " << acc*100 << "%\n";
}
high_resolution_clock::time_point end = high_resolution_clock::now();
double time_consume = duration_cast<duration<double>>(end - start).count();
total_acc /= epoch;
log_file << "\tEpoch: " << epoch
<<"\tBatch: " << batch
<< "\tlr: " << lr
<< "\tTime Consume: " << time_consume << " seconds"
<< "\tAverage Acc: " << total_acc * 100 << "%\n";
std::string param_path = "../model/loladense/";
for(auto pair : OneCNet->named_parameters()){
std::string sub_path = filename;
sub_path += "/";
std::string temp = pair.key();
size_t pos = temp.find_first_of('.');
temp[pos] = '_';
sub_path += temp;
sub_path += ".pt";
torch::save(pair.value(),param_path + sub_path);
}
log_file << "\n\n";
log_file.flush();
log_file.close();
}