classifier 2.6.0 → 2.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +174 -0
- data/README.md +177 -13
- data/docs/README.md +49 -0
- data/docs/bayes.md +108 -0
- data/docs/cli.md +295 -0
- data/docs/configuration.md +100 -0
- data/docs/keywords.md +171 -0
- data/docs/knn.md +92 -0
- data/docs/logistic-regression.md +107 -0
- data/docs/lsi.md +219 -0
- data/docs/persistence.md +124 -0
- data/docs/streaming.md +104 -0
- data/docs/tfidf.md +137 -0
- data/exe/classifier +0 -1
- data/exe/keywords +15 -0
- data/ext/classifier/extconf.rb +1 -2
- data/lib/classifier/bayes.rb +12 -3
- data/lib/classifier/cli.rb +3 -5
- data/lib/classifier/extensions/word_hash.rb +20 -0
- data/lib/classifier/keywords/cli.rb +299 -0
- data/lib/classifier/logistic_regression.rb +1 -2
- data/lib/classifier/lsi.rb +3 -3
- data/lib/classifier/streaming/line_reader.rb +9 -7
- data/lib/classifier/streaming/multi_io.rb +51 -0
- data/lib/classifier/streaming.rb +1 -0
- data/lib/classifier/tfidf.rb +3 -2
- data/lib/classifier/version.rb +1 -1
- metadata +19 -4
- data/CLAUDE.md +0 -77
data/docs/cli.md
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
# classifier
|
|
2
|
+
|
|
3
|
+
`classifier` trains and runs text classifiers from the shell. For term scores
|
|
4
|
+
rather than categories, use [`keywords`](keywords.md).
|
|
5
|
+
|
|
6
|
+
## Pre-trained models
|
|
7
|
+
|
|
8
|
+
The `-r` flag pulls a model from the registry, so classification works with no
|
|
9
|
+
training:
|
|
10
|
+
|
|
11
|
+
```console
|
|
12
|
+
$ classifier -r sms-spam-filter "You won a free iPhone"
|
|
13
|
+
spam
|
|
14
|
+
|
|
15
|
+
$ classifier -r imdb-sentiment "This movie was absolutely amazing"
|
|
16
|
+
positive
|
|
17
|
+
|
|
18
|
+
$ classifier models
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Train your own
|
|
22
|
+
|
|
23
|
+
```console
|
|
24
|
+
$ classifier train positive reviews/good/*.txt
|
|
25
|
+
$ classifier train negative reviews/bad/*.txt
|
|
26
|
+
|
|
27
|
+
$ classifier "Great product, highly recommend"
|
|
28
|
+
positive
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Training reads standard input when you name no file:
|
|
32
|
+
|
|
33
|
+
```console
|
|
34
|
+
$ echo "amazing fantastic" | classifier train positive
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The default model file is `./classifier.json`. Use `-f` for any other path. Each
|
|
38
|
+
`train` call updates that file in place.
|
|
39
|
+
|
|
40
|
+
## Probabilities
|
|
41
|
+
|
|
42
|
+
```console
|
|
43
|
+
$ classifier -p "Great product, highly recommend"
|
|
44
|
+
positive:0.89 negative:0.11
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Model information
|
|
48
|
+
|
|
49
|
+
```console
|
|
50
|
+
$ classifier info
|
|
51
|
+
{
|
|
52
|
+
"file": "./classifier.json",
|
|
53
|
+
"type": "bayes",
|
|
54
|
+
"categories": [
|
|
55
|
+
"Positive",
|
|
56
|
+
"Negative"
|
|
57
|
+
],
|
|
58
|
+
"category_stats": {
|
|
59
|
+
"Positive": {
|
|
60
|
+
"unique_words": 7,
|
|
61
|
+
"total_words": 7
|
|
62
|
+
},
|
|
63
|
+
"Negative": {
|
|
64
|
+
"unique_words": 7,
|
|
65
|
+
"total_words": 7
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Other classifiers
|
|
72
|
+
|
|
73
|
+
`-m` selects the algorithm. The default is `bayes`.
|
|
74
|
+
|
|
75
|
+
```console
|
|
76
|
+
$ classifier -m knn -k 3 train tech docs/tech/*.txt
|
|
77
|
+
$ classifier -m lr train positive reviews/good/*.txt
|
|
78
|
+
$ classifier -m lsi train dogs corpus/dogs/*.txt
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Logistic regression needs a fit step after training:
|
|
82
|
+
|
|
83
|
+
```console
|
|
84
|
+
$ classifier -m lr train positive reviews/good/*.txt
|
|
85
|
+
$ classifier -m lr train negative reviews/bad/*.txt
|
|
86
|
+
$ classifier -m lr fit
|
|
87
|
+
Model fitted successfully
|
|
88
|
+
$ classifier -m lr "I love it"
|
|
89
|
+
positive
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Search and related documents
|
|
93
|
+
|
|
94
|
+
These two commands need an LSI model.
|
|
95
|
+
|
|
96
|
+
```console
|
|
97
|
+
$ classifier -m lsi search "machine learning"
|
|
98
|
+
$ classifier -m lsi related article.txt
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`-n` sets how many results come back. The default is 10.
|
|
102
|
+
|
|
103
|
+
## Commands
|
|
104
|
+
|
|
105
|
+
| Command | Action |
|
|
106
|
+
|:--|:--|
|
|
107
|
+
| `train <category> [files...]` | Train a category from files or standard input |
|
|
108
|
+
| `info` | Print model information |
|
|
109
|
+
| `fit` | Fit the model. Logistic regression only |
|
|
110
|
+
| `search <query>` | Semantic search. LSI only |
|
|
111
|
+
| `related <item>` | Find related documents. LSI only |
|
|
112
|
+
| `models [registry]` | List the models in a registry |
|
|
113
|
+
| `pull <model>` | Download a model from the registry |
|
|
114
|
+
| `push <file>` | Contribute a model to the registry |
|
|
115
|
+
| `<text>` | Classify the text. The default action |
|
|
116
|
+
|
|
117
|
+
## Options
|
|
118
|
+
|
|
119
|
+
| Option | Meaning |
|
|
120
|
+
|:--|:--|
|
|
121
|
+
| `-f`, `--file FILE` | Model file. Default `./classifier.json` |
|
|
122
|
+
| `-m`, `--model TYPE` | Algorithm: `bayes`, `lsi`, `knn`, or `lr`. Default `bayes` |
|
|
123
|
+
| `-r`, `--remote MODEL` | Use a remote model, by name or `@user/repo:name` |
|
|
124
|
+
| `--search TEXT` | Search remote models by name and description, and local models by name |
|
|
125
|
+
| `-o`, `--output FILE` | Output path for `pull` |
|
|
126
|
+
| `-p` | Print probabilities |
|
|
127
|
+
| `-n`, `--count N` | Result count for `search` and `related`. Default 10 |
|
|
128
|
+
| `-k`, `--neighbors N` | Neighbor count for kNN. Default 5 |
|
|
129
|
+
| `--weighted` | Use distance-weighted voting for kNN |
|
|
130
|
+
| `--learning-rate N` | Learning rate for logistic regression. Default 0.1 |
|
|
131
|
+
| `--regularization N` | L2 regularization for logistic regression. Default 0.01 |
|
|
132
|
+
| `--max-iterations N` | Maximum iterations for logistic regression. Default 100 |
|
|
133
|
+
| `-q` | Quiet mode |
|
|
134
|
+
| `--local` | List locally cached models, with the `models` command |
|
|
135
|
+
| `-v`, `--version` | Print the gem version |
|
|
136
|
+
| `-h`, `--help` | Print the full usage |
|
|
137
|
+
|
|
138
|
+
## Using both commands together
|
|
139
|
+
|
|
140
|
+
`classifier` and `keywords` answer different questions about the same text.
|
|
141
|
+
`classifier` gives a category. `keywords` names the terms that make the text
|
|
142
|
+
distinctive against its corpus. Run them side by side to read a label together
|
|
143
|
+
with what the document is about.
|
|
144
|
+
|
|
145
|
+
Fit a vocabulary from the same corpus you train on, and the two views line up:
|
|
146
|
+
|
|
147
|
+
```console
|
|
148
|
+
$ keywords fit -m reviews.json reviews/good/*.txt reviews/bad/*.txt
|
|
149
|
+
$ keywords info -m reviews.json
|
|
150
|
+
Documents: 8
|
|
151
|
+
Vocabulary: 37
|
|
152
|
+
Min DF: 1
|
|
153
|
+
Max DF: 1.0
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
`keywords info` reports the corpus before you commit to training. A vocabulary
|
|
157
|
+
of 37 terms over 8 documents says the corpus is far too small, and no
|
|
158
|
+
classifier fixes that.
|
|
159
|
+
|
|
160
|
+
Then train, and read the two answers together:
|
|
161
|
+
|
|
162
|
+
```console
|
|
163
|
+
$ classifier -f reviews-model.json train positive reviews/good/*.txt
|
|
164
|
+
$ classifier -f reviews-model.json train negative reviews/bad/*.txt
|
|
165
|
+
|
|
166
|
+
$ classifier -f reviews-model.json -p "Broken on arrival, awful quality and useless customer service"
|
|
167
|
+
positive:0.07 negative:0.93
|
|
168
|
+
|
|
169
|
+
$ keywords -m reviews.json -n 5 "Broken on arrival, awful quality and useless customer service"
|
|
170
|
+
useless:0.4 awful:0.4 arrival:0.4 broken:0.4 service:0.34
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The first line is the verdict. The second is the document in shorthand, which
|
|
174
|
+
tells you what the classifier was reading when a result surprises you.
|
|
175
|
+
|
|
176
|
+
**The second line is not an explanation of the first.** The two commands hold
|
|
177
|
+
separate models. `keywords` reports TF-IDF weight, which measures how well a
|
|
178
|
+
term separates this document from the rest of the corpus. It never sees the
|
|
179
|
+
classifier, and it does not know which category a term favors. A term can top
|
|
180
|
+
the list and carry no weight in the decision.
|
|
181
|
+
|
|
182
|
+
Read it as context, not as attribution. When a label looks wrong, the terms
|
|
183
|
+
tell you whether the document says what you assumed, which is usually the real
|
|
184
|
+
problem. For the weights a model actually holds, use
|
|
185
|
+
`Classifier::LogisticRegression#weights` from Ruby, which returns the learned
|
|
186
|
+
weight per term and per category:
|
|
187
|
+
|
|
188
|
+
```ruby
|
|
189
|
+
classifier.weights("positive", limit: 5)
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
No command line flag reports per-term weights for a Bayes model.
|
|
193
|
+
|
|
194
|
+
### Find the words your corpus wastes on itself
|
|
195
|
+
|
|
196
|
+
A term that appears in nearly every document tells a classifier nothing, and
|
|
197
|
+
every corpus grows its own. A review corpus repeats `delivery`, a support
|
|
198
|
+
corpus repeats `ticket`. These are stopwords that no general stopword list
|
|
199
|
+
knows about, because they are specific to your data.
|
|
200
|
+
|
|
201
|
+
`keywords` finds them, because `--max-df` drops a term that appears in more
|
|
202
|
+
than the given ratio of documents. Compare the vocabulary size before and
|
|
203
|
+
after:
|
|
204
|
+
|
|
205
|
+
```console
|
|
206
|
+
$ keywords fit -m default.json good.txt bad.txt
|
|
207
|
+
$ keywords info -m default.json
|
|
208
|
+
Documents: 12
|
|
209
|
+
Vocabulary: 42
|
|
210
|
+
|
|
211
|
+
$ keywords fit -m pruned.json --max-df 0.5 good.txt bad.txt
|
|
212
|
+
$ keywords info -m pruned.json
|
|
213
|
+
Documents: 12
|
|
214
|
+
Vocabulary: 41
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
One term went. Score a document under each model to see which:
|
|
218
|
+
|
|
219
|
+
```console
|
|
220
|
+
$ keywords -m default.json -n 3 "delivery was awful and broken"
|
|
221
|
+
broken:0.69 awful:0.69 delivery:0.24
|
|
222
|
+
|
|
223
|
+
$ keywords -m pruned.json -n 3 "delivery was awful and broken"
|
|
224
|
+
broken:0.71 awful:0.71
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
`delivery` sat in all 12 documents and still drew weight. Dropping it sharpens
|
|
228
|
+
every term that carries real signal.
|
|
229
|
+
|
|
230
|
+
Watch the vocabulary count as you tune, because these bounds cut fast:
|
|
231
|
+
|
|
232
|
+
```console
|
|
233
|
+
$ keywords fit -m tight.json --min-df 2 good.txt bad.txt
|
|
234
|
+
$ keywords info -m tight.json
|
|
235
|
+
Documents: 12
|
|
236
|
+
Vocabulary: 7
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`--min-df 2` took 42 terms down to 7. That is no longer a vocabulary, it is a
|
|
240
|
+
handful of words. Move one bound at a time and read `keywords info` after each
|
|
241
|
+
change.
|
|
242
|
+
|
|
243
|
+
### Two commands, two models
|
|
244
|
+
|
|
245
|
+
The models are separate files in separate formats, and neither command reads
|
|
246
|
+
the other's:
|
|
247
|
+
|
|
248
|
+
```console
|
|
249
|
+
$ classifier -f reviews.json "broken awful"
|
|
250
|
+
Error: Unknown classifier type in model: tfidf
|
|
251
|
+
|
|
252
|
+
$ keywords -m reviews-model.json "broken awful"
|
|
253
|
+
Error: Invalid vectorizer type: bayes
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Note the flags differ too. `classifier` takes `-f`, and `keywords` takes `-m`.
|
|
257
|
+
|
|
258
|
+
| | `classifier` | `keywords` |
|
|
259
|
+
|:--|:--|:--|
|
|
260
|
+
| Answers | Which category | Which terms matter |
|
|
261
|
+
| Model flag | `-f` | `-m` |
|
|
262
|
+
| Default model | `./classifier.json` | `./keywords.json` |
|
|
263
|
+
| Builds a model with | `train` | `fit` |
|
|
264
|
+
| Pre-trained models | Yes, through `-r` | No |
|
|
265
|
+
|
|
266
|
+
### Do not pipe one into the other
|
|
267
|
+
|
|
268
|
+
`keywords` prints `term:score` pairs, which is not text to classify. Feeding
|
|
269
|
+
its output to `classifier` throws away the rest of the document and weakens the
|
|
270
|
+
result:
|
|
271
|
+
|
|
272
|
+
```console
|
|
273
|
+
$ classifier -f reviews-model.json -p "$LONG_REVIEW"
|
|
274
|
+
positive:0.08 negative:0.92 # the whole review
|
|
275
|
+
|
|
276
|
+
$ keywords -m reviews.json -n 4 "$LONG_REVIEW"
|
|
277
|
+
arrived:0.6 refund:0.3 useless:0.3 build:0.3
|
|
278
|
+
|
|
279
|
+
$ classifier -f reviews-model.json -p "arrived refund useless build"
|
|
280
|
+
positive:0.21 negative:0.79 # weaker, from the top terms alone
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
Confidence drops from 0.92 to 0.79. TF-IDF ranks a term by how much it
|
|
284
|
+
distinguishes one document from the rest of the corpus, which is not the same
|
|
285
|
+
as how much it signals a category. Here it puts `arrived` first, a neutral
|
|
286
|
+
word about delivery. Classify the full text, and read `keywords` alongside it
|
|
287
|
+
for context rather than for attribution.
|
|
288
|
+
|
|
289
|
+
## Install without Ruby
|
|
290
|
+
|
|
291
|
+
Homebrew installs the command line tools on their own:
|
|
292
|
+
|
|
293
|
+
```bash
|
|
294
|
+
brew install classifier
|
|
295
|
+
```
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# Configuration
|
|
2
|
+
|
|
3
|
+
## Global settings
|
|
4
|
+
|
|
5
|
+
`Classifier.configure` sets the defaults for every classifier:
|
|
6
|
+
|
|
7
|
+
```ruby
|
|
8
|
+
require "classifier"
|
|
9
|
+
|
|
10
|
+
Classifier.configure do |config|
|
|
11
|
+
config.min_word_length = 2
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
Classifier.config.min_word_length
|
|
15
|
+
# => 2
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
| Setting | Default | Effect |
|
|
19
|
+
|:--|:--|:--|
|
|
20
|
+
| `min_word_length` | 3 | The tokenizer drops any word shorter than this |
|
|
21
|
+
|
|
22
|
+
Set the configuration once at startup. The lazy setup is not thread-safe, so do
|
|
23
|
+
not first touch it from several threads at once.
|
|
24
|
+
|
|
25
|
+
Every classifier also takes `min_word_length` on its own, which overrides the
|
|
26
|
+
global value:
|
|
27
|
+
|
|
28
|
+
```ruby
|
|
29
|
+
Classifier::Bayes.new(:spam, :ham, min_word_length: 2)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Tokenization
|
|
33
|
+
|
|
34
|
+
The tokenizer downcases the text, strips punctuation, drops the stop words in
|
|
35
|
+
`CORPUS_SKIP_WORDS`, drops words shorter than `min_word_length`, and reduces
|
|
36
|
+
each remaining word to its Porter stem.
|
|
37
|
+
|
|
38
|
+
```ruby
|
|
39
|
+
"Ruby programming is elegant".word_hash
|
|
40
|
+
# => {rubi: 1, program: 1, eleg: 1}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`clean_word_hash` skips the punctuation strip when the text is already clean.
|
|
44
|
+
`stem_to_word_hash` maps each stem back to the most frequent original word:
|
|
45
|
+
|
|
46
|
+
```ruby
|
|
47
|
+
"Ruby programming is elegant and programming rocks".stem_to_word_hash
|
|
48
|
+
# => {rubi: "ruby", program: "programming", eleg: "elegant", rock: "rocks"}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Native extension
|
|
52
|
+
|
|
53
|
+
LSI uses a C extension for its linear algebra. It has no external dependency
|
|
54
|
+
and builds during `gem install`. Pure Ruby runs when the extension is absent,
|
|
55
|
+
with the same results and less speed.
|
|
56
|
+
|
|
57
|
+
```ruby
|
|
58
|
+
Classifier::LSI.backend
|
|
59
|
+
# => :native
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The value is `:native` or `:ruby`.
|
|
63
|
+
|
|
64
|
+
Force pure Ruby with an environment variable, which is useful to compare the
|
|
65
|
+
two:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
NATIVE_VECTOR=true bundle exec rake test
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Build the extension from a checkout:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
bundle exec rake compile
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Silence the startup notice about the missing extension:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
SUPPRESS_LSI_WARNING=true
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Errors
|
|
84
|
+
|
|
85
|
+
Every error inherits from `Classifier::Error`.
|
|
86
|
+
|
|
87
|
+
| Error | Raised when |
|
|
88
|
+
|:--|:--|
|
|
89
|
+
| `Classifier::NotFittedError` | A model is used before its fit. Logistic regression and TF-IDF |
|
|
90
|
+
| `Classifier::UnsavedChangesError` | `reload!` would discard unsaved changes |
|
|
91
|
+
| `Classifier::StorageError` | A storage backend operation fails |
|
|
92
|
+
|
|
93
|
+
```ruby
|
|
94
|
+
begin
|
|
95
|
+
classifier.classify("text")
|
|
96
|
+
rescue Classifier::NotFittedError
|
|
97
|
+
classifier.fit
|
|
98
|
+
retry
|
|
99
|
+
end
|
|
100
|
+
```
|
data/docs/keywords.md
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# keywords
|
|
2
|
+
|
|
3
|
+
`keywords` scores the terms of a text with TF-IDF. It prints `term:score` pairs
|
|
4
|
+
in descending order of score.
|
|
5
|
+
|
|
6
|
+
The gem installs this command next to `classifier`.
|
|
7
|
+
|
|
8
|
+
## A model comes first
|
|
9
|
+
|
|
10
|
+
`keywords` ships no pre-trained models. Build a vocabulary before you score any
|
|
11
|
+
text:
|
|
12
|
+
|
|
13
|
+
```console
|
|
14
|
+
$ keywords fit corpus/*.txt
|
|
15
|
+
Saved to "/path/to/keywords.json"
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
A command that needs a model and finds none exits 2:
|
|
19
|
+
|
|
20
|
+
```console
|
|
21
|
+
$ keywords "Ruby is elegant"
|
|
22
|
+
Error: No model found; run 'keywords fit' first or pass correct model using the '-m' option.
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The default model path is `./keywords.json`. Use `-m` for any other path.
|
|
26
|
+
|
|
27
|
+
## Commands
|
|
28
|
+
|
|
29
|
+
| Command | Action |
|
|
30
|
+
|:--|:--|
|
|
31
|
+
| `keywords fit <files...>` | Build a vocabulary from files or standard input |
|
|
32
|
+
| `keywords extract <file>` | Score the contents of one file |
|
|
33
|
+
| `keywords info` | Print the model statistics |
|
|
34
|
+
| `keywords <text>` | Score the text given as arguments |
|
|
35
|
+
|
|
36
|
+
With no arguments and no piped input, `keywords` prints a short guide.
|
|
37
|
+
|
|
38
|
+
## fit
|
|
39
|
+
|
|
40
|
+
Each **line** becomes a separate document. The document count drives the inverse
|
|
41
|
+
document frequency, so a file of 200 lines contributes 200 documents.
|
|
42
|
+
|
|
43
|
+
```console
|
|
44
|
+
$ keywords fit corpus/*.txt
|
|
45
|
+
Saved to "/path/to/keywords.json"
|
|
46
|
+
|
|
47
|
+
$ cat documents.txt | keywords fit
|
|
48
|
+
Saved to "/path/to/keywords.json"
|
|
49
|
+
|
|
50
|
+
$ keywords fit --min-df 2 --max-df 0.85 --ngram 1,2 corpus/*.txt
|
|
51
|
+
Saved to "/path/to/keywords.json"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`fit` skips a directory and keeps the files beside it, so a shell glob works
|
|
55
|
+
even when the directory holds a subdirectory:
|
|
56
|
+
|
|
57
|
+
```console
|
|
58
|
+
$ ls corpus
|
|
59
|
+
a.txt b.txt archive/
|
|
60
|
+
$ keywords fit corpus/*
|
|
61
|
+
Saved to "/path/to/keywords.json"
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
A path that matches nothing stops the run, so a typo never produces a smaller
|
|
65
|
+
model in silence:
|
|
66
|
+
|
|
67
|
+
```console
|
|
68
|
+
$ keywords fit corpus/a.txt corpus/NOPE.txt
|
|
69
|
+
Error: No files matched "corpus/NOPE.txt"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
An argument set with no readable file at all reports `No files to fit`. Empty
|
|
73
|
+
input reports `No documents found to save the model`. Neither writes a model.
|
|
74
|
+
|
|
75
|
+
`fit` reads one file at a time, so a corpus larger than the file descriptor
|
|
76
|
+
limit still works.
|
|
77
|
+
|
|
78
|
+
## extract
|
|
79
|
+
|
|
80
|
+
```console
|
|
81
|
+
$ keywords extract article.txt
|
|
82
|
+
machine:0.58 network:0.47 neural:0.47 learning:0.47
|
|
83
|
+
|
|
84
|
+
$ curl -s https://example.com/article | keywords extract
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`extract` requires a real file. A path that does not exist, or a directory,
|
|
88
|
+
exits 2. To score literal text, use the bare form instead.
|
|
89
|
+
|
|
90
|
+
## info
|
|
91
|
+
|
|
92
|
+
```console
|
|
93
|
+
$ keywords info
|
|
94
|
+
Documents: 1,234
|
|
95
|
+
Vocabulary: 5,678
|
|
96
|
+
Min DF: 1
|
|
97
|
+
Max DF: 1.0
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Options
|
|
101
|
+
|
|
102
|
+
| Option | Meaning |
|
|
103
|
+
|:--|:--|
|
|
104
|
+
| `-m`, `--model FILE` | Model file. Default `./keywords.json` |
|
|
105
|
+
| `-n`, `--top N` | Print the top N terms only. N must be positive |
|
|
106
|
+
| `-q` | Quiet. Suppress the `Saved to` line from `fit` |
|
|
107
|
+
| `--min-df N` | Minimum document frequency, as a count. Default 1 |
|
|
108
|
+
| `--max-df N` | Maximum document frequency, as a ratio from 0.0 to 1.0. Default 1.0 |
|
|
109
|
+
| `--ngram MIN,MAX` | N-gram range. Default `1,1` |
|
|
110
|
+
| `-v`, `--version` | Print the gem version |
|
|
111
|
+
| `-h`, `--help` | Print the full usage |
|
|
112
|
+
|
|
113
|
+
`--min-df` and `--max-df` apply during `fit`. The model stores them, and `info`
|
|
114
|
+
reports them back.
|
|
115
|
+
|
|
116
|
+
`-q` suppresses progress text but never the term scores. A scripted `fit` stays
|
|
117
|
+
silent, and a scripted score still produces its data.
|
|
118
|
+
|
|
119
|
+
## Output format
|
|
120
|
+
|
|
121
|
+
Terms print as `term:score`, separated by spaces, sorted by descending score.
|
|
122
|
+
|
|
123
|
+
The command maps stems back to whole words. A model built from `programming`
|
|
124
|
+
prints `programming`, not the `program` stem:
|
|
125
|
+
|
|
126
|
+
```console
|
|
127
|
+
$ keywords "Ruby is a programming language"
|
|
128
|
+
language:0.58 programming:0.58 ruby:0.58
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
An n-gram label joins its parts with a space:
|
|
132
|
+
|
|
133
|
+
```console
|
|
134
|
+
$ keywords fit --ngram 1,2 -m ng.json corpus/*.txt
|
|
135
|
+
$ keywords -m ng.json "machine learning neural networks"
|
|
136
|
+
machine learning:0.46 machine:0.46 neural networks:0.38 networks:0.38 neural:0.38 learning:0.38
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Each score depends on the corpus you fitted, so your numbers will differ.
|
|
140
|
+
|
|
141
|
+
That space sits inside a label in an otherwise space-separated stream. Parse
|
|
142
|
+
n-gram output on the `:` separator, not on whitespace.
|
|
143
|
+
|
|
144
|
+
## Exit codes
|
|
145
|
+
|
|
146
|
+
| Code | Meaning |
|
|
147
|
+
|:--|:--|
|
|
148
|
+
| 0 | Success |
|
|
149
|
+
| 1 | An unexpected error |
|
|
150
|
+
| 2 | A usage error, such as a bad option, a missing model, or a path that matches nothing |
|
|
151
|
+
|
|
152
|
+
Scripts can rely on 2 for every input mistake:
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
keywords fit corpus/*.txt || echo "fit failed with $?"
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Equivalent Ruby
|
|
159
|
+
|
|
160
|
+
The command wraps [`Classifier::TFIDF`](tfidf.md). This code does what
|
|
161
|
+
`keywords fit` does:
|
|
162
|
+
|
|
163
|
+
```ruby
|
|
164
|
+
require "classifier"
|
|
165
|
+
|
|
166
|
+
tfidf = Classifier::TFIDF.new(min_df: 2, max_df: 0.85, ngram_range: [1, 2])
|
|
167
|
+
tfidf.fit_from_stream(
|
|
168
|
+
Classifier::Streaming::MultiIO.new(Dir["corpus/*.txt"])
|
|
169
|
+
)
|
|
170
|
+
tfidf.save_to_file("keywords.json")
|
|
171
|
+
```
|
data/docs/knn.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# k-Nearest Neighbors
|
|
2
|
+
|
|
3
|
+
`Classifier::KNN` classifies text by the categories of its nearest examples. It
|
|
4
|
+
shows which examples drove the answer, which makes it useful when you must
|
|
5
|
+
explain a result.
|
|
6
|
+
|
|
7
|
+
It builds on [LSI](lsi.md) for the similarity measure.
|
|
8
|
+
|
|
9
|
+
## Add examples and classify
|
|
10
|
+
|
|
11
|
+
```ruby
|
|
12
|
+
require "classifier"
|
|
13
|
+
|
|
14
|
+
knn = Classifier::KNN.new(k: 3)
|
|
15
|
+
%w[laptop coding software developer programming].each { |w| knn.add(tech: w) }
|
|
16
|
+
%w[football basketball soccer goal team].each { |w| knn.add(sports: w) }
|
|
17
|
+
|
|
18
|
+
knn.classify("programming code")
|
|
19
|
+
# => "tech"
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`train` is an alias of `add`, so the call reads the same as Bayes:
|
|
23
|
+
|
|
24
|
+
```ruby
|
|
25
|
+
knn.train(tech: "compiler", sports: "referee")
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## See the neighbors
|
|
29
|
+
|
|
30
|
+
```ruby
|
|
31
|
+
knn.classify_with_neighbors("programming code")
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The result holds the winning category, the neighbors that voted, the vote
|
|
35
|
+
tally, and a confidence value:
|
|
36
|
+
|
|
37
|
+
```ruby
|
|
38
|
+
{
|
|
39
|
+
category: "tech",
|
|
40
|
+
neighbors: [
|
|
41
|
+
{ item: "programming", category: "tech", similarity: 0.9999999999999993 },
|
|
42
|
+
{ item: "coding", category: "tech", similarity: 0.9999999999999992 },
|
|
43
|
+
{ item: "team", category: "sports", similarity: 2.6e-16 }
|
|
44
|
+
],
|
|
45
|
+
votes: { "tech" => 2.0, "sports" => 1.0 },
|
|
46
|
+
confidence: 0.6666666666666666
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`confidence` is the winning share of the votes.
|
|
51
|
+
|
|
52
|
+
## Choose k
|
|
53
|
+
|
|
54
|
+
`k` sets how many neighbors vote. It defaults to 5.
|
|
55
|
+
|
|
56
|
+
```ruby
|
|
57
|
+
knn = Classifier::KNN.new(k: 3)
|
|
58
|
+
knn.k # => 3
|
|
59
|
+
knn.k = 5
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
A small `k` follows the data closely and reacts to noise. A large `k` smooths
|
|
63
|
+
the boundary. Keep `k` at or below the number of examples you added.
|
|
64
|
+
|
|
65
|
+
## Weighted voting
|
|
66
|
+
|
|
67
|
+
By default every neighbor casts an equal vote. Weighted voting scales each vote
|
|
68
|
+
by similarity, so a close neighbor counts for more:
|
|
69
|
+
|
|
70
|
+
```ruby
|
|
71
|
+
knn = Classifier::KNN.new(k: 5, weighted: true)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Set it later with `knn.weighted = true`.
|
|
75
|
+
|
|
76
|
+
## Inspect the model
|
|
77
|
+
|
|
78
|
+
```ruby
|
|
79
|
+
knn.categories # => ["tech", "sports"]
|
|
80
|
+
knn.items # every added example
|
|
81
|
+
knn.categories_for("programming")
|
|
82
|
+
knn.remove_item("programming")
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Save and load
|
|
86
|
+
|
|
87
|
+
```ruby
|
|
88
|
+
knn.save_to_file("model.json")
|
|
89
|
+
loaded = Classifier::KNN.load_from_file("model.json")
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
See [Persistence](persistence.md).
|