Author: | Tobias Leupold |
---|---|
Homepage: | http://nasauber.de/ |
Contact: | tobias.leupold@web.de |
Date: | 2010-06-02 |
Table of Contents
b8 is a spam filter implemented in PHP. (formerly called "bayes-php"). It is intended to keep your weblog or guestbook spam-free. The filter can be used anywhere in your PHP code and tells you if a text is spam or not, using statistical text analysis. See How does it work? for details about this.
To be able to do this, b8 first has to learn some spam and some ham example texts to decide what's good and what's not. If it makes mistakes classifying unknown texts, they can be corrected and b8 learns from what was going wrong, getting better with each example text.
At the moment of this writing, b8 has classified 14411 guestbook entries and weblog comments on my homepage since december 2006. 131 were ham. 39 spam texts (0.27 %) have been rated as ham (false negatives), with not even one false positive (ham message classified as spam).
This results in a sensitivity of 99.73 % and a specifity of 100 % for me. I hope, you'll get the same good results :-)
Basically, b8 is a Bayesian spam filter like Bogofilter or SpamBayes, but it is not intended to classify emails. On the other hand, when I begun writing b8, I didn't know a good spam filter (or any spam filter that isn't just example code how one could implement a Bayesian spam filter in PHP) that was intended to filter weblog or guestbook entries. That's why I had to write my own ;-)
Caused by it's purpose, the way b8 works is slightly different from most of the Bayesian email spam filters out there. See What's different? if you're interested in the details.
b8 is a naive Bayesian Spam filter, basically using the technique described in Paul Graham's article "A Plan For Spam" [1]. The improvements proposed in Graham's article "Better Bayesian Filtering" [2] and Gary Robinson's article "Spam Detection" [3] have also been considered. See also the article "A Statistical Approach to the Spam Problem" [4].
b8 cuts the text to classify to pieces, extracting stuff like email addresses, links and HTML tags. For each such token, it calculates a single probability for it being spam, based on what the filter has learned so far. When the token was not seen before, b8 trys to find similar ones using the "degeneration" described in [2] and uses the most relevant value found. If really nothing is found, a default rating is set.
Then, b8 takes the most relevant values (which have a rating far from 0.5, which would mean we don't know what it is) and calculates the probability that the whole text is spam by the inverse chi-square function described in [3].
There are some parameters that can be set which influence the filter's behaviour (see below).
In short words: you give b8 a text and get back a value between 0 and 1, saying it's ham when it's near 0 and saying it's spam when it's near 1.
Not much! You just need PHP 5 on the server where b8 will be used (b8 version 0.5 finally dropped PHP 4 compatibility – thankfully ;-) and a proper storage possibility for the wordlists. I strongly recommend using Berkeley DB. See below how you can check if you can use it and why you should use it. If the server's PHP wasn't compiled with Berkeley DB support, a MySQL table can be used alternatively.
b8 is designed to classify weblog or guestbook entries, not emails. So, it uses a slightly different technique than the others use.
My experience was that such spam entries were quite short, sometimes just "123abc" as text and a link to a suspect homepage. Some spam bots don't even make a difference between e. g. the "name" and "text" fields and post their text as email address, for example. So, b8 just takes one string to classify, making no difference between "headers" and "text".
The other thing is, that most Bayesian filters count one token one time, no matter how often it appears in the text (as Graham describes it in [1]). b8 does count how often a token was seen and learns or considers this. Additionally, the number of learned ham and spam texts are saved and used as the calculation base for the single possibilities. Why this? Because a text containing one link (no matter where it points to, just indicated by a "http://" or a "www.") might not be spam, but a text containing 20 links might be.
This means that b8 might be good for classifying weblog or guestbook entries – but very likely, it will work quite poor when being used for something else (like classifying emails). But as said above, for this task, there are a lot of very good filters out there to choose from.
The initial name for the filter was (damn creative!) "bayes-php". There were two main reasons for searching another name: 1. "bayes-php" sucks. 2. the PHP License does not want that the name of a script written in PHP does contain "PHP". Read the License FAQ for a reasonable argumentation about this.
Luckily, Tobias Lang proposed the new name "b8". And these are the reasons why I chose this name:
So … have a lot of fun using b8 :-)
If this is a new b8 installation, read on at the Installation section!
Please first follow the database update instructions of the bayes-php-0.3 release if you update from a version prior to bayes-php-0.3 and then read the following paragraph about updating from a version <0.3.3.
The configuration model of b8 has changed. Please read through the Configuration section and update your configuration accordingly.
b8's lexer has been partially re-written. It should be now able to handle all kind of non-latin-1 input, like cyrillic, chinese or japanese texts. Caused by this fact, much more tokens will be recognized when classifying such texts. Therefore, you could get different results in b8's ratings, even if the same database is used and although the math is still the same.
Installing b8 on your server is quite easy. You just have to provide the needed files. To do this, you could just upload the b8 subdirectory to the base directory of your homepage. It contains the filter itself and all needed backend classes. The other directories (doc, example and install) are not used by b8.
That's it ;-)
The configuration is passed as arrays when instantiating a new b8 object. Two arrays can be passed to b8, one containing b8's base configuration and some settings for the lexer (which should be common for all lexer classes, in case some other lexer than the default one will be written one day) and one for the storage backend.
You can have a look at example/index.php to see how this can be done. Using b8 in your scripts also shows example code showing how b8 can be included in a PHP script.
Not all values have to be set. When some values are missing, the default ones will be used. If you do use the default settings, you don't have to pass them to b8.
All these values can be set in the "config_b8" array (the first parameter) passed to b8. The name of the array doesn't matter (of course), it just has to be the first argument.
These are some basic settings telling b8 which backend classes to use:
- storage
This defines which storage backend to use to save b8's wordlist. Currently, two database backends are available: Berkeley DB (dba) and MySQL (mysql). At the moment, b8 0.5 does not support SQLite, but it will be (hopefully) re-added in one of the next releases. The default is dba (string).
- Berkeley DB
- This is the preferred storage backend. It was the original backend for the filter and remains the most performant. b8's storage model is optimized for this database, as it is really fast and fits perfectly to what the filter needs to do the job. All content is saved in a single file, you don't need special rights or a database server.
If you don't know whether your server's PHP can use a Berkeley DB, simply run the script install/setup_berkeleydb.php. If it shows a Berkeley DB handler, please use this backend.- MySQL
- As some webspace hosters don't allow using a Berkeley DB (but please be sure to check if you could use it!), but most do provide a MySQL server, using a MySQL table for the wordlist is provided as an alternative storage method. As said above, b8 was always intended to use a Berkeley DB. It doesn't use or need SQL to query the database. So, very likely, this will work less performant, produce a lot of unnecessary overhead and waste computing power. But it will do fine anyway!
See Configuration of the storage backend for the settings of the chosen backend.
- degenerator
- The degenerator class to be used. See How does it work? and [2] if you're interested in what "degeneration" is. Defaults to default (string). At the moment, only one degenerator exists, so you probably don't want to change this unless you have written your own degenerator.
- lexer
The lexer class to be used. Defaults to default (string). At the moment, only one lexer exists, so you probably don't want to change this unless you have written your own lexer.
The behaviour of the lexer can be additionally configured with the following variables:
- min_size
- The minimal length for a token to be considered when calculating the rating of a text. Defaults to 3 (integer).
- max_size
- The maximal length for a token to be considered when calculating the rating of a text. Defaults to 30 (integer).
- allow_numbers
- Should pure numbers also be considered? Defaults to FALSE (boolean).
The following settings influence the mathematical internals of b8. If you want to experiment, feel free to play around with them; but be warned: wrong settings of these values will result in poor performance or could even "short-circuit" the filter.
Leave these values as they are unless you are sure that your changes will result in a better performance!
The "Statistical discussion about b8" [5] shows why the default values are the default ones.
- use_relevant
- This tells b8 how many tokens should be used when calculating the spamminess of a text. The default setting is 15 (integer). This seems to be a quite reasonable value. When using to many tokens, the filter will fail on texts filled with useless stuff or with passages from a newspaper, etc. not being very spammish.
The tokens counted multiple times (see above) are added in addition to this value. They don't replace other ratings.- min_dev
- This defines a minumun deviation from 0.5 that a token's rating must have to be considered when calculating the spamminess. Tokens with a rating closer to 0.5 than this value will simply be skipped.
If you don't want to use this feature, set this to 0. Defaults to 0.2 (float). Read [5] before increasing this.- rob_x
- This is Gary Robinson's x constant (cf. [3]). A completely unknown token will be rated with the value of rob_x. The default 0.5 (float) seems to be quite reasonable, as we can't say if a token that also can't be rated by degeneration is good or bad.
If you receive much more spam as ham or vice versa, you could change this setting accordingly.- rob_s
- This is Gary Robinson's s constant. This is essentially the probability that the rob_x value is correct for a completely unknown token. It will also shift the probability of rarely seen tokens towards this value. The default is 0.3 (float)
See [3] for a closer description of the s constant and read [5] for specific information about this constant in b8's algorithms.
All these values can be set in the "config_database" array (the second parameter) passed to b8. The name of the array doesn't matter (of course), it just has to be the second argument.
Now, that everything is configured, you can start to use b8. A sample script that shows what can be done with the filter exists in example/index.php. The best thing for testing how all this works is to use this script before using b8 in your own scripts.
Before you can start, you have to setup a database so that b8 can store a wordlist.
I wrote a script to setup a new Berkeley DB for b8. It is located in install/setup_berkeleydb.php. Just run this script on your server and be sure that the directory containing it has sufficient access rights so that the server's HTTP server user or PHP user can create a new file in it (probably 0777). The script is quite self-explaining, just run it.
Of course, you can create a Berkeley DB by hand, you just have to insert three keys:
bayes*dbversion => 2 bayes*texts.ham => 0 bayes*texts.spam => 0
Be sure to set the right DBA handler in the storage backend cionfiguration if it's not db4.
The SQL file install/setup_mysql.sql contains both the create statement for the wordlist table of b8 and the INSERT statements for adding the necessary internal variables.
Simply change the table name according to your needs (or leave it as it is ;-) and run the SQL to setup a b8 wordlist MySQL table.
Just have a look at the example script located in example/index.php to see how you can include b8 in your scripts. Essentially, this strips down to:
# Include the b8 code require "{$_SERVER['DOCUMENT_ROOT']}/b8/b8.php"; # Do some configuration $config_b8 = array( 'some_key' => 'some_value', 'foo' => 'bar' ); $config_database = array( 'some_key' => 'some_value', 'foo' => 'bar' ); # Create a new b8 instance $b8 = new b8($config_b8, $config_database);
b8 provides three functions in an object oriented way (called e. g. via $b8->classify($text)):
Before b8 can decide whether a text is spam or ham, you have to tell it what you consider as spam or ham. At least one learned spam or one learned ham text is needed to calculate anything. To get good ratings, you need both learned ham and learned spam texts.
What's considered as "ham" or "spam" can be very different, depending on the operation site. On my homepage, practically each and every text posted using cyrillic letters is spam. On a russian homepage, this will be not the case. So I think it's not really meaningful to provide some "spam data" somebody can use. Just train b8 with "your" spam and ham. The more, the better!
For the practical use, I advise to give the filter all data availible. E. g. name, email address, homepage, IP address und of course the actual text should be stored in a variable (e. g. separated with an \n after each block) and then be classified. The learning should also be done with all data availible.
Saving the IP address is probably only meaningful for spam entries, because spammers often use the same IP address multiple times. In principle, you can leave out the IP of ham entries.
You can use b8 e. g. in a guestbook script and let it classify the text before saving it. Everyone has to decide which rating is necessary to classify a text as "spam", but a rating of >= 0.8 seems to be reasonable for me. If one expects the spam to be in another language that the ham entries or the spams are very short normally, one could also think about a limit of 0.7.
The email filters out there mostly use > 0.9 or even > 0.99; but keep in mind that they have way more data to analyze in most of the cases. A guestbook entry may be quite short, especially when it's spam.
In my opinion, a autolearn function is very handy. I save spam messages with a rating higher than 0.7 but less than 0.9 automatically as spam. I don't do this with ham messages in an automated way to prevent the filter from saving a false negative as ham and then classifying and learning all the spam as ham when I'm on holidays ;-)
So … that's it. Thanks for using b8! If you find a bug or have an idea how to make b8 better, let me know. I'm also always looking forward to get emails from people using b8 on their homepages :-)
[1] | (1, 2) Paul Graham, A Plan For Spam (http://paulgraham.com/spam.html) |
[2] | (1, 2, 3) Paul Graham, Better Bayesian Filtering (http://paulgraham.com/better.html) |
[3] | (1, 2, 3, 4) Gary Robinson, Spam Detection (http://radio.weblogs.com/0101454/stories/2002/09/16/spamDetection.html) |
[4] | A Statistical Approach to the Spam Problem (http://linuxjournal.com/article/6467) |
[5] | (1, 2, 3) Tobias Leupold, Statistical discussion about b8 (http://nasauber.de/opensource/b8/discussion/) |