This repository has been archived by the owner on Jul 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.php
85 lines (68 loc) · 2.32 KB
/
train.php
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
<?php
include __DIR__ . '/vendor/autoload.php';
use Rubix\ML\Datasets\Labeled;
use Rubix\ML\PersistentModel;
use Rubix\ML\Pipeline;
use Rubix\ML\Transformers\HTMLStripper;
use Rubix\ML\Transformers\TextNormalizer;
use Rubix\ML\Transformers\WordCountVectorizer;
use Rubix\ML\Other\Tokenizers\NGram;
use Rubix\ML\Transformers\TfIdfTransformer;
use Rubix\ML\Transformers\ZScaleStandardizer;
use Rubix\ML\Classifiers\MultiLayerPerceptron;
use Rubix\ML\NeuralNet\Layers\Dense;
use Rubix\ML\NeuralNet\Layers\Activation;
use Rubix\ML\NeuralNet\Layers\PReLU;
use Rubix\ML\NeuralNet\Layers\BatchNorm;
use Rubix\ML\NeuralNet\ActivationFunctions\LeakyReLU;
use Rubix\ML\NeuralNet\Optimizers\AdaMax;
use Rubix\ML\Persisters\Filesystem;
use Rubix\ML\Other\Loggers\Screen;
use League\Csv\Writer;
use function Rubix\ML\array_transpose;
ini_set('memory_limit', '-1');
echo 'Loading data into memory ...' . PHP_EOL;
$samples = $labels = [];
foreach (glob('train/pos/*.txt') as $file) {
$samples[] = [file_get_contents($file)];
$labels[] = 'positive';
}
foreach (glob('train/neg/*.txt') as $file) {
$samples[] = [file_get_contents($file)];
$labels[] = 'negative';
}
$dataset = Labeled::build($samples, $labels);
$estimator = new PersistentModel(
new Pipeline([
new HTMLStripper(),
new TextNormalizer(),
new WordCountVectorizer(10000, 3, new NGram(1, 2)),
new TfIdfTransformer(),
new ZScaleStandardizer(),
], new MultiLayerPerceptron([
new Dense(100),
new Activation(new LeakyReLU()),
new Dense(100),
new Activation(new LeakyReLU()),
new Dense(100),
new BatchNorm(),
new Activation(new LeakyReLU()),
new Dense(50),
new PReLU(),
new Dense(50),
new PReLU(),
], 200, new AdaMax(0.0001))),
new Filesystem('sentiment.model', true)
);
$estimator->setLogger(new Screen('sentiment'));
echo 'Training ...' . PHP_EOL;
$estimator->train($dataset);
$scores = $estimator->scores();
$losses = $estimator->steps();
$writer = Writer::createFromPath('progress.csv', 'w+');
$writer->insertOne(['score', 'loss']);
$writer->insertAll(array_transpose([$scores, $losses]));
echo 'Progress saved to progress.csv' . PHP_EOL;
if (strtolower(trim(readline('Save this model? (y|[n]): '))) === 'y') {
$estimator->save();
}