]> git.sesse.net Git - wloh/blob - bayeswf.cpp
Invert the Hessian using Eigen instead of just using the diagonal. Gives slightly...
[wloh] / bayeswf.cpp
1 #include <stdio.h>
2 #include <math.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <Eigen/Core>
6 #include <Eigen/Eigenvalues>
7
8 #include <map>
9 #include <vector>
10 #include <string>
11 #include <algorithm>
12
13 using namespace std;
14 using namespace Eigen;
15
16 #define PRIOR_MU 1500
17 #define PRIOR_WEIGHT 1.0
18 #define MAX_PLAYERS 4096
19 #define DUMP_RAW 0
20
21 float mu[MAX_PLAYERS];
22 float mu_stddev[MAX_PLAYERS];
23 float global_sigma = 70.0f;
24 float prior_sigma = 70.0f;
25
26 #define EPSILON 1e-3
27
28 /*
29  * L(mu_vec, sigma_vec, matches) = product[ L(mu_A, sigma_A, mu_B, sigma_B, score_AB - score_BA) ]
30  * log-likelihood = sum[ log( L(mu_A, sigma_A, mu_B, sigma_B, score_AB - score_BA) ) ]
31  * 
32  * L(mu1, sigma1, mu2, sigma2, score2 - score1) = sigmoid(mu2 - mu1, sqrt(sigma1² + sigma2²), (score2 - score1))
33  *
34  * pdf := 1/(sigma * sqrt(2*Pi)) * exp(-(x - mu)^2 / (2 * sigma^2));        
35  * pdfs := subs({ mu = mu1 - mu2, sigma = sqrt(sigma1^2 + sigma2^2) }, pdf);
36  * diff(log(pdfs), mu1); 
37  */
38
39 struct match {
40         int player, other_player;
41         int margin;
42         float weight;
43 };
44 map<int, vector<match> > matches_for_player;
45 vector<match> all_matches;
46
47 void dump_scores(const vector<string> &players, const float *mu, const float *mu_stddev, int num_players)
48 {
49 #if 0
50         for (int i = 0; i < num_players; ++i) {
51                 printf("%s=[%5.1f, %4.1f] ", players[i].c_str(), mu[i], sigma[i]);
52         }
53         printf("\n");
54 #elif 0
55         for (int i = 0; i < num_players; ++i) {
56                 printf("%5.1f ", mu[i]);
57         }
58         printf("\n");
59 #else
60         for (int i = 0; i < num_players; ++i) {
61                 printf("%f %f %s\n", mu[i], mu_stddev[i], players[i].c_str());
62         }
63 #endif
64 }
65
66 /*
67  * diff(logL, mu1) = -w * (mu1 - mu2 - x) / sigma_c^2
68  * maximizer for mu1 is given by: sum_i[ (w_i/sigma_c_i)^2 (mu1 - mu2_i - x_i) ] = 0
69  *                                sum_i[ (w_i/sigma_c_i)^2 mu1 ] = sum_i [ (w_i/sigma_c_i)^2 ( mu2_i + x_i ) ]
70  *                                mu1 = sum_i [ (w_i/sigma_c_i)^2 ( mu2_i + x_i ) ] / sum_i[ (w_i/sigma_c_i)^2 ]
71  */
72 void update_mu(float *mu, int player_num, const vector<match> &matches)
73 {
74         if (matches.empty()) {
75                 return;
76         }
77
78         float nom = 0.0f, denom = 0.0f;
79
80         // Prior.
81         {
82                 float inv_sigma2 = 1.0f / (prior_sigma * prior_sigma);
83                 nom += PRIOR_WEIGHT * PRIOR_MU * inv_sigma2;
84                 denom += PRIOR_WEIGHT * inv_sigma2;
85         }
86
87         // All matches.
88         for (unsigned i = 0; i < matches.size(); ++i) {
89                 float inv_sigma_c2 = matches[i].weight / (global_sigma * global_sigma);
90                 float x = matches[i].margin; // / 70.0f;
91         
92                 nom += (mu[matches[i].other_player] + x) * inv_sigma_c2;
93                 denom += inv_sigma_c2;
94         }
95         mu[player_num] = nom / denom;
96 }
97
98 void dump_raw(const float *mu, int num_players)
99 {
100         for (unsigned i = 0; i < all_matches.size(); ++i) {
101                 const match& m = all_matches[i];
102
103                 float mu1 = mu[m.player];
104                 float mu2 = mu[m.other_player];
105                 float sigma = global_sigma;
106                 float mu = mu1 - mu2;
107                 float x = m.margin;
108                 float w = m.weight;
109
110                 printf("%f %f\n", (x - mu) / sigma, w);
111         }
112 }
113
114 /*
115  * diff(logL, sigma) = w ( (x - mu)² - sigma² ) / sigma³
116  * maximizer for sigma is given by: sum_i[ (w_i/sigma)³ ((x - mu)² - sigma²) ] = 0
117  *                                   sum_i[ w_i ( (x - mu)² - sigma² ) ] = 0                            |: sigma != 0
118  *                                   sum_i[ w_i (x - mu)² ] = sum[ w_i sigma² ]
119  *                                   sigma = sqrt( sum_i[ w_i (x - mu)² ] / sum[w_i] )
120  */
121 void update_global_sigma(float *mu, int num_players)
122 {
123         float nom = 0.0f, denom = 0.0f;
124         for (unsigned i = 0; i < all_matches.size(); ++i) {
125                 const match& m = all_matches[i];
126
127                 float mu1 = mu[m.player];
128                 float mu2 = mu[m.other_player];
129                 float mu = mu1 - mu2;
130                 float x = m.margin;
131                 float w = m.weight;
132
133                 nom += w * ((x - mu) * (x - mu));
134                 denom += w;
135         }
136
137         global_sigma = sqrt(nom / denom);
138 }
139
140 /*
141  * diff(priorlogL, sigma) = w ( (x - mu)² - sigma² ) / sigma³
142  * maximizer for sigma is given by: sum_i[ (w_i/sigma)³ ((x - mu)² - sigma²) ] = 0
143  *                                   sum_i[ w_i ( (x - mu)² - sigma² ) ] = 0                            |: sigma != 0
144  *                                   sum_i[ w_i (x - mu)² ] = sum[ w_i sigma² ]
145  *                                   sigma = sqrt( sum_i[ w_i (x - mu)² ] / sum[w_i] )
146  */
147 void update_prior_sigma(float *mu, int num_players)
148 {
149         float nom = 0.0f, denom = 0.0f;
150         for (int i = 0; i < num_players; ++i) {
151                 float mu1 = mu[i];
152
153                 nom += ((mu1 - PRIOR_MU) * (mu1 - PRIOR_MU));
154                 denom += 1.0f;
155         }
156
157         prior_sigma = sqrt(nom / denom);
158         if (!(prior_sigma > 40.0f)) {
159                 prior_sigma = 40.0f;
160         }
161 }
162
163 float compute_logl(float z)
164 {
165         return -0.5 * (log(2.0f / M_PI) + z * z);
166 }
167
168 float compute_total_logl(float *mu, int num_players)
169 {
170         float total_logl = 0.0f;
171
172         // Prior.
173         for (int i = 0; i < num_players; ++i) {
174                 total_logl += PRIOR_WEIGHT * compute_logl((mu[i] - PRIOR_MU) / prior_sigma);
175         }
176
177         // Matches.
178         for (unsigned i = 0; i < all_matches.size(); ++i) {
179                 const match& m = all_matches[i];
180
181                 float mu1 = mu[m.player];
182                 float mu2 = mu[m.other_player];
183                 float sigma = global_sigma;
184                 float mu = mu1 - mu2;
185                 float x = m.margin;
186                 float w = m.weight;
187
188                 total_logl += w * compute_logl((x - mu) / sigma);
189         }
190
191         return total_logl;
192 }
193
194 /*
195  * Compute Hessian matrix of the negative log-likelihood, ie. for each term in logL:
196  *
197  * M_ij = D_i D_j (- logL) = -w / sigma²                                for i != j
198  *                            w / sigma²                                for i == j
199  *
200  * Note that this does not depend on mu or the margin at all.
201  */
202 double hessian[MAX_PLAYERS * MAX_PLAYERS];
203 void construct_hessian(const float *mu, int num_players)
204 {
205         memset(hessian, 0, sizeof(hessian));
206
207         for (int i = 0; i < num_players; ++i) {
208                 hessian[i * num_players + i] += 1.0f / (prior_sigma * prior_sigma);
209         }
210         for (unsigned i = 0; i < all_matches.size(); ++i) {
211                 const match &m = all_matches[i];
212
213                 int p1 = m.player;
214                 int p2 = m.other_player;
215
216                 double sigma_sq = global_sigma * global_sigma;
217                 float w = m.weight;
218
219                 hessian[p1 * num_players + p2] -= w / sigma_sq;
220                 hessian[p2 * num_players + p1] -= w / sigma_sq;
221
222                 hessian[p1 * num_players + p1] += w / sigma_sq;
223                 hessian[p2 * num_players + p2] += w / sigma_sq;
224         }
225 }
226
227 // Compute uncertainty (stddev) of mu estimates, which is sqrt((H^-1)_ii),
228 // where H is the Hessian (see construct_hessian()).
229 void compute_mu_uncertainty(const float *mu, int num_players)
230 {
231         Matrix<float, Dynamic, Dynamic> h(num_players, num_players);
232         for (int i = 0; i < num_players; ++i) {
233                 for (int j = 0; j < num_players; ++j) {
234                         h(i, j) = hessian[i * num_players + j];
235                 }
236         }
237
238         // FIXME: Use pseudoinverse if applicable.
239         Matrix<float, Dynamic, Dynamic> ih = h.inverse();
240         for (int i = 0; i < num_players; ++i) {
241                 mu_stddev[i] = sqrt(ih(i, i));
242         }
243 }
244
245 int main(int argc, char **argv)
246 {
247         int num_players;
248         if (scanf("%d", &num_players) != 1) {
249                 fprintf(stderr, "Could't read number of players\n");
250                 exit(1);
251         }
252
253         if (num_players > MAX_PLAYERS) {
254                 fprintf(stderr, "Max %d players supported\n", MAX_PLAYERS);
255                 exit(1);
256         }
257
258         vector<string> players;
259         map<string, int> player_map;
260
261         for (int i = 0; i < num_players; ++i) {
262                 char buf[256];
263                 if (scanf("%s", buf) != 1) {
264                         fprintf(stderr, "Couldn't read player %d\n", i);
265                         exit(1);
266                 }
267
268                 players.push_back(buf);
269                 player_map[buf] = i;
270         }
271
272         int num_matches = 0;
273         for ( ;; ) {
274                 char pl1[256], pl2[256];
275                 int score1, score2;
276                 float weight;
277
278                 if (scanf("%s %s %d %d %f", pl1, pl2, &score1, &score2, &weight) != 5) {
279                         //fprintf(stderr, "Read %d matches.\n", num_matches);
280                         break;
281                 }
282
283                 ++num_matches;
284
285                 if (player_map.count(pl1) == 0) {
286                         fprintf(stderr, "Unknown player '%s'\n", pl1);
287                         exit(1);
288                 }
289                 if (player_map.count(pl2) == 0) {
290                         fprintf(stderr, "Unknown player '%s'\n", pl2);
291                         exit(1);
292                 }
293
294                 match m1;
295                 m1.player = player_map[pl1];
296                 m1.other_player = player_map[pl2];
297                 m1.margin = score1 - score2;
298                 m1.weight = weight;
299                 matches_for_player[player_map[pl1]].push_back(m1);
300
301                 match m2;
302                 m2.player = player_map[pl2];
303                 m2.other_player = player_map[pl1];
304                 m2.margin = score2 - score1;
305                 m2.weight = weight;
306                 matches_for_player[player_map[pl2]].push_back(m2);
307
308                 all_matches.push_back(m1);
309         }
310
311         float mu[MAX_PLAYERS];
312
313         for (int i = 0; i < num_players; ++i) {
314                 mu[i] = PRIOR_MU;
315         }
316
317         for (int j = 0; j < 1000; ++j) {
318                 float old_mu[MAX_PLAYERS];
319                 float old_global_sigma = global_sigma;
320                 float old_prior_sigma = prior_sigma;
321                 memcpy(old_mu, mu, sizeof(mu));
322                 for (int i = 0; i < num_players; ++i) {
323                         update_mu(mu, i, matches_for_player[i]);
324                 }
325                 update_global_sigma(mu, num_players);
326                 update_prior_sigma(mu, num_players);
327                 /* for (int i = 0; i < num_players; ++i) {
328                         update_sigma(mu, sigma, i, matches_for_player[i]);
329                         dump_scores(players, mu, sigma, num_players);
330                 } */
331
332                 float sumdiff = 0.0f;
333                 for (int i = 0; i < num_players; ++i) {
334                         sumdiff += (mu[i] - old_mu[i]) * (mu[i] - old_mu[i]);
335                 }
336                 sumdiff += (prior_sigma - old_prior_sigma) * (prior_sigma - old_prior_sigma);
337                 sumdiff += (global_sigma - old_global_sigma) * (global_sigma - old_global_sigma);
338                 if (sumdiff < EPSILON) {
339                         //fprintf(stderr, "Converged after %d iterations. Stopping.\n", j);
340                         printf("%d 0 -1\n", j + 1);
341                         break;
342                 }
343         }
344
345 #if DUMP_RAW
346         dump_raw(mu, num_players);
347 #else
348         construct_hessian(mu, num_players);
349         compute_mu_uncertainty(mu, num_players);
350         dump_scores(players, mu, mu_stddev, num_players);
351         //fprintf(stderr, "Optimal sigma: %f (two-player: %f)\n", sigma[0], sigma[0] * sqrt(2.0f));
352         printf("%f 0 -2\n", global_sigma / sqrt(2.0f));
353         printf("%f 0 -3\n", prior_sigma);
354
355         float total_logl = compute_total_logl(mu, num_players);
356         printf("%f 0 -4\n", total_logl);
357 #endif
358 }