Debian Codegraph @

doc/bogofilter-tuning.HOWTO.html

raw
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
3 <html>
4 <head>
5 <title>Tuning bogofilter</title>
6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7 </head>
8 <body>
9 <h1>TUNING BOGOFILTER'S ROBINSON-FISHER METHOD -- an updated
10 HOWTO</h1>
11
12 <address>(<a href="mailto:[email protected]">Greg Louis</a>,
13 September 2004)</address>
14
15 <p>NB: Bogotune is a tool (shipped with bogofilter) that automates
16 the tuning process. Its "full search" mode performs a
17 five-dimensional grid search over possible values of the parameters
18 to be described below, and comes up with recommendations for
19 optimal settings. There's also a "partial search" mode that is only
20 three-dimensional. If you have enough spam and nonspam messages (at
21 least 2,500 of each), using bogotune is highly recommended for
22 optimizing bogofilter's accuracy.</p>
23
24 <h2>CONTENTS</h2>
25
26 <ul>
27 <li><a href="#intro">Introduction</a></li>
28
29 <li><a href="#robx">Robinson's x</a></li>
30
31 <li><a href="#robs">Robinson's s</a></li>
32
33 <li><a href="#md">The minimum deviation</a></li>
34
35 <li><a href="#esf">Effective size factors</a></li>
36
37 <li><a href="#co">The spam and nonspam cutoffs</a></li>
38
39 <li><a href="#bogot">Overview of bogotune</a></li>
40
41 <li><a href="#freq">How often to tune</a></li>
42
43 <li><a href="#train">A note on training</a></li>
44 </ul>
45
46 <p><a name="intro"></a></p>
47
48 <h2>INTRODUCTION</h2>
49
50 <p>The bogofilter program has evolved through three classification
51 methods: the original as proposed by Paul Graham and implemented in
52 bogofilter by Eric S. Raymond; a variation proposed by Gary
53 Robinson and implemented in bogofilter by Greg Louis; and a further
54 variation, also proposed by Gary Robinson, which uses Fisher's
55 method <cite>(Fisher, R. A., 1950: Statistical Methods for Research
56 Workers, pp. 99ff.&nbsp; London: Oliver and Boyd)</cite> of
57 combining probabilities; for bogofilter, your author has
58 implemented this one too.&nbsp; Recently, Gary Robinson described a
59 further improvement, the application of effective size factors in
60 the scoring process; this is available by default in bogofilter,
61 but since it's relatively new, an option exists in both bogofilter
62 and bogotune to switch it off.</p>
63
64 <p>Each of Gary Robinson's proposed classification methods works
65 better than the earlier versions.&nbsp; For optimal results, they
66 (and the original) require some tuning.&nbsp; As distributed,
67 bogofilter attempts to supply good starting values for the tunable
68 parameters.&nbsp; Since the optimum values depend on the size and
69 content of the wordlists at <em>your</em> installation, the best
70 results can only be determined by some experimentation using
71 <em>your</em> wordlists.&nbsp; After several thousand each of spam
72 and nonspam messages have been fed to bogofilter for training, this
73 experimentation can be well worthwhile: you may be able to cut the
74 number of spams that are still getting through by more than
75 half.</p>
76
77 <p>The purpose of this document is to explain how to adjust
78 bogofilter's parameters for best spam filtering.&nbsp; A manual
79 tuning process is described; though you'll be wise to use bogotune
80 to help find your parameter values, understanding the manual
81 process will help you make sense of what bogotune does.</p>
82
83 <p>With Robinson's changes as implemented in bogofilter, there are
84 seven (five without effective size factors) things to tune, six (or
85 four) of which are highly interdependent, as explained below:</p>
86
87 <p><a name="robx"></a></p>
88
89 <h2>ROBINSON'S x</h2>
90
91 <p>First off, you should determine the value of x appropriate to
92 your training database.</p>
93
94 <p>The way bogofilter works, summarizing briefly, is that the
95 message being classified is separated into "tokens" -- words, IP
96 addresses and other logical units of information.&nbsp; Each token
97 is looked up in the wordlist that makes up the training
98 database.&nbsp; The number of times it's been seen in a spam
99 message is divided by the total number of times it's been seen, and
100 that gives an indication of the likelihood that the token is in a
101 spam message.&nbsp; The likelihood estimates for all the tokens are
102 combined to give a score between 0 and 1 -- 0 means the message is
103 not likely to be a spam, 1 means it is.&nbsp; That's fine, but what
104 happens if a token's never been seen before? That's where x comes
105 in: it's a "first guess" at what the presence of an unknown token
106 means, in terms of its contribution to the score.&nbsp; It's the
107 value used as the likelihood estimate when a new token is
108 found.</p>
109
110 <p>Obtaining a value for x is easy: bogoutil will calculate it for
111 you.</p>
112
113 <p>Assuming your bogofilter wordlist is in ~/.bogofilter, run</p>
114
115 <div style="margin-left: 2em">
116 <pre>
117 bogoutil -r
118 </pre>
119 </div>
120
121 <p>This will print out an x value. If it's in the range of 0.4 to
122 0.6, you can run&nbsp;
123 <code>bogoutil&nbsp;-R&nbsp;~/.bogofilter</code>&nbsp; to install
124 the calculated value so bogofilter will use it from then on.</p>
125
126 <p>The value of x that bogoutil calculates is just the average
127 of</p>
128
129 <div style="margin-left: 2em">
130 <pre>
131 p(w) = badcount / (goodcount + badcount)
132 </pre>
133 </div>
134
135 <p>for every word in your training set that appears at least 10
136 times in spam and/or ham counts in your wordlist (i.e.
137 badcount&nbsp;+&nbsp;goodcount&nbsp;&gt;=&nbsp;10).</p>
138
139 <p>To be honest, that's an oversimplification, for the sake of
140 explaining the basic concept clearly.&nbsp; In real life, you have
141 to scale the counts somehow.&nbsp; If you had exactly the same
142 number of spam and nonspam messages contributing to your wordlist,
143 the formula for p(w) given above would be ok; but we actually have
144 to use</p>
145
146 <div style="margin-left: 2em">
147 <pre>
148 p(w) = (badcount / badlist_msgcount) /
149 (badcount / badlist_msgcount + goodcount / goodlist_msgcount)
150 </pre>
151 </div>
152
153 <p>where badlist_msgcount is the number of spam messages that were
154 fed into the training set, and goodlist_msgcount is the number of
155 nonspams used in training.</p>
156
157 <p>An equivalent way of calculating x, that's a little easier to
158 read, is:</p>
159
160 <div style="margin-left: 2em">
161 <pre>
162 scalefactor = badlist_msgcount / goodlist_msgcount
163 p(w) = badcount / (badcount + goodcount * scalefactor)
164 </pre>
165 </div>
166
167 <p>In either case, x is the average of those p(w) values.</p>
168
169 <p>The calculated x is just a first guess, and it may be worth
170 while experimenting (after tuning s and the minimum deviation as
171 described below) to see what happens if you adjust it up or
172 downward within a range of about 0.1 either way. <a name=
173 "robs"></a></p>
174
175 <h2>ROBINSON'S s</h2>
176
177 <p>With a count of zero for a given token, we have only x to go on,
178 so that's what we use as the likelihood estimate for that
179 token.&nbsp; The question then arises, what if we have seen the
180 token before, but only a few times? Statistical variation will
181 result in the ratio of two small numbers being rather unreliable,
182 so perhaps we ought to compromise between that ratio and our "first
183 guess" value.&nbsp; This is what the Robinson method does.</p>
184
185 <p>The compromise works like this: a parameter s is defined, that
186 serves as a weighting factor; the larger the value of s, the more
187 importance is given to x in the presence of low token counts.&nbsp;
188 The token count is&nbsp;
189 <code>n&nbsp;=&nbsp;badcount&nbsp;+&nbsp;goodcount</code>&nbsp; and
190 the p(w) value for the token is modified as follows:</p>
191
192 <div style="margin-left: 2em">
193 <pre>
194 f(w) = (s * x + n * p(w))/(s + n)
195 </pre>
196 </div>
197
198 <p>As you see, if n is zero, f(w) is just x, as we have been saying
199 all along; but if n is nonzero and small, the s&nbsp;*&nbsp;x term
200 will influence the f(w) value.</p>
201
202 <p>Parameters s and x are only important when the counts are small,
203 and the value of s reflects what we think of as "small." If s is
204 large, then when counts are small we trust our x value more than we
205 do the p(w); if s is small, we give more weight to p(w) and less to
206 x.</p>
207
208 <p>So how big should s be? Gary Robinson suggested, on a
209 theoretical basis, that we start with a value of 1; it might be
210 worth trying values in the range of 0.01 to 10, though I've never
211 had good results with values larger than 1.&nbsp; Making s smaller
212 than 0.01 or so is a bad idea, because of what happens when a token
213 is encountered that's been seen in spam before, but never in
214 nonspam, or vice versa.&nbsp; In that case, p(w) is exactly 1 or 0,
215 and f(w) will vary greatly as the value of s diminishes.&nbsp; As
216 an example, one spam that had about ten such tokens, out of 78 that
217 contributed to the spam score, scored 0.999 with s set to 0.001,
218 and was found to score 0.505 when s was 1.0e-8!</p>
219
220 <p>Choosing a value for s is a matter of trial and error.&nbsp;
221 Experience suggests that 0.1 might be a better starting value than
222 1, at least if your training database is moderately large.</p>
223
224 <p><a name="md"></a></p>
225
226 <h2>THE MINIMUM DEVIATION</h2>
227
228 <p>MIN_DEV is another thing you might need to vary.&nbsp; Paul
229 Graham's original method was based on looking only at the fifteen
230 tokens with p(w) values farthest from 0.5 (nearest to 0 or
231 1).&nbsp; We don't do it that way; instead, we set a minimum
232 deviation from 0.5 (Gary Robinson coined the term "exclusion
233 radius" for this parameter), and look at all the tokens with f(w)
234 values farther away than that.&nbsp; If the minimum is set to zero,
235 every token in the message contributes its spammishness value f(w)
236 to the final calculation.&nbsp; It might save time, and perhaps
237 improve discrimination, to ignore tokens with f(w) values near 0.5,
238 since those tokens obviously make less difference to the outcome of
239 the calculation.&nbsp; It seems helpful, at least once the training
240 database is a good size, to use a MIN_DEV value between 0.3 and
241 0.46.&nbsp; You might try 0.35 initially; one experiment suggests
242 that even 0.44 might be a good value, but that may not work for
243 everyone.&nbsp; In fact, some people are likely to find that quite
244 a small value of MIN_DEV (around 0.05) works best.</p>
245
246 <p>Note that higher values of MIN_DEV accentuate the distortion
247 caused by small s, because tokens appearing in only one of the spam
248 and nonspam counts will (if present) be a higher proportion of the
249 total number of tokens considered.</p>
250
251 <p><a name="esf"></a></p>
252
253 <h2>EFFECTIVE SIZE FACTORS (ESF)</h2>
254
255 <p>Tokens tend to appear more than once in a given message.&nbsp;
256 If a spam contains the word "valium" it's likely to occur several
257 times.&nbsp; Bogofilter only uses any given token once in
258 calculating the message score, no matter how many times it appears
259 in the message; but since "spammy" and "non-spammy" tokens may
260 occur with very different frequency in the populations of spam and
261 nonspam messages respectively, it helps (as Gary Robinson pointed
262 out) to take this difference in redundancy into account.&nbsp; This
263 is done as follows:&nbsp; Without effective size factors, the score
264 is calculated with inverse chi-squared function
265 <strong>prbx</strong> thus:</p>
266
267 <div style="margin-left: 2em">
268 <pre>
269 P = prbx(-2 * sum(ln(1-f(w))), 2*N)
270 Q = prbx(-2 * sum(ln(f(w))), 2*N)
271 S = (1 + Q - P) / 2
272 </pre>
273 </div>
274
275 <p>and to apply ESF, we instead calculate:</p>
276
277 <div style="margin-left: 2em">
278 <pre>
279 P = prbx(-2 * ln(prod(1-f(w))^y), 2*N*y)
280 Q = prbx(-2 * ln(prod(f(w))^z), 2*N*z)
281 S = Q / (Q + P)
282 </pre>
283 </div>
284
285 <p>where y and z are the spam and nonspam ESF values, the
286 <strong>prod</strong> function returns the product of all its
287 arguments, and S is forced to 0.5 if Q and P are both very near
288 zero.</p>
289
290 <p>Determining the correct values to use for y and z is, like
291 choosing the value for s, a matter of trial and error.&nbsp; A
292 significant corpus of messages is required and users who don't have
293 access to large collections of their spam and nonspam messages
294 should probably opt to do without ESF.&nbsp; Useful values to try
295 seem to be in the range of 0.75 raised to powers between 1 and
296 20.</p>
297
298 <p><a name="co"></a></p>
299
300 <h2>THE SPAM AND NONSPAM CUTOFFS</h2>
301
302 <p>Most spam messages will have scores very close to 1 when the
303 Fisher method of combining the likelihood estimates is applied, and
304 most nonspam will have scores very close to 0.&nbsp; In between,
305 there is a grey area, where messages will fall that have both
306 spammish and nonspammish characteristics.&nbsp; The spam and
307 nonspam cutoffs are thresholds: bogofilter classes messages with
308 scores below the nonspam cutoff as nonspam, and those with scores
309 at or above the spam cutoff as spam. Messages with scores between
310 the two cutoff values are classed as uncertain.&nbsp; (Usually,
311 mail administrators will want to deliver mail classed as uncertain,
312 even though some of it may well be spam.)</p>
313
314 <p>The best value for the spam cutoff depends strongly on the
315 values of the x, s, MIN_DEV and ESF parameters that are being used
316 in the calculation.&nbsp; For that reason, the way to test a given
317 parameter set is the following:</p>
318
319 <ol>
320 <li>Determine a suitable level of false positives (nonspams
321 classified as spam); this will probably need to fall somewhere in
322 the range of 0.05 to 0.3 percent (the lower the better, of course,
323 except that lowering the false-positive target too much gives too
324 many false negatives).</li>
325
326 <li>Apply the parameters to classify a number of known nonspam
327 messages. From the distribution of scores, pick a spam cutoff value
328 that will give the selected proportion of false positives.</li>
329
330 <li>Apply the parameters and the chosen spam cutoff to classify a
331 number of spam messages; the parameter set should be judged on how
332 few false negatives (spam messages classed as uncertain or nonspam)
333 are obtained.</li>
334 </ol>
335
336 <p>The value for the nonspam threshold should be such that no more
337 than about one in ten thousand spams is classified as
338 nonspam.&nbsp; A value of 0.2 to 0.25 might be a good starting
339 point for use with the recommended s and MIN_DEV (0.1 and 0.35
340 respectively).</p>
341
342 <p><a name="bogot"></a></p>
343
344 <h2>AN OVERVIEW OF BOGOTUNE</h2>
345
346 <p>As already mentioned, bogotune attempts to automate the above
347 process by doing a grid search over useful ranges of s, MIN_DEV, x,
348 y and z (an option exists to disable ESF, i.e. leave the ESF values
349 [y and z] at 1.0).&nbsp; Bogotune validates the test inputs,
350 calculates a suitable cache size for the training database,
351 calculates the starting x value as described above, and picks a
352 false-positive target with which to run the grid search.&nbsp;
353 There is an option to force a specific target (more about this
354 shortly).&nbsp; If not coerced, the target is calculated based on
355 the number of nonspam messages in the test set, and then adjusted
356 downward to give a cutoff between 0.5 and 0.975, above 0.55 if
357 possible.&nbsp; It's important to note that this false-positive
358 target is chosen to facilitate the grid search, and is usually very
359 much larger than one would want to see in production; there's no
360 relation between the two.&nbsp; At the end of its run, bogotune
361 attempts to suggest a reasonable production target.</p>
362
363 <p>With these preliminaries completed, bogotune performs two
364 scans:&nbsp; The first is a coarse grid search over the entire
365 useful range of each parameter, which should locate an approximate
366 optimum.&nbsp; A finer grid, centered on the optimum derived from
367 the coarse search, is then scanned to produce the final
368 recommendations.&nbsp; At the end of each scan, outliers --
369 apparently good parameter sets from which even slight deviation
370 degrades performance significantly -- are rejected.&nbsp; Bogotune
371 usually manages to find a robust parameter set that gives good
372 discrimination between spam and nonspam messages, provided that
373 sufficient training and test messages are supplied.</p>
374
375 <p>There are two reasons why one might want to force a bogotune run
376 to use a specific false-positive target.&nbsp; One is that
377 sometimes bogotune's target calculation algorithm is overly
378 optimistic, i.e. it occasionally sets the target too low.&nbsp; The
379 symptom of this problem is that many parameter combinations in the
380 coarse grid scan simply can't deliver that few false positives from
381 the test message corpus.&nbsp; Manually increasing the target by 20
382 to 30 percent usually fixes this.&nbsp; The other reason to coerce
383 the target to a specific value is that one might want to compare
384 two bogotune runs -- with and without ESF, for example -- and
385 comparisons aren't valid unless both runs use the same target.</p>
386
387 <p>Bogotune may produce very different recommendations for very
388 similar sets of spam and nonspam messages.&nbsp; That's not
389 necessarily a defect.&nbsp; For many message populations, the
390 scoring algorithm doesn't depend heavily on precise values of any
391 of the parameters but the spam cutoff.&nbsp; In such cases it's
392 common to see bogotune's coarse scan settle on one of several local
393 optima that may have quite different parameter values.&nbsp; In
394 general, the parameter values have more influence when a single
395 training database is used for a large number of users, and are less
396 crucial when the wordlist is for just one or a few users. <a name=
397 "freq"></a></p>
398
399 <h2>HOW OFTEN TO TUNE</h2>
400
401 <p>It's probably wise to review the spam cutoff frequently.&nbsp;
402 If the false-negative count is gratifyingly low, or if false
403 positives are occurring, increasing the cutoff will reduce the
404 false-positive rate. If, on the other hand, there are absolutely no
405 false positives but the false-negative rate is high, lowering the
406 cutoff a bit may improve discrimination.</p>
407
408 <p>How often to tune the other parameters depends on how fussy you
409 are about optimizing performance.&nbsp; If you're eager to get the
410 best discrimination you can, here are my recommendations:&nbsp; In
411 the early stage, while the training database is still small and
412 growing rapidly, it's probably wise to experiment with tuning x, s
413 and MIN_DEV once a month or so.&nbsp; Once the training database is
414 a good size (over 5000 spams and 5000 nonspams), this can be
415 reduced to quarterly or half-yearly.&nbsp; If you use ESF (which I
416 recommend you do), retuning should probably happen a bit more
417 often, especially if you see that the characteristics of spam
418 you're receiving seem to be changing.</p>
419
420 <p>FWIW my own practice, after two years' experience, is to review
421 the spam cutoff monthly and do a bogotune run about quarterly. <a
422 name="train"></a></p>
423
424 <h2>A NOTE ON TRAINING</h2>
425
426 <p>Bogofilter's ability to distinguish accurately between spam and
427 nonspam messages depends on the quality of its training
428 database.&nbsp; Here is a way of maximizing that quality with
429 relatively little effort.</p>
430
431 <p>When starting afresh, feed every spam and every nonspam you get
432 into bogofilter.&nbsp; Do not use bogofilter's -u option to do
433 this: there will be far too many errors when your training database
434 is small.&nbsp; Instead, classify messages manually and train
435 bogofilter with the -n and -s options appropriately.&nbsp; You can
436 do it in batches: if you work with standard mbox files, use a mail
437 reader to move spam and nonspam into separate files, then do&nbsp;
438 <code>bogofilter&nbsp;-s&nbsp;&lt;&nbsp;spambox</code>&nbsp;
439 and&nbsp; <code>bogofilter&nbsp;-n&nbsp;&lt;&nbsp;nonspambox</code>
440 to register the messages.</p>
441
442 <p>To find out how many spam and nonspam messages have gone into
443 your wordlist, assuming it's kept in ~/.bogofilter, do</p>
444
445 <div style="margin-left: 2em">
446 <pre>
447 bogoutil -w ~/.bogofilter .MSG_COUNT
448 </pre>
449 </div>
450
451 <p>Once you've accumulated about 5,000 spam or nonspam messages in
452 the list, you need to let the other count catch up unless they're
453 growing at about the same rate.&nbsp; Stop adding every message to
454 the larger of the two counts, and instead, add only messages that
455 bogofilter got wrong or was unsure about.&nbsp; To do this, you
456 need to start classifying messages into 4 sets instead of 2: spam,
457 nonspam, unsures that were actually spam, and unsures that were
458 nonspam.</p>
459
460 <p>Once the counts are both over 5,000 and fairly similar, you can
461 train only on errors and unsures.&nbsp; By this time there should
462 be very few errors (spams classed as nonspam or vice versa), but
463 there will still be a proportion of unsure spam and unsure nonspam
464 messages. Training on these will keep bogofilter working well, as
465 you're telling it what it needs to learn, and not so much of what
466 it already knows. If one list grows faster than the other, extra
467 (correctly classified) messages may be added from time to time to
468 equalize them again; try to keep the smaller list's message count
469 at least two thirds of the larger's.</p>
470
471 <p>The use of bogofilter's -u option is convenient but
472 dangerous.&nbsp; Even when well trained, bogofilter <em>will</em>
473 misclassify a small number of messages.&nbsp; With the -u option,
474 these mistakes are entered into the database and decrease its
475 accuracy.&nbsp; More mistakes result and the process
476 snowballs.&nbsp; You therefore need to review and correct the
477 databases frequently, and in the interval between such reviews,
478 bogofilter's effectiveness will keep falling off.&nbsp; The method
479 described above has the advantage that (human error excepted) no
480 wrongly classified messages are ever entered into the database, and
481 if you have to leave it for a time without updating it, its
482 effectiveness doesn't diminish.</p>
483
484 <hr>
485 <p>Much of the advice given here arises out of experiments reported
486 on the author's bogofilter web pages; in particular, the report at
487 <a href="http://www.bgl.nu/bogofilter/smindev3.html">http://www.bgl.nu/bogofilter/smindev3.html</a>
488 might interest those who'd like more information about the basis of
489 bogofilter tuning.</p>
490
491 <p>Thanks go to David Relson for reviewing this document in draft
492 and suggesting several improvements.</p>
493
494 <address>[&copy; <a href="mailto:[email protected]">Greg
495 Louis</a>, 2004; last modified 2004-09-09]</address>
496 </body>
497 </html>
498