-
Notifications
You must be signed in to change notification settings - Fork 317
Expand file tree
/
Copy pathImportanceClassifier.php
More file actions
569 lines (512 loc) Β· 18.6 KB
/
ImportanceClassifier.php
File metadata and controls
569 lines (512 loc) Β· 18.6 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2020-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Mail\Service\Classification;
use Closure;
use Horde_Imap_Client;
use OCA\Mail\Account;
use OCA\Mail\Db\Mailbox;
use OCA\Mail\Db\MailboxMapper;
use OCA\Mail\Db\Message;
use OCA\Mail\Db\MessageMapper;
use OCA\Mail\Db\Tag;
use OCA\Mail\Db\TagMapper;
use OCA\Mail\Exception\ClassifierTrainingException;
use OCA\Mail\Exception\ServiceException;
use OCA\Mail\Model\Classifier;
use OCA\Mail\Model\ClassifierPipeline;
use OCA\Mail\Service\Classification\FeatureExtraction\CompositeExtractor;
use OCA\Mail\Service\Classification\FeatureExtraction\IExtractor;
use OCA\Mail\Support\PerformanceLogger;
use OCA\Mail\Support\PerformanceLoggerTask;
use OCP\AppFramework\Db\DoesNotExistException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Rubix\ML\Classifiers\KNearestNeighbors;
use Rubix\ML\CrossValidation\Reports\MulticlassBreakdown;
use Rubix\ML\Datasets\Labeled;
use Rubix\ML\Datasets\Unlabeled;
use Rubix\ML\Estimator;
use Rubix\ML\Kernels\Distance\Manhattan;
use Rubix\ML\Learner;
use Rubix\ML\Persistable;
use RuntimeException;
use function array_column;
use function array_combine;
use function array_filter;
use function array_map;
use function array_slice;
use function count;
use function json_encode;
/**
* Classify importance of messages
*
* This services uses machine learning techniques to guess the importance of in-
* coming messages. The training will be done in the background, so the actual
* classification can happen fast.
*
* To overcome the "cold start" problem there is also a fall-back mechanism of
* rule-based classification that is active as long as there are too few important
* messages to learn meaningful patterns of what the users typically considers
* as important.
*/
class ImportanceClassifier {
/**
* Mailbox special uses to exclude from the training
*/
private const EXEMPT_FROM_TRAINING = [
Horde_Imap_Client::SPECIALUSE_ALL,
Horde_Imap_Client::SPECIALUSE_DRAFTS,
Horde_Imap_Client::SPECIALUSE_FLAGGED,
Horde_Imap_Client::SPECIALUSE_JUNK,
Horde_Imap_Client::SPECIALUSE_SENT,
Horde_Imap_Client::SPECIALUSE_TRASH,
];
/**
* @var string label for data sets that are classified as important
*/
public const LABEL_IMPORTANT = 'i';
/**
* @var string label for data sets that are classified as not important
*/
public const LABEL_NOT_IMPORTANT = 'ni';
/**
* The minimum number of important messages. Without those the unsupervised
* training would yield random classification. Hence we switch to a rule-based
* classifier. This is known as the "cold start" problem.
*/
private const COLD_START_THRESHOLD = 20;
/**
* The maximum number of data sets to train the classifier with
*/
private const MAX_TRAINING_SET_SIZE = 300;
/** @var MailboxMapper */
private $mailboxMapper;
/** @var MessageMapper */
private $messageMapper;
/** @var PersistenceService */
private $persistenceService;
/** @var PerformanceLogger */
private $performanceLogger;
/** @var ImportanceRulesClassifier */
private $rulesClassifier;
private ContainerInterface $container;
private TagMapper $tagMapper;
public function __construct(MailboxMapper $mailboxMapper,
MessageMapper $messageMapper,
PersistenceService $persistenceService,
PerformanceLogger $performanceLogger,
ImportanceRulesClassifier $rulesClassifier,
ContainerInterface $container,
TagMapper $tagMapper) {
$this->mailboxMapper = $mailboxMapper;
$this->messageMapper = $messageMapper;
$this->persistenceService = $persistenceService;
$this->performanceLogger = $performanceLogger;
$this->rulesClassifier = $rulesClassifier;
$this->container = $container;
$this->tagMapper = $tagMapper;
}
private static function createDefaultEstimator(): KNearestNeighbors {
// A meta estimator was trained on the same data multiple times to average out the
// variance of the trained model.
// Parameters were chosen from the best configuration across 100 runs.
// Both variance (spread) and f1 score were considered.
// Note: Lower k values yield slightly higher f1 scores but show higher variances.
return new KNearestNeighbors(15, true, new Manhattan());
}
/**
* @throws ServiceException If the extractor is not available
*/
private function createExtractor(): CompositeExtractor {
try {
return $this->container->get(CompositeExtractor::class);
} catch (ContainerExceptionInterface $e) {
throw new ServiceException('Default extractor is not available', 0, $e);
}
}
private function filterMessageHasSenderEmail(Message $message): bool {
return $message->getFrom()->first() !== null && $message->getFrom()->first()->getEmail() !== null;
}
/**
* Build a data set for training an importance classifier.
*
* @param Account $account
* @param IExtractor $extractor
* @param LoggerInterface $logger
* @param PerformanceLoggerTask|null $perf
* @param bool $shuffle
* @return array|null Returns null if there are not enough messages to train
*/
public function buildDataSet(
Account $account,
IExtractor $extractor,
LoggerInterface $logger,
?PerformanceLoggerTask $perf = null,
bool $shuffle = false,
): ?array {
$perf ??= $this->performanceLogger->start('build data set for importance classifier training');
$incomingMailboxes = $this->getIncomingMailboxes($account);
$nIncoming = count($incomingMailboxes);
$logger->debug("found $nIncoming incoming mailbox(es)");
$perf->step('find incoming mailboxes');
$outgoingMailboxes = $this->getOutgoingMailboxes($account);
$nOutgoing = count($outgoingMailboxes);
$logger->debug("found $nOutgoing outgoing mailbox(es)");
$perf->step('find outgoing mailboxes');
$mailboxIds = array_map(static fn (Mailbox $mailbox) => $mailbox->getId(), $incomingMailboxes);
$messages = array_filter(
$this->messageMapper->findLatestMessages($account->getUserId(), $mailboxIds, self::MAX_TRAINING_SET_SIZE),
[$this, 'filterMessageHasSenderEmail']
);
// Drop messages whose importance flag was set by the classifier itself.
// We have no ground truth for these, so including them would let the
// classifier reinforce its own predictions over time.
$classifierTaggedIds = array_flip($this->tagMapper->getClassifierTaggedMessageIds(
$messages,
$account->getUserId(),
Tag::LABEL_IMPORTANT,
));
$autoTaggedDropped = 0;
$messages = array_filter($messages, static function (Message $message) use ($classifierTaggedIds, &$autoTaggedDropped) {
if (isset($classifierTaggedIds[$message->getMessageId()])) {
$autoTaggedDropped++;
return false;
}
return true;
});
$importantMessages = array_filter($messages, static fn (Message $message) => $message->getFlagImportant() === true);
$nMessages = count($messages);
$nImportant = count($importantMessages);
$logger->debug("found $nMessages messages of which $nImportant are important (dropped $autoTaggedDropped classifier-tagged messages)");
if (count($importantMessages) < self::COLD_START_THRESHOLD) {
$logger->info('not enough messages to train a classifier');
return null;
}
$perf->step('find latest ' . self::MAX_TRAINING_SET_SIZE . ' messages');
$dataSet = $this->getFeaturesAndImportance($account, $incomingMailboxes, $outgoingMailboxes, $messages, $extractor);
if ($shuffle) {
shuffle($dataSet);
}
return $dataSet;
}
/**
* Train an account's classifier of important messages
*
* Train a classifier based on a user's existing messages to be able to derive
* importance markers for new incoming messages.
*
* To factor in (server-side) filtering into multiple mailboxes, the algorithm
* will not only look for messages in the inbox but also other non-special
* mailboxes.
*
* To prevent memory exhaustion, the process will only load a fixed maximum
* number of messages per account.
*
* @param Account $account
* @param LoggerInterface $logger
* @param ?Closure $estimator Returned instance should at least implement Learner, Estimator and Persistable. If null, the default estimator will be used.
* @param bool $shuffleDataSet Shuffle the data set before training
* @param bool $persist Persist the trained classifier to use it for message classification
*
* @return ClassifierPipeline|null The validation estimator, persisted estimator (if `$persist` === true) or null in case none was trained
*
* @throws ServiceException
*/
public function train(
Account $account,
LoggerInterface $logger,
?Closure $estimator = null,
bool $shuffleDataSet = false,
bool $persist = true,
): ?ClassifierPipeline {
$perf = $this->performanceLogger->start('importance classifier training');
$extractor = $this->createExtractor();
$dataSet = $this->buildDataSet($account, $extractor, $logger, $perf, $shuffleDataSet);
if ($dataSet === null) {
return null;
}
return $this->trainWithCustomDataSet(
$account,
$logger,
$dataSet,
$extractor,
$estimator,
$perf,
$persist,
);
}
/**
* Train a classifier using a custom data set.
*
* @param Account $account
* @param LoggerInterface $logger
* @param array $dataSet Training data set built by buildDataSet()
* @param CompositeExtractor $extractor Extractor used to extract the given data set
* @param ?Closure $estimator Returned instance should at least implement Learner, Estimator and Persistable. If null, the default estimator will be used.
* @param PerformanceLoggerTask|null $perf Optionally reuse a performance logger task
* @param bool $persist Persist the trained classifier to use it for message classification
*
* @return ClassifierPipeline|null The validation estimator, persisted estimator (if `$persist` === true) or null in case none was trained
*
* @throws ServiceException
*/
private function trainWithCustomDataSet(
Account $account,
LoggerInterface $logger,
array $dataSet,
CompositeExtractor $extractor,
?Closure $estimator,
?PerformanceLoggerTask $perf = null,
bool $persist = true,
): ?ClassifierPipeline {
$perf ??= $this->performanceLogger->start('importance classifier training');
$estimator ??= self::createDefaultEstimator(...);
/**
* How many of the most recent messages are excluded from training?
*/
$validationThreshold = max(
5,
(int)((float)count($dataSet) * 0.2)
);
$validationSet = array_slice($dataSet, 0, $validationThreshold);
$trainingSet = array_slice($dataSet, $validationThreshold);
$validationSetImportantCount = 0;
$trainingSetImportantCount = 0;
foreach ($validationSet as $data) {
if ($data['label'] === self::LABEL_IMPORTANT) {
$validationSetImportantCount++;
}
}
foreach ($trainingSet as $data) {
if ($data['label'] === self::LABEL_IMPORTANT) {
$trainingSetImportantCount++;
}
}
$nTraining = count($trainingSet);
$nValidation = count($validationSet);
$nFeatures = count($trainingSet[0]['features'] ?? []);
$labelImportant = self::LABEL_IMPORTANT;
$logger->debug("data set split into $nTraining ($labelImportant: $trainingSetImportantCount) training and $nValidation ($labelImportant: $validationSetImportantCount) validation sets with $nFeatures dimensions");
if ($validationSet === [] || $trainingSet === []) {
$logger->info('not enough messages to train a classifier');
$perf->end();
return null;
}
/** @var Learner&Estimator&Persistable $validationEstimator */
$validationEstimator = $estimator();
$this->trainClassifier($validationEstimator, $validationSet);
try {
$classifier = $this->validateClassifier(
$validationEstimator,
$trainingSet,
$validationSet,
$logger
);
} catch (ClassifierTrainingException $e) {
$logger->error('Importance classifier training failed: ' . $e->getMessage(), [
'exception' => $e,
]);
$perf->end();
return null;
}
$perf->step('train and validate classifier with training and validation sets');
if (!$persist) {
return new ClassifierPipeline($validationEstimator, $extractor);
}
/** @var Learner&Estimator&Persistable $persistedEstimator */
$persistedEstimator = $estimator();
$this->trainClassifier($persistedEstimator, $dataSet);
$perf->step('train classifier with full data set');
$classifier->setDuration($perf->end());
$classifier->setAccountId($account->getId());
$classifier->setEstimator(get_class($persistedEstimator));
$classifier->setPersistenceVersion(PersistenceService::VERSION);
$this->persistenceService->persist($account, $persistedEstimator, $extractor);
$logger->debug("Classifier for account {$account->getId()} persisted", [
'classifier' => $classifier,
]);
return new ClassifierPipeline($persistedEstimator, $extractor);
}
/**
* @param Account $account
*
* @return Mailbox[]
*/
private function getIncomingMailboxes(Account $account): array {
return array_filter($this->mailboxMapper->findAll($account), static function (Mailbox $mailbox) {
foreach (self::EXEMPT_FROM_TRAINING as $excluded) {
if ($mailbox->isSpecialUse($excluded)) {
return false;
}
}
return true;
});
}
/**
* @param Account $account
*
* @return Mailbox[]
* @todo allow more than one outgoing mailbox
*/
private function getOutgoingMailboxes(Account $account): array {
try {
$sentMailboxId = $account->getMailAccount()->getSentMailboxId();
if ($sentMailboxId === null) {
return [];
}
return [
$this->mailboxMapper->findById($sentMailboxId)
];
} catch (DoesNotExistException $e) {
return [];
}
}
/**
* Get the feature vector of every message
*
* @param Account $account
* @param Mailbox[] $incomingMailboxes
* @param Mailbox[] $outgoingMailboxes
* @param Message[] $messages
*
* @return array
*/
private function getFeaturesAndImportance(Account $account,
array $incomingMailboxes,
array $outgoingMailboxes,
array $messages,
IExtractor $extractor): array {
$extractor->prepare($account, $incomingMailboxes, $outgoingMailboxes, $messages);
return array_map(static function (Message $message) use ($extractor) {
$sender = $message->getFrom()->first();
if ($sender === null) {
throw new RuntimeException('This should not happen');
}
$features = $extractor->extract($message);
return [
'features' => $features,
'label' => $message->getFlagImportant() ? self::LABEL_IMPORTANT : self::LABEL_NOT_IMPORTANT,
'sender' => $sender->getEmail(),
];
}, $messages);
}
/**
* @param Account $account
* @param Message[] $messages
* @param LoggerInterface $logger
*
* @return bool[]
*
* @throws ServiceException
*/
public function classifyImportance(Account $account,
array $messages,
LoggerInterface $logger): array {
$pipeline = null;
try {
$pipeline = $this->persistenceService->loadLatest($account);
} catch (ServiceException $e) {
$logger->warning('Failed to load persisted estimator and extractor: ' . $e->getMessage(), [
'exception' => $e,
]);
}
// Persistence is disabled on some instances (due to no memory cache being available).
// Try to train a classifier on-the-fly on those instances.
if ($pipeline === null) {
$pipeline = $this->train($account, $logger);
}
// Can't train pipeline and no persistence available? -> Skip rule based classifier ...
// It won't yield good results. Instead, we have to wait for the user to accumulate more
// emails so that training a classifier succeeds.
if ($pipeline === null && !$this->persistenceService->isAvailable()) {
return [];
}
if ($pipeline === null) {
$predictions = $this->rulesClassifier->classifyImportance(
$account,
$this->getIncomingMailboxes($account),
$this->getOutgoingMailboxes($account),
$messages
);
return array_combine(
array_map(static fn (Message $m) => $m->getUid(), $messages),
array_map(static fn (Message $m) => ($predictions[$m->getUid()] ?? false) === true, $messages)
);
}
$messagesWithSender = array_filter($messages, [$this, 'filterMessageHasSenderEmail']);
$features = $this->getFeaturesAndImportance(
$account,
$this->getIncomingMailboxes($account),
$this->getOutgoingMailboxes($account),
$messagesWithSender,
$pipeline->getExtractor(),
);
$predictions = $pipeline->getEstimator()->predict(
Unlabeled::build(array_column($features, 'features'))
);
return array_combine(
array_map(static fn (Message $m) => $m->getUid(), $messagesWithSender),
array_map(static fn ($p) => $p === self::LABEL_IMPORTANT, $predictions)
);
}
private function trainClassifier(Learner $classifier, array $trainingSet): void {
$classifier->train(Labeled::build(
array_column($trainingSet, 'features'),
array_column($trainingSet, 'label')
));
}
/**
* @param Estimator $estimator
* @param array $trainingSet
* @param array $validationSet
* @param LoggerInterface $logger
*
* @return Classifier
*/
private function validateClassifier(Estimator $estimator,
array $trainingSet,
array $validationSet,
LoggerInterface $logger): Classifier {
/** @var float[] $predictedValidationLabel */
$predictedValidationLabel = $estimator->predict(Unlabeled::build(
array_column($validationSet, 'features')
));
$reporter = new MulticlassBreakdown();
$report = $reporter->generate(
$predictedValidationLabel,
array_column($validationSet, 'label')
);
$recallImportant = $report['classes'][self::LABEL_IMPORTANT]['recall'] ?? 0;
$precisionImportant = $report['classes'][self::LABEL_IMPORTANT]['precision'] ?? 0;
$f1ScoreImportant = $report['classes'][self::LABEL_IMPORTANT]['f1 score'] ?? 0;
/**
* What we care most is the percentage of messages classified as important in relation to the truly important messages
* as we want to have a classification that rather flags too much as important that too little.
*
* The f1 score tells us how balanced the results are, as in, if the classifier blindly detects messages as important
* or if there is some a pattern it.
*
* Ref https://en.wikipedia.org/wiki/Precision_and_recall
* Ref https://en.wikipedia.org/wiki/F1_score
*/
$logger->debug('classification report: ' . json_encode([
'recall' => $recallImportant,
'precision' => $precisionImportant,
'f1Score' => $f1ScoreImportant,
]));
$logger->debug("classifier validated: recall(important)=$recallImportant, precision(important)=$precisionImportant f1(important)=$f1ScoreImportant");
$classifier = new Classifier();
$classifier->setType(Classifier::TYPE_IMPORTANCE);
$classifier->setTrainingSetSize(count($trainingSet));
$classifier->setValidationSetSize(count($validationSet));
$classifier->setRecallImportant($recallImportant);
$classifier->setPrecisionImportant($precisionImportant);
$classifier->setF1ScoreImportant($f1ScoreImportant);
return $classifier;
}
}