-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgen_insights.cc
More file actions
254 lines (223 loc) · 9.14 KB
/
gen_insights.cc
File metadata and controls
254 lines (223 loc) · 9.14 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
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
/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry "Dima" Korolev <dmitry.korolev@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/
#include <cmath>
#include <map>
#include <set>
#include "insights.h"
CEREAL_REGISTER_TYPE(insight::MutualInformation);
#include "../Current/Bricks/dflags/dflags.h"
#include "../Current/Bricks/file/file.h"
#include "../Current/Bricks/strings/util.h"
using bricks::FileSystem;
using namespace bricks::strings;
DEFINE_string(input, "data/insights_input.json", "");
DEFINE_string(output, "data/insights.json", "");
DEFINE_double(prior, 2.5, "Consider under three events noise.");
DEFINE_double(gain_threshold,
0.0, // No real lower bound, just statistically significant above the noise level.
"Threshold on delta entropy in mutual information vs. individual information.");
DEFINE_bool(dump, false, "");
typedef long double DOUBLE;
const DOUBLE EPS = 1e-8;
const DOUBLE BITS = std::log(DOUBLE(0.5)); // Represent entropy in bits.
DOUBLE entropy(DOUBLE p) {
assert(p >= 0.0 && p <= 1.0 + EPS);
if (p > EPS && p < 1.0) {
return p * std::log(p);
} else {
return 0;
}
}
DOUBLE bits(size_t n, size_t c1, size_t c2) {
assert(n > 0);
assert(c1 <= n);
assert(c2 <= n);
assert(c1 + c2 == n);
const DOUBLE p = FLAGS_prior;
const DOUBLE k = DOUBLE(1) / (p * 2 + n);
return (entropy(k * (p + c1)) + entropy(k * (p + c2))) * BITS * n;
}
DOUBLE bits(size_t n, size_t c1, size_t c2, size_t c3, size_t c4) {
assert(n > 0);
assert(c1 <= n);
assert(c2 <= n);
assert(c3 <= n);
assert(c4 <= n);
assert(c1 + c2 + c3 + c4 == n);
const DOUBLE p = FLAGS_prior;
const DOUBLE k = DOUBLE(1) / (p * 4 + n);
return (entropy(k * (p + c1)) + entropy(k * (p + c2)) + entropy(k * (p + c3)) + entropy(k * (p + c4))) *
BITS * n;
}
int main(int argc, char** argv) {
ParseDFlags(&argc, &argv);
fprintf(stderr, "Reading '%s' ...", FLAGS_input.c_str());
fflush(stderr);
const auto input = ParseJSON<InsightsInput>(FileSystem::ReadFileAsString(FLAGS_input));
fprintf(stderr, "\b\b\b: Done, %d realm(s).\n", static_cast<int>(input.realm.size()));
InsightsOutput output;
// TODO(dkorolev): This will change with more than one realm.
assert(input.realm.size() == 1u);
output.tag = input.realm[0].tag;
output.feature = input.realm[0].feature;
for (const auto& realm : input.realm) {
const auto& S = realm.session;
const size_t N = S.size();
fprintf(stderr, "Realm '%s', %d sessions ...", realm.description.c_str(), static_cast<int>(N));
fflush(stderr);
// Build indexes and reverse indexes for features and tags.
std::vector<std::string> tag;
std::unordered_map<std::string, size_t> tag_index;
std::vector<std::string> feature;
std::unordered_map<std::string, size_t> feature_index;
for (const auto& cit : realm.tag) {
tag_index[cit.first];
}
for (auto& it : tag_index) {
it.second = tag.size();
tag.push_back(it.first);
}
for (const auto& cit : realm.feature) {
feature_index[cit.first];
}
for (auto& it : feature_index) {
it.second = feature.size();
feature.push_back(it.first);
}
const size_t T = tag.size();
const size_t F = feature.size();
fprintf(stderr, "\b\b\b\b, %d tags, %d features ...", static_cast<int>(T), static_cast<int>(F));
fflush(stderr);
// Compute counters and entropies.
std::vector<size_t> C(F, 0u);
// Efficiently pack in memory { F * F * 4 } size_t's.
std::vector<size_t> CC_storage(F * F * 4, 0u);
std::vector<std::vector<size_t*>> CC(F, std::vector<size_t*>(F)); // [i][j] -> { --, -+, +-, ++ }.
{
size_t* ptr = &CC_storage[0];
for (size_t i = 0; i < F; ++i) {
for (size_t j = 0; j < F; ++j) {
CC[i][j] = ptr;
ptr += 4;
}
}
assert(ptr == &CC_storage[0] + (F * F * 4));
}
{
// Last session index that had this feature set. Start from infinity.
std::vector<size_t> q(F);
memset(&q[0], 0xff, F * sizeof(size_t));
for (size_t sid = 0; sid < N; ++sid) {
for (const auto& f : S[sid].feature) {
const auto cit = feature_index.find(f);
assert(cit != feature_index.end());
assert(cit->second < F);
q[cit->second] = sid;
}
// has(f) -> size_t(1) if feature f is present, and size_t(0) otherwise.
const auto has = [&q, &sid](const size_t f) { return q[f] == sid ? 1u : 0u; };
for (size_t fi = 0; fi < F; ++fi) {
const size_t bi = has(fi);
if (bi) {
// Keep the `+` counter per one feature. The `-` counter is obviously `N - C[f]`.
++C[fi];
}
for (size_t fj = fi + 1; fj < F; ++fj) {
// Keep the { `--`, `-+`, `+-`, `++` } counters for pairs of features.
const size_t bj = has(fj);
const size_t offset = bi * 2 + bj;
++CC[fi][fj][offset];
++CC[fj][fi][offset];
}
}
}
}
// Compute entropies.
std::vector<DOUBLE> E(F);
for (size_t f = 0; f < F; ++f) {
assert(C[f] <= N);
E[f] = bits(N, C[f], N - C[f]);
}
std::vector<std::vector<DOUBLE>> EE(F, std::vector<DOUBLE>(F));
for (size_t fi = 0; fi + 1 < F; ++fi) {
for (size_t fj = fi + 1; fj < F; ++fj) {
const auto& cc = CC[fi][fj];
assert(cc[0] <= N);
assert(cc[1] <= N);
assert(cc[2] <= N);
assert(cc[3] <= N);
assert(cc[0] + cc[1] + cc[2] + cc[3] == N);
EE[fi][fj] = EE[fj][fi] = bits(N, cc[0], cc[1], cc[2], cc[3]);
}
}
fprintf(stderr, "\b\b\b\b, entropy done ...");
for (size_t fi = 0; fi + 1 < F; ++fi) {
for (size_t fj = fi + 1; fj < F; ++fj) {
if (!FLAGS_prior) {
// If prior is zero, gain is always positive.
// For nonzero priors, gain can be negative for low absolute numbers. Which is what we want.
if (!((EE[fi][fj] < E[fi] + E[fj] + EPS))) {
std::cerr << fi << ' ' << fj << ": " << C[fi] << ' ' << C[fj] << ", " << CC[fi][fj][0] << ' '
<< CC[fi][fj][1] << ' ' << CC[fi][fj][2] << ' ' << CC[fi][fj][3] << ": " << E[fi] << ' '
<< E[fj] << ' ' << EE[fi][fj] << std::endl;
}
assert(EE[fi][fj] < E[fi] + E[fj] + EPS);
}
const DOUBLE gain = (E[fi] + E[fj] - EE[fi][fj]);
if (gain > FLAGS_gain_threshold) {
const std::string& si = feature[fi];
const std::string& sj = feature[fj];
const auto mi = realm.feature.find(si);
const auto mj = realm.feature.find(sj);
assert(mi != realm.feature.end());
assert(mj != realm.feature.end());
const std::string& ti = mi->second.tag;
const std::string& tj = mj->second.tag;
// Explicitly disable insights between features of the same tag.
if (ti != tj) {
if (FLAGS_dump) {
std::cout << (E[fi] + E[fj] - EE[fi][fj]) << '\t' << feature[fi] << '\t' << feature[fj]
<< std::endl;
}
auto insight = make_unique<insight::MutualInformation>();
insight->score = gain;
insight->lhs = si;
insight->rhs = sj;
insight->counters = insight::MutualInformation::Counters{
N, C[fi], C[fj], CC[fi][fj][0], CC[fi][fj][1], CC[fi][fj][2], CC[fi][fj][3]};
output.insight.emplace_back(std::move(insight));
}
}
}
}
fprintf(stderr, "\b\b\b\b, done.\n");
fflush(stderr);
}
fprintf(stderr, "Organizing the output ...");
fflush(stderr);
std::sort(output.insight.begin(),
output.insight.end(),
[](const std::unique_ptr<insight::AbstractBase>& lhs,
const std::unique_ptr<insight::AbstractBase>& rhs) { return lhs->score > rhs->score; });
fprintf(stderr, "\b\b\b\b, writing to '%s' ...", FLAGS_output.c_str());
fflush(stderr);
FileSystem::WriteStringToFile(JSON(output, "insights"), FLAGS_output.c_str());
fprintf(stderr, "\b\b\b\b: All done.\n");
}