-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
85 lines (69 loc) · 2.32 KB
/
main.cpp
File metadata and controls
85 lines (69 loc) · 2.32 KB
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
#include "parser.tab.hpp"
#include "model.h"
void optimize(Model& model, int steps, double mom, double lr);
void gdm(Model& model, int steps, double mom, double lr);
std::map<std::string, double> gradient(const Model& model);
void info(const Model& model);
int main(int argc, char* argv[]) {
Model model;
yy::parser parser(model);
int parseRes = parser.parse();
if (parseRes != 0) {
std::cerr << "Parse error: " << parseRes << std::endl;
return parseRes;
}
for (const auto& farg : model.arguments) {
if (model.vars.find(farg) == model.vars.end()) {
std::cerr << "Uninitialized variable: " << farg << std::endl;
return 1;
}
}
if (argc == 3 && strcmp(argv[1], "-steps") == 0) {
if (model.arguments.empty()) {
std::cerr << "Function is constant" << std::endl;
return 1;
}
int steps = std::stoi(argv[2]);
optimize(model, steps, 0.9, 0.01);
} else {
info(model);
}
return 0;
}
void optimize(Model& model, int steps, double mom, double lr) {
gdm(model, steps, mom, lr);
double fvalue = model.ast->value(model.vars, "").first;
std::cout << "Function value: " << fvalue << std::endl;
for (const auto& var: model.vars) {
std::cout << var.first << ": " << var.second << std::endl;
}
}
void gdm(Model& model, int steps, double mom, double lr) {
std::map<std::string, double> rates;
for (const auto& arg: model.arguments) {
rates.insert(std::make_pair(arg, 0.0));
}
for (int step = 0; step < steps; step++) {
std::map<std::string, double> grad = gradient(model);
for (const auto& partial : grad) {
rates[partial.first] = mom * rates[partial.first] + lr * partial.second;
model.vars[partial.first] -= rates[partial.first];
}
}
}
std::map<std::string, double> gradient(const Model& model) {
std::map<std::string, double> grad;
for (const auto& farg: model.arguments) {
Dual dual = model.ast->value(model.vars, farg);
grad.insert(std::make_pair(farg, dual.second));
}
return grad;
}
void info(const Model& model) {
double fvalue = model.ast->value(model.vars, "").first;
std::map<std::string, double> grad = gradient(model);
std::cout << "Function value: " << fvalue << std::endl;
for (const auto& partial: grad) {
std::cout << "Derivative d/d" << partial.first << ": " << partial.second << std::endl;
}
}