-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
108 lines (80 loc) · 2.13 KB
/
main.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
#include<iostream>
#include<string>
#include<vector>
#include<utility>
#include"Matrix.h"
#include"numeric.h"
#include"BP.h"
#include"Optimizer.h"
#include"SGD.h"
#include"dataloader.h"
#include<glog/logging.h>
BPnet trainBP();
void testBP(BPnet&);
int main(void) {
// set up logger
google::InitGoogleLogging("BP_Logger");
google::SetStderrLogging(google::INFO);
BPnet net;
// training
net = trainBP();
LOG(INFO) << "training done !\n\n\n";
// test
testBP(net);
return 0;
}
BPnet trainBP() {
using namespace std;
// hidden layer structures, change network stuctures here
vector<int> hidden_nums;
hidden_nums.reserve(3);
hidden_nums.push_back(4);
hidden_nums.push_back(5);
hidden_nums.push_back(10);
// optimizer
SGD_OPT optimizer{std::make_shared<SGD>(1e-3, 0.9)};
BPnet net(hidden_nums, "gaussian", optimizer);
// dataloader
int batch_size = 32;
Dataloader dl("../data/cifar_dbs/train.db");
// training
int iter_num = 10;
double loss(0);
MATRIX img;
MATRIX label;
for (int i{0}; i < iter_num; i++) {
auto batch = dl.get_one_batch(batch_size);
img = batch.first;
label = batch.second;
// one training iteration
loss = net.train(img, label);
LOG(INFO) << "iteration: " << iter_num
<< ", loss: " << loss << std::endl;
}
return net;
}
void testBP(BPnet& net) {
using namespace std;
// test data
int batch_size = 32;
Dataloader dl("../data/cifar_dbs/test.db");
dl.set_batch_size(32);
LOG(INFO) << "dataloader initialized \n";
MATRIX img;
MATRIX scores;
MATRIX pred;
vector<MATRIX> vsc;
int iter_num = dl.get_iter_num(batch_size);
LOG(INFO) << "iter number by batch size " << batch_size
<< ": " << iter_num << std::endl;
vsc.reserve(iter_num);
for (int i{0}; i < iter_num; ++i) {
auto batch = dl.get_one_batch();
img = batch.first;
vsc.push_back(net.forward(img));
}
scores = MATRIX::tile(vsc);
pred = scores.argmax(1);
scores.shape().print();
pred.shape().print();
}