You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

classifier_test.pl 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. #!/usr/bin/env perl
  2. use warnings;
  3. use strict;
  4. use Pod::Usage;
  5. use Getopt::Long;
  6. use Time::HiRes qw(gettimeofday tv_interval);
  7. use JSON::XS;
  8. use String::ShellQuote;
  9. use FileHandle;
  10. use IPC::Open2;
  11. use Data::Dumper;
  12. my $spam_dir;
  13. my $ham_dir;
  14. my $parallel = 1;
  15. my $classifier = "bayes";
  16. my $spam_symbol = "BAYES_SPAM";
  17. my $ham_symbol = "BAYES_HAM";
  18. my $timeout = 10;
  19. my $rspamc = $ENV{'RSPAMC'} || "rspamc";
  20. my $bogofilter = $ENV{'BOGOFILTER'} || "bogofilter";
  21. my $dspam = $ENV{'DSPAM'} || "dspam";
  22. my $train_fraction = 0.5;
  23. my $use_bogofilter = 0;
  24. my $use_dspam = 0;
  25. my $check_only = 0;
  26. my $rspamc_prob_trigger = 95;
  27. my $man;
  28. my $help;
  29. GetOptions(
  30. "spam|s=s" => \$spam_dir,
  31. "ham|h=s" => \$ham_dir,
  32. "spam-symbol=s" => \$spam_symbol,
  33. "ham-symbol=s" => \$ham_symbol,
  34. "classifier|c=s" => \$classifier,
  35. "timeout|t=f" => \$timeout,
  36. "parallel|p=i" => \$parallel,
  37. "train-fraction|t=f" => \$train_fraction,
  38. "bogofilter|b" => \$use_bogofilter,
  39. "dspam|d" => \$use_dspam,
  40. "check-only" => \$check_only,
  41. "help|?" => \$help,
  42. "man" => \$man
  43. ) or pod2usage(2);
  44. pod2usage(1) if $help;
  45. pod2usage( -exitval => 0, -verbose => 2 ) if $man;
  46. sub read_dir_files {
  47. my ( $dir, $target ) = @_;
  48. opendir( my $dh, $dir ) or die "cannot open dir $dir: $!";
  49. while ( my $file = readdir $dh ) {
  50. if ( -f "$dir/$file" ) {
  51. push @{$target}, "$dir/$file";
  52. }
  53. }
  54. }
  55. sub shuffle_array {
  56. my ($ar) = @_;
  57. for ( my $i = 0 ; $i < scalar @{$ar} ; $i++ ) {
  58. if ( $i > 1 ) {
  59. my $sel = int( rand( $i - 1 ) );
  60. ( @{$ar}[$i], @{$ar}[$sel] ) = ( @{$ar}[$sel], @{$ar}[$i] );
  61. }
  62. }
  63. }
  64. sub learn_rspamc {
  65. my ( $files, $spam ) = @_;
  66. my $processed = 0;
  67. my $cmd = $spam ? "learn_spam" : "learn_ham";
  68. my $args_quoted = shell_quote @{$files};
  69. open( my $p, "$rspamc -t $timeout -c $classifier --compact -j -n $parallel $cmd $args_quoted |" )
  70. or die "cannot spawn $rspamc: $!";
  71. while (<$p>) {
  72. my $res = eval('decode_json($_)');
  73. if ( $res && $res->{'success'} ) {
  74. $processed++;
  75. }
  76. }
  77. return $processed;
  78. }
  79. sub learn_bogofilter {
  80. my ( $files, $spam ) = @_;
  81. my $processed = 0;
  82. foreach my $f ( @{$files} ) {
  83. my $args_quoted = shell_quote $f;
  84. my $fl = $spam ? "-s" : "-n";
  85. `$bogofilter -I $args_quoted $fl`;
  86. if ( $? == 0 ) {
  87. $processed++;
  88. }
  89. }
  90. return $processed;
  91. }
  92. sub learn_dspam {
  93. my ( $files, $spam ) = @_;
  94. my $processed = 0;
  95. foreach my $f ( @{$files} ) {
  96. my $args_quoted = shell_quote $f;
  97. my $fl = $spam ? "--class=spam" : "--class=innocent";
  98. open( my $p, "|$dspam --user nobody --source=corpus --stdout --mode=toe $fl" )
  99. or die "cannot run $dspam: $!";
  100. open( my $inp, "< $f" );
  101. while (<$inp>) {
  102. print $p $_;
  103. }
  104. }
  105. return $processed;
  106. }
  107. sub learn_samples {
  108. my ( $ar_ham, $ar_spam ) = @_;
  109. my $len;
  110. my $processed = 0;
  111. my $total = 0;
  112. my $learn_func;
  113. my @files_spam;
  114. my @files_ham;
  115. if ($use_dspam) {
  116. $learn_func = \&learn_dspam;
  117. }
  118. elsif ($use_bogofilter) {
  119. $learn_func = \&learn_bogofilter;
  120. }
  121. else {
  122. $learn_func = \&learn_rspamc;
  123. }
  124. $len = int( scalar @{$ar_ham} * $train_fraction );
  125. my @cur_vec;
  126. # Shuffle spam and ham samples
  127. for ( my $i = 0 ; $i < $len ; $i++ ) {
  128. if ( $i > 0 && ( $i % $parallel == 0 || $i == $len - 1 ) ) {
  129. push @cur_vec, @{$ar_ham}[$i];
  130. push @files_ham, [@cur_vec];
  131. @cur_vec = ();
  132. $total++;
  133. }
  134. else {
  135. push @cur_vec, @{$ar_ham}[$i];
  136. }
  137. }
  138. $len = int( scalar @{$ar_spam} * $train_fraction );
  139. @cur_vec = ();
  140. for ( my $i = 0 ; $i < $len ; $i++ ) {
  141. if ( $i > 0 && ( $i % $parallel == 0 || $i == $len - 1 ) ) {
  142. push @cur_vec, @{$ar_spam}[$i];
  143. push @files_spam, [@cur_vec];
  144. @cur_vec = ();
  145. $total++;
  146. }
  147. else {
  148. push @cur_vec, @{$ar_spam}[$i];
  149. }
  150. }
  151. for ( my $i = 0 ; $i < $total ; $i++ ) {
  152. my $args;
  153. my $spam;
  154. if ( $i % 2 == 0 ) {
  155. $args = pop @files_spam;
  156. if ( !$args ) {
  157. $args = pop @files_ham;
  158. $spam = 0;
  159. }
  160. else {
  161. $spam = 1;
  162. }
  163. }
  164. else {
  165. $args = pop @files_ham;
  166. if ( !$args ) {
  167. $args = pop @files_spam;
  168. $spam = 1;
  169. }
  170. else {
  171. $spam = 0;
  172. }
  173. }
  174. my $r = $learn_func->( $args, $spam );
  175. if ($r) {
  176. $processed += $r;
  177. }
  178. }
  179. return $processed;
  180. }
  181. sub check_rspamc {
  182. my ( $files, $spam, $fp_cnt, $fn_cnt, $detected_cnt ) = @_;
  183. my $args_quoted = shell_quote @{$files};
  184. my $processed = 0;
  185. open(
  186. my $p,
  187. "$rspamc -t $timeout -n $parallel --header=\"Settings: {symbols_enabled=[BAYES_SPAM]}\" --compact -j $args_quoted |"
  188. ) or die "cannot spawn $rspamc: $!";
  189. while (<$p>) {
  190. my $res = eval('decode_json($_)');
  191. if ( $res && $res->{'default'} ) {
  192. $processed++;
  193. if ($spam) {
  194. if ( $res->{'default'}->{$ham_symbol} ) {
  195. my $m = $res->{'default'}->{$ham_symbol}->{'options'}->[0];
  196. if ( $m && $m =~ /^(\d+(?:\.\d+)?)%$/ ) {
  197. my $percentage = int($1);
  198. if ( $percentage >= $rspamc_prob_trigger ) {
  199. $$fp_cnt++;
  200. }
  201. }
  202. else {
  203. $$fp_cnt++;
  204. }
  205. }
  206. elsif ( !$res->{'default'}->{$spam_symbol} ) {
  207. $$fn_cnt++;
  208. }
  209. else {
  210. $$detected_cnt++;
  211. }
  212. }
  213. else {
  214. if ( $res->{'default'}->{$spam_symbol} ) {
  215. my $m = $res->{'default'}->{$spam_symbol}->{'options'}->[0];
  216. if ( $m && $m =~ /^(\d+(?:\.\d+)?)%$/ ) {
  217. my $percentage = int($1);
  218. if ( $percentage >= $rspamc_prob_trigger ) {
  219. $$fp_cnt++;
  220. }
  221. }
  222. else {
  223. $$fp_cnt++;
  224. }
  225. }
  226. elsif ( !$res->{'default'}->{$ham_symbol} ) {
  227. $$fn_cnt++;
  228. }
  229. else {
  230. $$detected_cnt++;
  231. }
  232. }
  233. }
  234. }
  235. return $processed;
  236. }
  237. sub check_bogofilter {
  238. my ( $files, $spam, $fp_cnt, $fn_cnt, $detected_cnt ) = @_;
  239. my $processed = 0;
  240. foreach my $f ( @{$files} ) {
  241. my $args_quoted = shell_quote $f;
  242. open( my $p, "$bogofilter -t -I $args_quoted |" )
  243. or die "cannot spawn $bogofilter: $!";
  244. while (<$p>) {
  245. if ( $_ =~ /^([SHU])\s+.*$/ ) {
  246. $processed++;
  247. if ($spam) {
  248. if ( $1 eq 'H' ) {
  249. $$fp_cnt++;
  250. }
  251. elsif ( $1 eq 'U' ) {
  252. $$fn_cnt++;
  253. }
  254. else {
  255. $$detected_cnt++;
  256. }
  257. }
  258. else {
  259. if ( $1 eq 'S' ) {
  260. $$fp_cnt++;
  261. }
  262. elsif ( $1 eq 'U' ) {
  263. $$fn_cnt++;
  264. }
  265. else {
  266. $$detected_cnt++;
  267. }
  268. }
  269. }
  270. }
  271. }
  272. return $processed;
  273. }
  274. sub check_dspam {
  275. my ( $files, $spam, $fp_cnt, $fn_cnt, $detected_cnt ) = @_;
  276. my $processed = 0;
  277. foreach my $f ( @{$files} ) {
  278. my $args_quoted = shell_quote $f;
  279. my $pid = open2( *Reader, *Writer, "$dspam --user nobody --classify --stdout --mode=notrain" );
  280. open( my $inp, "< $f" );
  281. while (<$inp>) {
  282. print Writer $_;
  283. }
  284. close Writer;
  285. while (<Reader>) {
  286. if ( $_ =~ qr(^X-DSPAM-Result: nobody; result="([^"]+)"; class="[^"]+"; probability=(\d+(?:\.\d+)?).*$) ) {
  287. $processed++;
  288. my $percentage = int( $2 * 100.0 );
  289. if ($spam) {
  290. if ( $1 eq 'Innocent' ) {
  291. if ( $percentage <= ( 100 - $rspamc_prob_trigger ) ) {
  292. $$fp_cnt++;
  293. }
  294. }
  295. elsif ( $1 ne 'Spam' ) {
  296. $$fn_cnt++;
  297. }
  298. else {
  299. $$detected_cnt++;
  300. }
  301. }
  302. else {
  303. if ( $1 eq 'Spam' ) {
  304. if ( $percentage >= $rspamc_prob_trigger ) {
  305. $$fp_cnt++;
  306. }
  307. }
  308. elsif ( $1 ne 'Innocent' ) {
  309. $$fn_cnt++;
  310. }
  311. else {
  312. $$detected_cnt++;
  313. }
  314. }
  315. }
  316. }
  317. close Reader;
  318. waitpid( $pid, 0 );
  319. }
  320. return $processed;
  321. }
  322. sub cross_validate {
  323. my ($hr) = @_;
  324. my $args = "";
  325. my $processed = 0;
  326. my $fp_spam = 0;
  327. my $fn_spam = 0;
  328. my $fp_ham = 0;
  329. my $fn_ham = 0;
  330. my $total_spam = 0;
  331. my $total_ham = 0;
  332. my $detected_spam = 0;
  333. my $detected_ham = 0;
  334. my $i = 0;
  335. my $len = scalar keys %{$hr};
  336. my @files_spam;
  337. my @files_ham;
  338. my @cur_spam;
  339. my @cur_ham;
  340. my $check_func;
  341. if ($use_dspam) {
  342. $check_func = \&check_dspam;
  343. }
  344. elsif ($use_bogofilter) {
  345. $check_func = \&check_bogofilter;
  346. }
  347. else {
  348. $check_func = \&check_rspamc;
  349. }
  350. while ( my ( $fn, $spam ) = each( %{$hr} ) ) {
  351. if ($spam) {
  352. if ( scalar @cur_spam >= $parallel || $i == $len - 1 ) {
  353. push @cur_spam, $fn;
  354. push @files_spam, [@cur_spam];
  355. @cur_spam = ();
  356. }
  357. else {
  358. push @cur_spam, $fn;
  359. }
  360. }
  361. else {
  362. if ( scalar @cur_ham >= $parallel || $i == $len - 1 ) {
  363. push @cur_ham, $fn;
  364. push @files_ham, [@cur_ham];
  365. @cur_ham = ();
  366. }
  367. else {
  368. push @cur_ham, $fn;
  369. }
  370. }
  371. }
  372. shuffle_array( \@files_spam );
  373. foreach my $fn (@files_spam) {
  374. my $r = $check_func->( $fn, 1, \$fp_ham, \$fn_spam, \$detected_spam );
  375. $total_spam += $r;
  376. $processed += $r;
  377. }
  378. shuffle_array( \@files_ham );
  379. foreach my $fn (@files_ham) {
  380. my $r = $check_func->( $fn, 0, \$fp_spam, \$fn_ham, \$detected_ham );
  381. $total_ham += $r;
  382. $processed += $r;
  383. }
  384. printf "Scanned %d messages
  385. %d spam messages (%d detected)
  386. %d ham messages (%d detected)\n", $processed, $total_spam, $detected_spam, $total_ham, $detected_ham;
  387. printf "\nHam FP rate: %.2f%% (%d messages)
  388. Ham FN rate: %.2f%% (%d messages)\n", $fp_ham / $total_ham * 100.0, $fp_ham, $fn_ham / $total_ham * 100.0, $fn_ham;
  389. printf "\nSpam FP rate: %.2f%% (%d messages)
  390. Spam FN rate: %.2f%% (%d messages)\n",
  391. $fp_spam / $total_spam * 100.0, $fp_spam,
  392. $fn_spam / $total_spam * 100.0, $fn_spam;
  393. }
  394. if ( !$spam_dir || !$ham_dir ) {
  395. die "spam or/and ham directories are not specified";
  396. }
  397. my @spam_samples;
  398. my @ham_samples;
  399. read_dir_files( $spam_dir, \@spam_samples );
  400. read_dir_files( $ham_dir, \@ham_samples );
  401. shuffle_array( \@spam_samples );
  402. shuffle_array( \@ham_samples );
  403. if ( !$check_only ) {
  404. my $learned = 0;
  405. my $t0 = [gettimeofday];
  406. $learned = learn_samples( \@ham_samples, \@spam_samples );
  407. my $t1 = [gettimeofday];
  408. printf "Learned classifier, %d items processed, %.2f seconds elapsed\n", $learned, tv_interval( $t0, $t1 );
  409. }
  410. my %validation_set;
  411. my $len = int( scalar @spam_samples * $train_fraction );
  412. for ( my $i = $len ; $i < scalar @spam_samples ; $i++ ) {
  413. $validation_set{ $spam_samples[$i] } = 1;
  414. }
  415. $len = int( scalar @ham_samples * $train_fraction );
  416. for ( my $i = $len ; $i < scalar @spam_samples ; $i++ ) {
  417. $validation_set{ $ham_samples[$i] } = 0;
  418. }
  419. cross_validate( \%validation_set );
  420. __END__
  421. =head1 NAME
  422. classifier_test.pl - test various parameters for a classifier
  423. =head1 SYNOPSIS
  424. classifier_test.pl [options]
  425. Options:
  426. --spam Directory with spam files
  427. --ham Directory with ham files
  428. --spam-symbol Symbol for spam (default: BAYES_SPAM)
  429. --ham-symbol Symbol for ham (default: BAYES_HAM)
  430. --classifier Classifier to test (default: bayes)
  431. --timeout Timeout for rspamc (default: 10)
  432. --parallel Parallel execution (default: 1)
  433. --help Brief help message
  434. --man Full documentation
  435. =head1 OPTIONS
  436. =over 8
  437. =item B<--spam>
  438. Directory with spam files.
  439. =item B<--ham>
  440. Directory with ham files.
  441. =item B<--classifier>
  442. Specifies classifier name to test.
  443. =item B<--help>
  444. Print a brief help message and exits.
  445. =item B<--man>
  446. Prints the manual page and exits.
  447. =back
  448. =head1 DESCRIPTION
  449. B<classifier_test.pl> is intended to test Rspamd classifier for false positives, false negatives and other parameters.
  450. It uses half of the corpus for training and half for cross-validation.
  451. =cut