1SA-LEARN(1)           User Contributed Perl Documentation          SA-LEARN(1)
2
3
4

NAME

6       sa-learn - train SpamAssassin's Bayesian classifier
7

SYNOPSIS

9       sa-learn [options] [file]...
10
11       sa-learn [options] --dump [ all | data | magic ]
12
13       Options:
14
15        --ham                 Learn messages as ham (non-spam)
16        --spam                Learn messages as spam
17        --forget              Forget a message
18        --use-ignores         Use bayes_ignore_from and bayes_ignore_to
19        --sync                Synchronize the database and the journal if needed
20        --force-expire        Force a database sync and expiry run
21        --dbpath <path>       Allows commandline override (in bayes_path form)
22                              for where to read the Bayes DB from
23        --dump [all|data|magic]  Display the contents of the Bayes database
24                              Takes optional argument for what to display
25         --regexp <re>        For dump only, specifies which tokens to
26                              dump based on a regular expression.
27        -f file, --folders=file  Read list of files/directories from file
28        --dir                 Ignored; historical compatibility
29        --file                Ignored; historical compatibility
30        --mbox                Input sources are in mbox format
31        --mbx                 Input sources are in mbx format
32        --max-size <b>        Skip messages larger than b bytes;
33                              defaults to 256 KiB, 0 implies no limit
34        --showdots            Show progress using dots
35        --progress            Show progress using progress bar
36        --no-sync             Skip synchronizing the database and journal
37                              after learning
38        -L, --local           Operate locally, no network accesses
39        --import              Migrate data from older version/non DB_File
40                              based databases
41        --clear               Wipe out existing database
42        --backup              Backup, to STDOUT, existing database
43        --restore <filename>  Restore a database from filename
44        -u username, --username=username
45                              Override username taken from the runtime
46                              environment, used with SQL
47        -C path, --configpath=path, --config-file=path
48                              Path to standard configuration dir
49        -p prefs, --prefspath=file, --prefs-file=file
50                              Set user preferences file
51        --siteconfigpath=path Path for site configs
52                              (default: /etc/mail/spamassassin)
53        --cf='config line'    Additional line of configuration
54        -D, --debug [area=n,...]  Print debugging messages
55        -V, --version         Print version
56        -h, --help            Print usage message
57

DESCRIPTION

59       Given a typical selection of your incoming mail classified as spam or
60       ham (non-spam), this tool will feed each mail to SpamAssassin, allowing
61       it to 'learn' what signs are likely to mean spam, and which are likely
62       to mean ham.
63
64       Simply run this command once for each of your mail folders, and it will
65       ''learn'' from the mail therein.
66
67       Note that csh-style globbing in the mail folder names is supported; in
68       other words, listing a folder name as "*" will scan every folder that
69       matches.  See "Mail::SpamAssassin::ArchiveIterator" for more details.
70
71       SpamAssassin remembers which mail messages it has learnt already, and
72       will not re-learn those messages again, unless you use the --forget
73       option. Messages learnt as spam will have SpamAssassin markup removed,
74       on the fly.
75
76       If you make a mistake and scan a mail as ham when it is spam, or vice
77       versa, simply rerun this command with the correct classification, and
78       the mistake will be corrected.  SpamAssassin will automatically
79       'forget' the previous indications.
80
81       Users of "spamd" who wish to perform training remotely, over a network,
82       should investigate the "spamc -L" switch.
83

OPTIONS

85       --ham
86           Learn the input message(s) as ham.   If you have previously learnt
87           any of the messages as spam, SpamAssassin will forget them first,
88           then re-learn them as ham.  Alternatively, if you have previously
89           learnt them as ham, it'll skip them this time around.  If the
90           messages have already been filtered through SpamAssassin, the
91           learner will ignore any modifications SpamAssassin may have made.
92
93       --spam
94           Learn the input message(s) as spam.   If you have previously learnt
95           any of the messages as ham, SpamAssassin will forget them first,
96           then re-learn them as spam.  Alternatively, if you have previously
97           learnt them as spam, it'll skip them this time around.  If the
98           messages have already been filtered through SpamAssassin, the
99           learner will ignore any modifications SpamAssassin may have made.
100
101       --folders=filename, -f filename
102           sa-learn will read in the list of folders from the specified file,
103           one folder per line in the file.  If the folder is prefixed with
104           "ham:type:" or "spam:type:", sa-learn will learn that folder
105           appropriately, otherwise the folders will be assumed to be of the
106           type specified by --ham or --spam.
107
108           "type" above is optional, but is the same as the standard for
109           ArchiveIterator: mbox, mbx, dir, file, or detect (the default if
110           not specified).
111
112       --mbox
113           sa-learn will read in the file(s) containing the emails to be
114           learned, and will process them in mbox format (one or more emails
115           per file).
116
117       --mbx
118           sa-learn will read in the file(s) containing the emails to be
119           learned, and will process them in mbx format (one or more emails
120           per file).
121
122       --use-ignores
123           Don't learn the message if a from address matches configuration
124           file item "bayes_ignore_from" or a to address matches
125           "bayes_ignore_to".  The option might be used when learning from a
126           large file of messages from which the hammy spam messages or spammy
127           ham messages have not been removed.
128
129       --sync
130           Synchronize the journal and databases.  Upon successfully syncing
131           the database with the entries in the journal, the journal file is
132           removed.
133
134       --force-expire
135           Forces an expiry attempt, regardless of whether it may be necessary
136           or not.  Note: This doesn't mean any tokens will actually expire.
137           Please see the EXPIRATION section below.
138
139           Note: "--force-expire" also causes the journal data to be
140           synchronized into the Bayes databases.
141
142       --forget
143           Forget a given message previously learnt.
144
145       --dbpath
146           Allows a commandline override of the bayes_path configuration
147           option.
148
149       --dump option
150           Display the contents of the Bayes database.  Without an option or
151           with the all option, all magic tokens and data tokens will be
152           displayed.  magic will only display magic tokens, and data will
153           only display the data tokens.
154
155           Can also use the --regexp RE option to specify which tokens to
156           display based on a regular expression.
157
158       --clear
159           Clear an existing Bayes database by removing all traces of the
160           database.
161
162           WARNING: This is destructive and should be used with care.
163
164       --backup
165           Performs a dump of the Bayes database in machine/human readable
166           format.
167
168           The dump will include token and seen data.  It is suitable for
169           input back into the --restore command.
170
171       --restore=filename
172           Performs a restore of the Bayes database defined by filename.
173
174           WARNING: This is a destructive operation, previous Bayes data will
175           be wiped out.
176
177       -h, --help
178           Print help message and exit.
179
180       -u username, --username=username
181           If specified this username will override the username taken from
182           the runtime environment.  You can use this option to specify users
183           in a virtual user configuration when using SQL as the Bayes
184           backend.
185
186           NOTE: This option will not change to the given username, it will
187           only attempt to act on behalf of that user.  Because of this you
188           will need to have proper permissions to be able to change files
189           owned by username.  In the case of SQL this generally is not a
190           problem.
191
192       -C path, --configpath=path, --config-file=path
193           Use the specified path for locating the distributed configuration
194           files.  Ignore the default directories (usually
195           "/usr/share/spamassassin" or similar).
196
197       --siteconfigpath=path
198           Use the specified path for locating site-specific configuration
199           files.  Ignore the default directories (usually
200           "/etc/mail/spamassassin" or similar).
201
202       --cf='config line'
203           Add additional lines of configuration directly from the command-
204           line, parsed after the configuration files are read.   Multiple
205           --cf arguments can be used, and each will be considered a separate
206           line of configuration.
207
208       -p prefs, --prefspath=prefs, --prefs-file=prefs
209           Read user score preferences from prefs (usually
210           "$HOME/.spamassassin/user_prefs").
211
212       --progress
213           Prints a progress bar (to STDERR) showing the current progress.  In
214           the case where no valid terminal is found this option will behave
215           very much like the --showdots option.
216
217       -D [area,...], --debug [area,...]
218           Produce debugging output. If no areas are listed, all debugging
219           information is printed. Diagnostic output can also be enabled for
220           each area individually; area is the area of the code to instrument.
221           For example, to produce diagnostic output on bayes, learn, and dns,
222           use:
223
224                   spamassassin -D bayes,learn,dns
225
226           For more information about which areas (also known as channels) are
227           available, please see the documentation at:
228
229                   C<http://wiki.apache.org/spamassassin/DebugChannels>
230
231           Higher priority informational messages that are suitable for
232           logging in normal circumstances are available with an area of
233           "info".
234
235       --no-sync
236           Skip the slow synchronization step which normally takes place after
237           changing database entries.  If you plan to learn from many folders
238           in a batch, or to learn many individual messages one-by-one, it is
239           faster to use this switch and run "sa-learn --sync" once all the
240           folders have been scanned.
241
242           Clarification: The state of --no-sync overrides the
243           bayes_learn_to_journal configuration option.  If not specified, sa-
244           learn will learn to the database directly.  If specified, sa-learn
245           will learn to the journal file.
246
247           Note: --sync and --no-sync can be specified on the same
248           commandline, which is slightly confusing.  In this case, the
249           --no-sync option is ignored since there is no learn operation.
250
251       -L, --local
252           Do not perform any network accesses while learning details about
253           the mail messages.  This will speed up the learning process, but
254           may result in a slightly lower accuracy.
255
256           Note that this is currently ignored, as current versions of
257           SpamAssassin will not perform network access while learning; but
258           future versions may.
259
260       --import
261           If you previously used SpamAssassin's Bayesian learner without the
262           "DB_File" module installed, it will have created files in other
263           formats, such as "GDBM_File", "NDBM_File", or "SDBM_File".  This
264           switch allows you to migrate that old data into the "DB_File"
265           format.  It will overwrite any data currently in the "DB_File".
266
267           Can also be used with the --dbpath path option to specify the
268           location of the Bayes files to use.
269

MIGRATION

271       There are now multiple backend storage modules available for storing
272       user's bayesian data. As such you might want to migrate from one
273       backend to another. Here is a simple procedure for migrating from one
274       backend to another.
275
276       Note that if you have individual user databases you will have to
277       perform a similar procedure for each one of them.
278
279       sa-learn --sync
280           This will sync any outstanding journal entries
281
282       sa-learn --backup > backup.txt
283           This will save all your Bayes data to a plain text file.
284
285       sa-learn --clear
286           This is optional, but good to do to clear out the old database.
287
288       Repeat!
289           At this point, if you have multiple databases, you should perform
290           the procedure above for each of them. (i.e. each user's database
291           needs to be backed up before continuing.)
292
293       Switch backends
294           Once you have backed up all databases you can update your
295           configuration for the new database backend. This will involve at
296           least the bayes_store_module config option and may involve some
297           additional config options depending on what is required by the
298           module. (For example, you may need to configure an SQL database.)
299
300       sa-learn --restore backup.txt
301           Again, you need to do this for every database.
302
303       If you are migrating to SQL you can make use of the -u <username>
304       option in sa-learn to populate each user's database. Otherwise, you
305       must run sa-learn as the user who database you are restoring.
306

INTRODUCTION TO BAYESIAN FILTERING

308       (Thanks to Michael Bell for this section!)
309
310       For a more lengthy description of how this works, go to
311       http://www.paulgraham.com/ and see "A Plan for Spam". It's reasonably
312       readable, even if statistics make me break out in hives.
313
314       The short semi-inaccurate version: Given training, a spam heuristics
315       engine can take the most "spammy" and "hammy" words and apply
316       probabilistic analysis. Furthermore, once given a basis for the
317       analysis, the engine can continue to learn iteratively by applying both
318       the non-Bayesian and Bayesian rulesets together to create evolving
319       "intelligence".
320
321       SpamAssassin 2.50 and later supports Bayesian spam analysis, in the
322       form of the BAYES rules. This is a new feature, quite powerful, and is
323       disabled until enough messages have been learnt.
324
325       The pros of Bayesian spam analysis:
326
327       Can greatly reduce false positives and false negatives.
328           It learns from your mail, so it is tailored to your unique e-mail
329           flow.
330
331       Once it starts learning, it can continue to learn from SpamAssassin and
332       improve over time.
333
334       And the cons:
335
336       A decent number of messages are required before results are useful for
337       ham/spam determination.
338       It's hard to explain why a message is or isn't marked as spam.
339           i.e.: a straightforward rule, that matches, say, "VIAGRA" is easy
340           to understand. If it generates a false positive or false negative,
341           it is fairly easy to understand why.
342
343           With Bayesian analysis, it's all probabilities - "because the past
344           says it is likely as this falls into a probabilistic distribution
345           common to past spam in your systems". Tell that to your users!
346           Tell that to the client when he asks "what can I do to change
347           this". (By the way, the answer in this case is "use whitelisting".)
348
349       It will take disk space and memory.
350           The databases it maintains take quite a lot of resources to store
351           and use.
352

GETTING STARTED

354       Still interested? Ok, here's the guidelines for getting this working.
355
356       First a high-level overview:
357
358       Build a significant sample of both ham and spam.
359           I suggest several thousand of each, placed in SPAM and HAM
360           directories or mailboxes.  Yes, you MUST hand-sort this - otherwise
361           the results won't be much better than SpamAssassin on its own.
362           Verify the spamminess/haminess of EVERY message.  You're urged to
363           avoid using a publicly available corpus (sample) - this must be
364           taken from YOUR mail server, if it is to be statistically useful.
365           Otherwise, the results may be pretty skewed.
366
367       Use this tool to teach SpamAssassin about these samples, like so:
368                   sa-learn --spam /path/to/spam/folder
369                   sa-learn --ham /path/to/ham/folder
370                   ...
371
372           Let SpamAssassin proceed, learning stuff. When it finds ham and
373           spam it will add the "interesting tokens" to the database.
374
375       If you need SpamAssassin to forget about specific messages, use the
376       --forget option.
377           This can be applied to either ham or spam that has run through the
378           sa-learn processes. It's a bit of a hammer, really, lowering the
379           weighting of the specific tokens in that message (only if that
380           message has been processed before).
381
382       Learning from single messages uses a command like this:
383                   sa-learn --ham --no-sync mailmessage
384
385           This is handy for binding to a key in your mail user agent.  It's
386           very fast, as all the time-consuming stuff is deferred until you
387           run with the "--sync" option.
388
389       Autolearning is enabled by default
390           If you don't have a corpus of mail saved to learn, you can let
391           SpamAssassin automatically learn the mail that you receive.  If you
392           are autolearning from scratch, the amount of mail you receive will
393           determine how long until the BAYES_* rules are activated.
394

EFFECTIVE TRAINING

396       Learning filters require training to be effective.  If you don't train
397       them, they won't work.  In addition, you need to train them with new
398       messages regularly to keep them up-to-date, or their data will become
399       stale and impact accuracy.
400
401       You need to train with both spam and ham mails.  One type of mail alone
402       will not have any effect.
403
404       Note that if your mail folders contain things like forwarded spam,
405       discussions of spam-catching rules, etc., this will cause trouble.  You
406       should avoid scanning those messages if possible.  (An easy way to do
407       this is to move them aside, into a folder which is not scanned.)
408
409       If the messages you are learning from have already been filtered
410       through SpamAssassin, the learner will compensate for this.  In effect,
411       it learns what each message would look like if you had run
412       "spamassassin -d" over it in advance.
413
414       Another thing to be aware of, is that typically you should aim to train
415       with at least 1000 messages of spam, and 1000 ham messages, if
416       possible.  More is better, but anything over about 5000 messages does
417       not improve accuracy significantly in our tests.
418
419       Be careful that you train from the same source -- for example, if you
420       train on old spam, but new ham mail, then the classifier will think
421       that a mail with an old date stamp is likely to be spam.
422
423       It's also worth noting that training with a very small quantity of ham,
424       will produce atrocious results.  You should aim to train with at least
425       the same amount (or more if possible!) of ham data than spam.
426
427       On an on-going basis, it is best to keep training the filter to make
428       sure it has fresh data to work from.  There are various ways to do
429       this:
430
431       1. Supervised learning
432           This means keeping a copy of all or most of your mail, separated
433           into spam and ham piles, and periodically re-training using those.
434           It produces the best results, but requires more work from you, the
435           user.
436
437           (An easy way to do this, by the way, is to create a new folder for
438           'deleted' messages, and instead of deleting them from other
439           folders, simply move them in there instead.  Then keep all spam in
440           a separate folder and never delete it.  As long as you remember to
441           move misclassified mails into the correct folder set, it is easy
442           enough to keep up to date.)
443
444       2. Unsupervised learning from Bayesian classification
445           Another way to train is to chain the results of the Bayesian
446           classifier back into the training, so it reinforces its own
447           decisions.  This is only safe if you then retrain it based on any
448           errors you discover.
449
450           SpamAssassin does not support this method, due to experimental
451           results which strongly indicate that it does not work well, and
452           since Bayes is only one part of the resulting score presented to
453           the user (while Bayes may have made the wrong decision about a
454           mail, it may have been overridden by another system).
455
456       3. Unsupervised learning from SpamAssassin rules
457           Also called 'auto-learning' in SpamAssassin.  Based on statistical
458           analysis of the SpamAssassin success rates, we can automatically
459           train the Bayesian database with a certain degree of confidence
460           that our training data is accurate.
461
462           It should be supplemented with some supervised training in
463           addition, if possible.
464
465           This is the default, but can be turned off by setting the
466           SpamAssassin configuration parameter "bayes_auto_learn" to 0.
467
468       4. Mistake-based training
469           This means training on a small number of mails, then only training
470           on messages that SpamAssassin classifies incorrectly.  This works,
471           but it takes longer to get it right than a full training session
472           would.
473

FILES

475       sa-learn and the other parts of SpamAssassin's Bayesian learner, use a
476       set of persistent database files to store the learnt tokens, as
477       follows.
478
479       bayes_toks
480           The database of tokens, containing the tokens learnt, their count
481           of occurrences in ham and spam, and the timestamp when the token
482           was last seen in a message.
483
484           This database also contains some 'magic' tokens, as follows: the
485           version number of the database, the number of ham and spam messages
486           learnt, the number of tokens in the database, and timestamps of:
487           the last journal sync, the last expiry run, the last expiry token
488           reduction count, the last expiry timestamp delta, the oldest token
489           timestamp in the database, and the newest token timestamp in the
490           database.
491
492           This is a database file, using "DB_File".  The database 'version
493           number' is 0 for databases from 2.5x, 1 for databases from certain
494           2.6x development releases, 2 for 2.6x, and 3 for 3.0 and later
495           releases.
496
497       bayes_seen
498           A map of Message-Id and some data from headers and body to what
499           that message was learnt as. This is used so that SpamAssassin can
500           avoid re-learning a message it has already seen, and so it can
501           reverse the training if you later decide that message was learnt
502           incorrectly.
503
504           This is a database file, using "DB_File".
505
506       bayes_journal
507           While SpamAssassin is scanning mails, it needs to track which
508           tokens it uses in its calculations.  To avoid the contention of
509           having each SpamAssassin process attempting to gain write access to
510           the Bayes DB, the token timestamps are written to a 'journal' file
511           which will later (either automatically or via "sa-learn --sync") be
512           used to synchronize the Bayes DB.
513
514           Also, through the use of "bayes_learn_to_journal", or when using
515           the "--no-sync" option with sa-learn, the actual learning data will
516           take be placed into the journal for later synchronization.  This is
517           typically useful for high-traffic sites to avoid the same
518           contention as stated above.
519

EXPIRATION

521       Since SpamAssassin can auto-learn messages, the Bayes database files
522       could increase perpetually until they fill your disk.  To control this,
523       SpamAssassin performs journal synchronization and bayes expiration
524       periodically when certain criteria (listed below) are met.
525
526       SpamAssassin can sync the journal and expire the DB tokens either
527       manually or opportunistically.  A journal sync is due if --sync is
528       passed to sa-learn (manual), or if the following is true
529       (opportunistic):
530
531       - bayes_journal_max_size does not equal 0 (means don't sync)
532       - the journal file exists
533
534       and either:
535
536       - the journal file has a size greater than bayes_journal_max_size
537
538       or
539
540       - a journal sync has previously occurred, and at least 1 day has passed
541       since that sync
542
543       Expiry is due if --force-expire is passed to sa-learn (manual), or if
544       all of the following are true (opportunistic):
545
546       - the last expire was attempted at least 12hrs ago
547       - bayes_auto_expire does not equal 0
548       - the number of tokens in the DB is > 100,000
549       - the number of tokens in the DB is > bayes_expiry_max_db_size
550       - there is at least a 12 hr difference between the oldest and newest
551       token atimes
552
553   EXPIRE LOGIC
554       If either the manual or opportunistic method causes an expire run to
555       start, here is the logic that is used:
556
557       - figure out how many tokens to keep.  take the larger of either
558       bayes_expiry_max_db_size * 75% or 100,000 tokens.  therefore, the goal
559       reduction is number of tokens - number of tokens to keep.
560       - if the reduction number is < 1000 tokens, abort (not worth the
561       effort).
562       - if an expire has been done before, guesstimate the new atime delta
563       based on the old atime delta.  (new_atime_delta = old_atime_delta *
564       old_reduction_count / goal)
565       - if no expire has been done before, or the last expire looks "weird",
566       do an estimation pass.  The definition of "weird" is:
567           - last expire over 30 days ago
568           - last atime delta was < 12 hrs
569           - last reduction count was < 1000 tokens
570           - estimated new atime delta is < 12 hrs
571           - the difference between the last reduction count and the goal
572           reduction count is > 50%
573
574   ESTIMATION PASS LOGIC
575       Go through each of the DB's tokens.  Starting at 12hrs, calculate
576       whether or not the token would be expired (based on the difference
577       between the token's atime and the db's newest token atime) and keep the
578       count.  Work out from 12hrs exponentially by powers of 2.  ie: 12hrs *
579       1, 12hrs * 2, 12hrs * 4, 12hrs * 8, and so on, up to 12hrs * 512
580       (6144hrs, or 256 days).
581
582       The larger the delta, the smaller the number of tokens that will be
583       expired.  Conversely, the number of tokens goes up as the delta gets
584       smaller.  So starting at the largest atime delta, figure out which
585       delta will expire the most tokens without going above the goal
586       expiration count.  Use this to choose the atime delta to use, unless
587       one of the following occurs:
588
589       - the largest atime (smallest reduction count) would expire too many
590       tokens.  this means the learned tokens are mostly old and there needs
591       to be new tokens learned before an expire can occur.
592       - all of the atime choices result in 0 tokens being removed. this means
593       the tokens are all newer than 12 hours and there needs to be new tokens
594       learned before an expire can occur.
595       - the number of tokens that would be removed is < 1000.  the benefit
596       isn't worth the effort.  more tokens need to be learned.
597
598       If the expire run gets past this point, it will continue to the end.  A
599       new DB is created since the majority of DB libraries don't shrink the
600       DB file when tokens are removed.  So we do the "create new, migrate old
601       to new, remove old, rename new" shuffle.
602
603   EXPIRY RELATED CONFIGURATION SETTINGS
604       "bayes_auto_expire" is used to specify whether or not SpamAssassin
605       ought to opportunistically attempt to expire the Bayes database. The
606       default is 1 (yes).
607       "bayes_expiry_max_db_size" specifies both the auto-expire token count
608       point, as well as the resulting number of tokens after expiry as
609       described above.  The default value is 150,000, which is roughly
610       equivalent to a 6Mb database file if you're using DB_File.
611       "bayes_journal_max_size" specifies how large the Bayes journal will
612       grow before it is opportunistically synced.  The default value is
613       102400.
614

INSTALLATION

616       The sa-learn command is part of the Mail::SpamAssassin Perl module.
617       Install this as a normal Perl module, using "perl -MCPAN -e shell", or
618       by hand.
619

SEE ALSO

621       spamassassin(1) spamc(1) Mail::SpamAssassin(3)
622       Mail::SpamAssassin::ArchiveIterator(3)
623
624       <http://www.paulgraham.com/> Paul Graham's "A Plan For Spam" paper
625
626       <http://www.linuxjournal.com/article/6467> Gary Robinson's f(x) and
627       combining algorithms, as used in SpamAssassin
628
629       <http://www.bgl.nu/~glouis/bogofilter/> 'Training on error' page.  A
630       discussion of various Bayes training regimes, including 'train on
631       error' and unsupervised training.
632

PREREQUISITES

634       "Mail::SpamAssassin"
635

AUTHORS

637       The SpamAssassin(tm) Project <http://spamassassin.apache.org/>
638
639
640
641perl v5.16.3                      2018-10-15                       SA-LEARN(1)
Impressum