-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
search_graph.cc
402 lines (344 loc) · 13.6 KB
/
search_graph.cc
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include "search_graph.h"
#include "vw.h"
#include "gd.h"
#include "vw_exception.h"
using namespace std;
/*
example format:
ALL NODES
ALL EDGES
<blank>
ALL NODES
ALL EDGES
<blank>
and so on
node lines look like normal vw examples with unary features:
label:weight |n features
label:weight |n features
...
they are *implicitly* labeled starting at 1. (note the namespace
needn't be called n.) if weight is omitted it is assumed to be 1.0.
edge lines look like:
n1 n2 n3 ... |e features
n1 n2 n3 ... |e features
...
here, n1 n2 n3 are integer node ids, starting at one. technically
these are hyperedges, since they can touch more than two nodes. in the
canonical representation, there will just be n1 and n2.
the only thing that differentiates edges from nodes is that edges have
>1 input.
edges can either be directed or undirected. the default is undirected,
in which case the order of nodes listed in the edge is irrelevant. if
you add --search_graph_directed then the edges will be interpreted as
directed edges. for simple edges that connect two nodes, such as "n1
n2 | ...", the direction will be n1-->n2. for hyperedges of size K
such as "n1 n2 n3 n4 | ...", the default assumption is that the edge
has K-1 sources and 1 sink, so {n1,n2,n3}-->n4 in this case. if you
desire hyper-edges with more than one sink, you can specify them by
separating the source nodes from the sink nodes with a "0". for
instance "n1 n2 n3 0 n4 | ..." is the same as "n1 n2 n3 n4 | ...", but
"n1 n2 0 n3 n4 | ..." means {n1,n2}-->{n3,n4}. in undirected mode, all
0s are ignored; in directed mode, all but the first are ignored.
*/
namespace GraphTask
{
Search::search_task task = { "graph", run, initialize, finish, setup, takedown };
struct task_data
{ // global data
size_t num_loops;
size_t K; // number of labels, *NOT* including the +1 for 'unlabeled'
size_t numN; // number of neighbor predictions (equals K+1 for undirected, or 2*(K+1) for directed)
bool use_structure;
bool separate_learners;
bool directed;
// for adding new features
uint64_t mask; // all->reg.weight_mask
uint64_t multiplier; // all.wpp << all.stride_shift
size_t ss; // stride_shift
size_t wpp;
// per-example data
uint32_t N; // number of nodes
uint32_t E; // number of edges
vector< vector<size_t> > adj; // adj[n] is a vector of *edge example ids* that contain n
vector<uint32_t> bfs; // order of nodes to process
vector<size_t> pred; // predictions
example*cur_node; // pointer to the current node for add_edge_features_fn
float* neighbor_predictions; // prediction on this neighbor for add_edge_features_fn
uint32_t* confusion_matrix;
float* true_counts;
float true_counts_total;
};
inline bool example_is_test(polylabel&l) { return l.cs.costs.size() == 0; }
void initialize(Search::search& sch, size_t& num_actions, po::variables_map& vm)
{ task_data * D = new task_data();
po::options_description sspan_opts("search graphtask options");
sspan_opts.add_options()("search_graph_num_loops", po::value<size_t>(), "how many loops to run [def: 2]");
sspan_opts.add_options()("search_graph_no_structure", "turn off edge features");
sspan_opts.add_options()("search_graph_separate_learners", "use a different learner for each pass");
sspan_opts.add_options()("search_graph_directed", "construct features based on directed graph semantics");
sch.add_program_options(vm, sspan_opts);
D->num_loops = 2;
D->use_structure = true;
D->directed = false;
if (vm.count("search_graph_num_loops")) D->num_loops = vm["search_graph_num_loops"].as<size_t>();
if (vm.count("search_graph_no_structure")) D->use_structure = false;
if (vm.count("search_graph_separate_learners")) D->separate_learners = true;
if (vm.count("search_graph_directed")) D->directed = true;
if (D->num_loops <= 1) { D->num_loops = 1; D->separate_learners = false; }
D->K = num_actions;
D->numN = (D->directed+1) * (D->K+1);
cerr << "K=" << D->K << ", numN=" << D->numN << endl;
D->neighbor_predictions = calloc_or_throw<float>(D->numN);
D->confusion_matrix = calloc_or_throw<uint32_t>( (D->K+1)*(D->K+1) );
D->true_counts = calloc_or_throw<float>(D->K+1);
D->true_counts_total = (float)(D->K+1);
for (size_t k=0; k<=D->K; k++) D->true_counts[k] = 1.;
if (D->separate_learners) sch.set_num_learners(D->num_loops);
sch.set_task_data<task_data>(D);
sch.set_options( 0 ); // Search::AUTO_HAMMING_LOSS
sch.set_label_parser( COST_SENSITIVE::cs_label, example_is_test );
}
void finish(Search::search& sch)
{ task_data * D = sch.get_task_data<task_data>();
free(D->neighbor_predictions);
free(D->confusion_matrix);
free(D->true_counts);
delete D;
}
inline bool example_is_edge(example*e) { return e->l.cs.costs.size() > 1; }
void run_bfs(task_data &D, vector<example*>& ec)
{ D.bfs.clear();
vector<bool> touched;
for (size_t n=0; n<D.N; n++) touched.push_back(false);
touched[0] = true;
D.bfs.push_back(0);
size_t i = 0;
while (D.bfs.size() < D.N)
{ while (i < D.bfs.size())
{ uint32_t n = D.bfs[i];
for (size_t id : D.adj[n])
for (size_t j=0; j<ec[id]->l.cs.costs.size(); j++)
{ uint32_t m = ec[id]->l.cs.costs[j].class_index;
if ((m > 0) && (!touched[m-1]))
{ D.bfs.push_back(m-1);
touched[m-1] = true;
}
}
i++;
}
if (D.bfs.size() < D.N)
// we finished a SCC, need to find another
for (uint32_t n=0; n<D.N; n++)
if (! touched[n])
{ touched[n] = true;
D.bfs.push_back(n);
break;
}
}
}
void setup(Search::search& sch, vector<example*>& ec)
{
task_data& D = *sch.get_task_data<task_data>();
D.multiplier = D.wpp << D.ss;
D.wpp = sch.get_vw_pointer_unsafe().wpp;
D.mask = sch.get_vw_pointer_unsafe().weights.mask();
D.ss = sch.get_vw_pointer_unsafe().weights.stride_shift();
D.N = 0;
D.E = 0;
for (size_t i=0; i<ec.size(); i++)
if (example_is_edge(ec[i]))
D.E++;
else // it's a node!
{ if (D.E > 0)
THROW("error: got a node after getting edges!");
D.N++;
if (ec[i]->l.cs.costs.size() > 0)
{ D.true_counts[ec[i]->l.cs.costs[0].class_index] += 1.;
D.true_counts_total += 1.;
}
}
if ((D.N == 0) && (D.E > 0))
THROW("error: got edges without any nodes (perhaps ring_size is too small?)!");
D.adj = vector<vector<size_t>>(D.N, vector<size_t>(0));
for (size_t i=D.N; i<ec.size(); i++)
{ for (size_t n=0; n<ec[i]->l.cs.costs.size(); n++)
{ if (ec[i]->l.cs.costs[n].class_index > D.N)
THROW("error: edge source points to too large of a node id: " << (ec[i]->l.cs.costs[n].class_index) << " > " << D.N);
}
for (size_t n=0; n<ec[i]->l.cs.costs.size(); n++)
{ size_t nn = ec[i]->l.cs.costs[n].class_index;
if ((nn > 0) && (((D.adj[nn-1].size() == 0) || (D.adj[nn-1][D.adj[nn-1].size()-1] != i)))) // don't allow dups
D.adj[nn-1].push_back(i);
}
}
run_bfs(D, ec);
D.pred.clear();
for (size_t n=0; n<D.N; n++)
D.pred.push_back( D.K+1 );
}
void takedown(Search::search& sch, vector<example*>& /*ec*/)
{ task_data& D = *sch.get_task_data<task_data>();
D.bfs.clear();
D.pred.clear();
for (auto x : D.adj) x.clear();
D.adj.clear();
}
void add_edge_features_group_fn(task_data&D, float fv, uint64_t fx)
{ example*node = D.cur_node;
uint64_t fx2 = fx / (uint64_t)D.multiplier;
for (size_t k=0; k<D.numN; k++)
{ if (D.neighbor_predictions[k] == 0.) continue;
node->feature_space[neighbor_namespace].push_back(fv * D.neighbor_predictions[k], (uint64_t)(( fx2 + 348919043 * k ) * D.multiplier) & (uint64_t)D.mask);
}
}
void add_edge_features_single_fn(task_data&D, float fv, uint64_t fx)
{ example*node = D.cur_node;
features& fs = node->feature_space[neighbor_namespace];
uint64_t fx2 = fx / (uint64_t)D.multiplier;
size_t k = (size_t) D.neighbor_predictions[0];
fs.push_back(fv, (uint32_t)(( fx2 + 348919043 * k ) * D.multiplier) & (uint64_t)D.mask);
}
void add_edge_features(Search::search&sch, task_data&D, size_t n, vector<example*>&ec)
{ D.cur_node = ec[n];
for (size_t i : D.adj[n])
{ for (size_t k=0; k<D.numN; k++) D.neighbor_predictions[k] = 0.;
float pred_total = 0.;
uint32_t last_pred = 0;
if (D.use_structure)
{ bool n_in_sink = true;
if (D.directed)
for (size_t j=0; j<ec[i]->l.cs.costs.size()-1; j++)
{ size_t m = ec[i]->l.cs.costs[j].class_index;
if (m == 0) break;
if (m-1 == n) { n_in_sink = false; break; }
}
bool m_in_sink = false;
for (size_t j=0; j<ec[i]->l.cs.costs.size(); j++)
{ size_t m = ec[i]->l.cs.costs[j].class_index;
if (m == 0) { m_in_sink = true; continue; }
if (j == ec[i]->l.cs.costs.size()-1) m_in_sink = true;
m--;
if (m == n) continue;
size_t other_side = (D.directed && (n_in_sink != m_in_sink)) ? (D.K+1) : 0;
D.neighbor_predictions[ D.pred[m]-1 + other_side ] += 1.;
pred_total += 1.;
last_pred = (uint32_t)D.pred[m]-1 + (uint32_t)other_side;
}
}
else
{ D.neighbor_predictions[0] += 1.;
pred_total += 1.;
last_pred = 0;
}
if (pred_total == 0.) continue;
//cerr << n << ':' << i << " -> ["; for (size_t k=0; k<D.numN; k++) cerr << ' ' << D.neighbor_predictions[k]; cerr << " ]" << endl;
for (size_t k=0; k<D.numN; k++) D.neighbor_predictions[k] /= pred_total;
example&edge = *ec[i];
if (pred_total <= 1.) // single edge
{ D.neighbor_predictions[0] = (float)last_pred;
GD::foreach_feature<task_data,uint64_t,add_edge_features_single_fn>(sch.get_vw_pointer_unsafe(), edge, D);
}
else // lots of edges
GD::foreach_feature<task_data,uint64_t,add_edge_features_group_fn>(sch.get_vw_pointer_unsafe(), edge, D);
}
ec[n]->indices.push_back(neighbor_namespace);
ec[n]->total_sum_feat_sq += ec[n]->feature_space[neighbor_namespace].sum_feat_sq;
ec[n]->num_features += ec[n]->feature_space[neighbor_namespace].size();
vw& all = sch.get_vw_pointer_unsafe();
for (string& i : all.pairs)
{ int i0 = (int)i[0];
int i1 = (int)i[1];
if ((i0 == (int)neighbor_namespace) || (i1 == (int)neighbor_namespace))
{ ec[n]->num_features += ec[n]->feature_space[i0].size() * ec[n]->feature_space[i1].size();
ec[n]->total_sum_feat_sq += ec[n]->feature_space[i0].sum_feat_sq*ec[n]->feature_space[i1].sum_feat_sq;
}
}
}
void del_edge_features(task_data&/*D*/, uint32_t n, vector<example*>&ec)
{ ec[n]->indices.pop();
features& fs = ec[n]->feature_space[neighbor_namespace];
ec[n]->total_sum_feat_sq -= fs.sum_feat_sq;
ec[n]->num_features -= fs.size();
fs.erase();
}
#define IDX(i,j) ( (i) * (D.K+1) + j )
float macro_f(task_data& D)
{ float total_f1 = 0.;
float count_f1 = 0.;
for (size_t k=1; k<=D.K; k++)
{ float trueC = 0.;
float predC = 0.;
for (size_t j=1; j<=D.K; j++)
{ trueC += (float)D.confusion_matrix[ IDX(k,j) ];
predC += (float)D.confusion_matrix[ IDX(j,k) ];
}
if (trueC == 0) continue;
float correctC = (float)D.confusion_matrix[ IDX(k,k) ];
count_f1++;
if (correctC > 0)
{ float pre = correctC / predC;
float rec = correctC / trueC;
total_f1 += 2 * pre * rec / (pre + rec);
}
}
return total_f1 / count_f1;
}
void run(Search::search& sch, vector<example*>& ec)
{ task_data& D = *sch.get_task_data<task_data>();
float loss_val = 0.5f / (float)D.num_loops;
for (size_t n=0; n<D.N; n++) D.pred[n] = D.K+1;
for (size_t loop=0; loop<D.num_loops; loop++)
{ bool last_loop = loop == (D.num_loops-1);
int start = 0; int end = D.N; int step = 1;
if (loop % 2 == 1) { start = D.N-1; end=-1; step = -1; } // go inward on odd loops
for (int n_id = start; n_id != end; n_id += step)
{ uint32_t n = D.bfs[n_id];
uint32_t k = (ec[n]->l.cs.costs.size() > 0) ? ec[n]->l.cs.costs[0].class_index : 0;
bool add_features = /* D.use_structure && */ sch.predictNeedsExample();
//add_features = false;
if (add_features) add_edge_features(sch, D, n, ec);
Search::predictor P = Search::predictor(sch, n+1);
P.set_input(*ec[n]);
if (false && (k > 0))
{ float min_count = 1e12f;
for (size_t k2=1; k2<=D.K; k2++)
min_count = min(min_count, D.true_counts[k2]);
float w = min_count / D.true_counts[k];
//float w = D.true_counts_total / D.true_counts[k] / (float)(D.K);
P.set_weight( w );
//cerr << "w = " << D.true_counts_total / D.true_counts[k] / (float)(D.K) << endl;
//P.set_weight( D.true_counts_total / D.true_counts[k] / (float)(D.K) );
}
if (D.separate_learners) P.set_learner_id(loop);
if (k > 0) // for test examples
P.set_oracle(k);
// add all the conditioning
for (size_t i=0; i<D.adj[n].size(); i++)
{ for (size_t j=0; j<ec[i]->l.cs.costs.size(); j++)
{ uint32_t m = ec[i]->l.cs.costs[j].class_index;
if (m == 0) continue;
m--;
if (m == n) continue;
P.add_condition(m+1, 'e');
}
}
// make the prediction
D.pred[n] = P.predict();
if (ec[n]->l.cs.costs.size() > 0) // for test examples
sch.loss((ec[n]->l.cs.costs[0].class_index == D.pred[n]) ? 0.f : (last_loop ? 0.5f : loss_val));
if (add_features) del_edge_features(D, n, ec);
}
}
for (uint32_t n=0; n<D.N; n++)
D.confusion_matrix[ IDX( ec[n]->l.cs.costs[0].class_index, D.pred[n] ) ] ++;
sch.loss( 1.f - macro_f(D) );
if (sch.output().good())
for (uint32_t n=0; n<D.N; n++)
sch.output() << D.pred[n] << ' ';
}
}