/
TfIdfTransformer.php
242 lines (210 loc) · 5.98 KB
/
TfIdfTransformer.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
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
<?php
namespace Rubix\ML\Transformers;
use Rubix\ML\DataType;
use Rubix\ML\Persistable;
use Rubix\ML\Helpers\Params;
use Rubix\ML\Datasets\Dataset;
use Rubix\ML\Traits\AutotrackRevisions;
use Rubix\ML\Specifications\DatasetIsNotEmpty;
use Rubix\ML\Specifications\SpecificationChain;
use Rubix\ML\Specifications\SamplesAreCompatibleWithTransformer;
use Rubix\ML\Exceptions\InvalidArgumentException;
use Rubix\ML\Exceptions\RuntimeException;
use function array_fill;
use function log;
/**
* TF-IDF Transformer
*
* Term Frequency - Inverse Document Frequency is a measure of how important a word is to
* a document. The TF-IDF value increases with the number of times a word appears in a document
* and is offset by the frequency of the word in the corpus.
*
* > **Note**: TF-IDF Transformer assumes that its input is made up of term frequency
* vectors such as those created by Word Count or Token Hashing Vectorizer.
*
* References:
* [1] S. Robertson. (2003). Understanding Inverse Document Frequency: On theoretical
* arguments for IDF.
* [2] C. D. Manning et al. (2009). An Introduction to Information Retrieval.
*
* @category Machine Learning
* @package Rubix/ML
* @author Andrew DalPino
*/
class TfIdfTransformer implements Transformer, Stateful, Elastic, Reversible, Persistable
{
use AutotrackRevisions;
/**
* The amount of additive (Laplace) smoothing to add to the IDFs.
*
* @var float
*/
protected float $smoothing;
/**
* Should we apply a sub-linear function to dampen the effect of recurring tokens?
*
* @var bool
*/
protected bool $dampening;
/**
* The document frequencies of each word i.e. the number of times a word appeared in a document.
*
* @var int[]|null
*/
protected ?array $dfs = null;
/**
* The inverse document frequencies for each feature column.
*
* @var float[]|null
*/
protected ?array $idfs = null;
/**
* The number of documents (samples) that have been fitted so far.
*
* @var int
*/
protected int $n = 0;
/**
* @param float $smoothing
* @param bool $dampening
* @throws InvalidArgumentException
*/
public function __construct(float $smoothing = 1.0, bool $dampening = false)
{
if ($smoothing <= 0.0) {
throw new InvalidArgumentException('Smoothing must be'
. " greater than 0, $smoothing given.");
}
$this->smoothing = $smoothing;
$this->dampening = $dampening;
}
/**
* Return the data types that this transformer is compatible with.
*
* @internal
*
* @return list<\Rubix\ML\DataType>
*/
public function compatibility() : array
{
return [
DataType::continuous(),
];
}
/**
* Is the transformer fitted?
*
* @return bool
*/
public function fitted() : bool
{
return isset($this->idfs);
}
/**
* Return the document frequencies calculated during fitting.
*
* @return int[]|null
*/
public function dfs() : ?array
{
return $this->dfs;
}
/**
* Fit the transformer to a dataset.
*
* @param Dataset $dataset
*/
public function fit(Dataset $dataset) : void
{
$this->dfs = array_fill(0, $dataset->numFeatures(), 0);
$this->n = 0;
$this->update($dataset);
}
/**
* Update the fitting of the transformer.
*
* @param Dataset $dataset
* @throws InvalidArgumentException
*/
public function update(Dataset $dataset) : void
{
SpecificationChain::with([
new DatasetIsNotEmpty($dataset),
new SamplesAreCompatibleWithTransformer($dataset, $this),
])->check();
if ($this->dfs === null) {
$this->fit($dataset);
return;
}
foreach ($dataset->samples() as $sample) {
foreach ($sample as $column => $value) {
if ($value > 0) {
++$this->dfs[$column];
}
}
}
$this->n += $dataset->numSamples();
$nHat = $this->n + $this->smoothing;
$idfs = [];
foreach ($this->dfs as $df) {
$idfs[] = 1.0 + log($nHat / ($df + $this->smoothing));
}
$this->idfs = $idfs;
}
/**
* Transform the dataset in place.
*
* @param list<list<mixed>> $samples
* @throws RuntimeException
*/
public function transform(array &$samples) : void
{
if ($this->idfs === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
foreach ($sample as $column => &$value) {
if ($value > 0) {
if ($this->dampening) {
$value = 1.0 + log($value);
}
$value *= $this->idfs[$column];
}
}
}
}
/**
* Perform the reverse transformation to the samples.
*
* @param list<list<mixed>> $samples
* @throws RuntimeException
*/
public function reverseTransform(array &$samples) : void
{
if ($this->idfs === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
foreach ($sample as $column => &$value) {
if ($value > 0) {
$value /= $this->idfs[$column];
if ($this->dampening) {
$value = exp($value - 1.0);
}
}
}
}
}
/**
* Return the string representation of the object.
*
* @internal
*
* @return string
*/
public function __toString() : string
{
return "TF-IDF Transformer (smoothing: {$this->smoothing}, dampening: "
. Params::toString($this->dampening) . ')';
}
}