]> git.sesse.net Git - wloh/blob - bayeswf.cpp
Compute the Hessian instead of the Fisher information matrix. The numerics here suck.
[wloh] / bayeswf.cpp
1 #include <stdio.h>
2 #include <math.h>
3 #include <string.h>
4 #include <stdlib.h>
5
6 #include <map>
7 #include <vector>
8 #include <string>
9 #include <algorithm>
10
11 using namespace std;
12
13 #define MAX_PLAYERS 4096
14
15 float mu[MAX_PLAYERS];
16 float sigma[MAX_PLAYERS];
17
18 #define EPSILON 1e-3
19
20 /*
21  * L(mu_vec, sigma_vec, matches) = product[ L(mu_A, sigma_A, mu_B, sigma_B, score_AB - score_BA) ]
22  * log-likelihood = sum[ log( L(mu_A, sigma_A, mu_B, sigma_B, score_AB - score_BA) ) ]
23  * 
24  * L(mu1, sigma1, mu2, sigma2, score2 - score1) = sigmoid(mu2 - mu1, sqrt(sigma1² + sigma2²), (score2 - score1))
25  *
26  * pdf := 1/(sigma * sqrt(2*Pi)) * exp(-(x - mu)^2 / (2 * sigma^2));        
27  * pdfs := subs({ mu = mu1 - mu2, sigma = sqrt(sigma1^2 + sigma2^2) }, pdf);
28  * diff(log(pdfs), mu1); 
29  */
30
31 struct match {
32         int other_player;
33         int margin;
34         float weight;
35 };
36 map<int, vector<match> > matches_for_player;
37
38 void dump_scores(const vector<string> &players, const float *mu, const float *sigma, int num_players)
39 {
40 #if 0
41         for (int i = 0; i < num_players; ++i) {
42                 printf("%s=[%5.1f, %4.1f] ", players[i].c_str(), mu[i], sigma[i]);
43         }
44         printf("\n");
45 #elif 0
46         for (int i = 0; i < num_players; ++i) {
47                 printf("%5.1f ", mu[i]);
48         }
49         printf("\n");
50 #else
51         for (int i = 0; i < num_players; ++i) {
52                 printf("%5.1f %s\n", mu[i], players[i].c_str());
53         }
54         printf("\n");
55 #endif
56 }
57
58 /*
59  * diff(logL, mu1) = -w * (mu1 - mu2 - x) / sigma_c^2
60  * maximizer for mu1 is given by: sum_i[ (w_i/sigma_c_i)^2 (mu1 - mu2_i - x_i) ] = 0
61  *                                sum_i[ (w_i/sigma_c_i)^2 mu1 ] = sum_i [ (w_i/sigma_c_i)^2 ( mu2_i + x_i ) ]
62  *                                mu1 = sum_i [ (w_i/sigma_c_i)^2 ( mu2_i + x_i ) ] / sum_i[ (w_i/sigma_c_i)^2 ]
63  */
64 void update_mu(float *mu, float *sigma, int player_num, const vector<match> &matches)
65 {
66         if (matches.empty()) {
67                 return;
68         }
69
70         float nom = 0.0f, denom = 0.0f;
71         for (unsigned i = 0; i < matches.size(); ++i) {
72                 float sigma1 = sigma[player_num];
73                 float sigma2 = sigma[matches[i].other_player];
74                 float inv_sigma_c2 = matches[i].weight / (sigma1 * sigma1 + sigma2 * sigma2);
75                 float x = matches[i].margin; // / 70.0f;
76         
77                 nom += (mu[matches[i].other_player] + x) * inv_sigma_c2;
78                 denom += inv_sigma_c2;
79         }
80         mu[player_num] = nom / denom;
81 }
82
83 /*
84  * diff(logL, sigma1) = sigma1 (-sigma1² - sigma2² + (x - mu)²) / sigma_c²
85  * maximizer for sigma1 is given by: sum_i[ (1/sigma_c_i)² sigma1 ((x - mu)² - (sigma1² + sigma2²) ] = 0
86  *                                   sum_i[ (x - mu)² - sigma1² - sigma2² ] = 0                                  |: sigma1 != 0, sigma2 != 0
87  *                                   sum_i[ (x - mu)² - sigma2² ] = sum[ sigma1² ]
88  *                                   sigma1 = sqrt( sum_i[ (x - mu)² - sigma2² ] / N )
89  */
90 void update_sigma(float *mu, float *sigma, int player_num, const vector<match> &matches)
91 {
92         if (matches.size() < 2) {
93                 return;
94         }
95
96         float sum = 0.0f;
97         for (unsigned i = 0; i < matches.size(); ++i) {
98                 float mu1 = mu[player_num];
99                 float mu2 = mu[matches[i].other_player];
100                 float mu = mu1 - mu2;
101                 float sigma2 = sigma[matches[i].other_player];
102                 float x = matches[i].margin;
103
104                 //fprintf(stderr, "x=%f mu=%f sigma2=%f   add %f-%f = %f\n", x, mu, sigma2, (x-mu)*(x-mu), sigma2*sigma2, (x - mu) * (x - mu) - sigma2 * sigma2);
105                 sum += (x - mu) * (x - mu) - sigma2 * sigma2;
106         }
107
108         if (sum <= 0) {
109                 return;
110         }
111         //fprintf(stderr, "sum=%f\n", sum);
112         sigma[player_num] = sqrt(sum / matches.size());
113 }
114
115 /*
116  * diff(logL, sigma) = w ( (x - mu)² - sigma² ) / sigma³
117  * maximizer for sigma is given by: sum_i[ (w_i/sigma)³ ((x - mu)² - sigma²) ] = 0
118  *                                   sum_i[ w_i ( (x - mu)² - sigma² ) ] = 0                            |: sigma != 0
119  *                                   sum_i[ w_i (x - mu)² ] = sum[ w_i sigma² ]
120  *                                   sigma = sqrt( sum_i[ w_i (x - mu)² ] / sum[w_i] )
121  */
122 void update_global_sigma(float *mu, float *sigma, int num_players)
123 {
124         float nom = 0.0f, denom = 0.0f;
125         for (int i = 0; i < num_players; ++i) {
126                 for (unsigned j = 0; j < matches_for_player[i].size(); ++j) {
127                         const match& m = matches_for_player[i][j];
128
129                         // Only count each match once.
130                         if (m.other_player <= i) {
131                                 continue;
132                         }
133
134                         float mu1 = mu[i];
135                         float mu2 = mu[m.other_player];
136                         float mu = mu1 - mu2;
137                         float x = m.margin;
138                         float w = m.weight;
139
140                         nom += w * ((x - mu) * (x - mu));
141                         denom += w;
142                 }
143         }
144
145         float best_sigma = sqrt(nom / denom) / sqrt(2.0f);  // Divide evenly between the two players.
146         for (int i = 0; i < num_players; ++i) {
147                 sigma[i] = best_sigma;
148         }
149 }
150
151 void renormalize(float *mu, float *sigma, int num_players)
152 {
153         float avg = 0.0f;
154         for (int i = 0; i < num_players; ++i) {
155                 avg += mu[i];
156         }
157         float corr = 1500.0f - avg / num_players;
158         for (int i = 0; i < num_players; ++i) {
159                 mu[i] += corr;
160         }
161 }
162
163 /*
164  * Compute Hessian matrix of the negative log-likelihood, ie. for each term in logL:
165  *
166  * M_ij = D_i D_j (- logL) = -1 / sigma²                                for i != j
167  *                            1 / sigma²                                for i == j
168  *
169  * Note that this does not depend on mu or the margin at all.
170  */
171 double hessian[MAX_PLAYERS][MAX_PLAYERS];
172 void construct_hessian(const float *mu, const float *sigma, int num_players)
173 {
174         memset(hessian, 0, sizeof(hessian));
175
176         for (int i = 0; i < num_players; ++i) {
177                 double sigma1 = sigma[i];
178
179                 for (unsigned k = 0; k < matches_for_player[i].size(); ++k) {
180                         int j = matches_for_player[i][k].other_player;
181
182                         double sigma2 = sigma[j];
183                         double sigma_sq = sigma1 * sigma1 + sigma2 * sigma2;
184
185                         hessian[i][j] -= 1.0f / sigma_sq;
186                         hessian[i][i] += 1.0f / sigma_sq;
187                 }
188         }
189
190         for (int i = 0; i < num_players; ++i) {
191                 for (int j = 0; j < num_players; ++j) {
192                         printf("%.12f ", hessian[i][j]);
193                 }
194                 printf("\n");
195         }
196 }
197
198 int main(int argc, char **argv)
199 {
200         int num_players;
201         if (scanf("%d", &num_players) != 1) {
202                 fprintf(stderr, "Could't read number of players\n");
203                 exit(1);
204         }
205
206         if (num_players > MAX_PLAYERS) {
207                 fprintf(stderr, "Max %d players supported\n", MAX_PLAYERS);
208                 exit(1);
209         }
210
211         vector<string> players;
212         map<string, int> player_map;
213
214         for (int i = 0; i < num_players; ++i) {
215                 char buf[256];
216                 if (scanf("%s", buf) != 1) {
217                         fprintf(stderr, "Couldn't read player %d\n", i);
218                         exit(1);
219                 }
220
221                 players.push_back(buf);
222                 player_map[buf] = i;
223         }
224
225         int num_matches = 0;
226         for ( ;; ) {
227                 char pl1[256], pl2[256];
228                 int score1, score2;
229                 float weight;
230
231                 if (scanf("%s %s %d %d %f", pl1, pl2, &score1, &score2, &weight) != 5) {
232                         fprintf(stderr, "Read %d matches.\n", num_matches);
233                         break;
234                 }
235
236                 ++num_matches;
237
238                 if (player_map.count(pl1) == 0) {
239                         fprintf(stderr, "Unknown player '%s'\n", pl1);
240                         exit(1);
241                 }
242                 if (player_map.count(pl2) == 0) {
243                         fprintf(stderr, "Unknown player '%s'\n", pl2);
244                         exit(1);
245                 }
246
247                 match m1;
248                 m1.other_player = player_map[pl2];
249                 m1.margin = score1 - score2;
250                 m1.weight = weight;
251                 matches_for_player[player_map[pl1]].push_back(m1);
252
253                 match m2;
254                 m2.other_player = player_map[pl1];
255                 m2.margin = score2 - score1;
256                 m2.weight = weight;
257                 matches_for_player[player_map[pl2]].push_back(m2);
258         }
259
260         float mu[MAX_PLAYERS];
261         float sigma[MAX_PLAYERS];
262
263         for (int i = 0; i < num_players; ++i) {
264                 mu[i] = 1500.0f;
265                 sigma[i] = 70.0f / sqrt(2.0f);
266         }
267         renormalize(mu, sigma, num_players);
268
269         for (int j = 0; j < 1000; ++j) {
270                 float old_mu[MAX_PLAYERS];
271                 float old_sigma[MAX_PLAYERS];
272                 memcpy(old_mu, mu, sizeof(mu));
273                 memcpy(old_sigma, sigma, sizeof(sigma));
274                 for (int i = 0; i < num_players; ++i) {
275                         update_mu(mu, sigma, i, matches_for_player[i]);
276                         renormalize(mu, sigma, num_players);
277                 }
278                 update_global_sigma(mu, sigma, num_players);
279                 /* for (int i = 0; i < num_players; ++i) {
280                         update_sigma(mu, sigma, i, matches_for_player[i]);
281                         dump_scores(players, mu, sigma, num_players);
282                 } */
283
284                 float sumdiff = 0.0f;
285                 for (int i = 0; i < num_players; ++i) {
286                         sumdiff += (mu[i] - old_mu[i]) * (mu[i] - old_mu[i]);
287                         sumdiff += (sigma[i] - old_sigma[i]) * (sigma[i] - old_sigma[i]);
288                 }
289                 if (sumdiff < EPSILON) {
290                         fprintf(stderr, "Converged after %d iterations. Stopping.\n", j);
291                         break;
292                 }
293         }
294         dump_scores(players, mu, sigma, num_players);
295         fprintf(stderr, "Optimal sigma: %f (two-player: %f)\n", sigma[0], sigma[0] * sqrt(2.0f));
296
297         construct_hessian(mu, sigma, num_players);
298 }