MCPcopy Create free account
hub / github.com/AllentDan/LibtorchTutorials / Initialize

Method Initialize

lesson5-TrainingVGG/Classification.cpp:14–58  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

12}
13
14void Classifier::Initialize(int _num_classes, std::string _pretrained_path){
15 std::vector<int> cfg_d = {64, 64, -1, 128, 128, -1, 256, 256, 256, -1, 512, 512, 512, -1, 512, 512, 512, -1};
16 auto net_pretrained = VGG(cfg_d,1000,true);
17 vgg = VGG(cfg_d,_num_classes,true);
18 torch::load(net_pretrained, _pretrained_path);
19 torch::OrderedDict<std::string, at::Tensor> pretrained_dict = net_pretrained->named_parameters();
20 torch::OrderedDict<std::string, at::Tensor> model_dict = vgg->named_parameters();
21
22 for (auto n = pretrained_dict.begin(); n != pretrained_dict.end(); n++)
23 {
24 if (strstr((*n).key().data(), "classifier")) {
25 continue;
26 }
27 model_dict[(*n).key()] = (*n).value();
28 }
29
30 torch::autograd::GradMode::set_enabled(false); // make parameters copying possible
31 auto new_params = model_dict; // implement this
32 auto params = vgg->named_parameters(true /*recurse*/);
33 auto buffers = vgg->named_buffers(true /*recurse*/);
34 for (auto& val : new_params) {
35 auto name = val.key();
36 auto* t = params.find(name);
37 if (t != nullptr) {
38 t->copy_(val.value());
39 }
40 else {
41 t = buffers.find(name);
42 if (t != nullptr) {
43 t->copy_(val.value());
44 }
45 }
46 }
47 torch::autograd::GradMode::set_enabled(true);
48 try
49 {
50 vgg->to(device);
51 }
52 catch (const std::exception&e)
53 {
54 std::cout << e.what() << std::endl;
55 }
56
57 return;
58}
59
60void Classifier::Train(int num_epochs, int batch_size, float learning_rate, std::string train_val_dir, std::string image_type, std::string save_path){
61 std::string path_train = train_val_dir+ "\\train";

Callers 1

mainFunction · 0.45

Calls 7

beginMethod · 0.80
endMethod · 0.80
dataMethod · 0.80
whatMethod · 0.80
keyMethod · 0.45
valueMethod · 0.45
findMethod · 0.45

Tested by

no test coverage detected