-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
document_classification.py
2171 lines (1773 loc) · 89.2 KB
/
document_classification.py
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import csv
import json
import logging
import os
from pathlib import Path
from typing import Dict, List, Optional, Union
import flair
from flair.data import (
Corpus,
DataPair,
FlairDataset,
Sentence,
Tokenizer,
_iter_dataset,
)
from flair.datasets.base import find_train_dev_test_files
from flair.file_utils import cached_path, unpack_file, unzip_file
from flair.tokenization import SegtokTokenizer, SpaceTokenizer
log = logging.getLogger("flair")
class ClassificationCorpus(Corpus):
"""A classification corpus from FastText-formatted text files."""
def __init__(
self,
data_folder: Union[str, Path],
label_type: str = "class",
train_file=None,
test_file=None,
dev_file=None,
truncate_to_max_tokens: int = -1,
truncate_to_max_chars: int = -1,
filter_if_longer_than: int = -1,
tokenizer: Union[bool, Tokenizer] = SegtokTokenizer(),
memory_mode: str = "partial",
label_name_map: Optional[Dict[str, str]] = None,
skip_labels: Optional[List[str]] = None,
allow_examples_without_labels=False,
sample_missing_splits: bool = True,
encoding: str = "utf-8",
) -> None:
"""Instantiates a Corpus from text classification-formatted task data.
Args:
data_folder: base folder with the task data
label_type: name of the label
train_file: the name of the train file
test_file: the name of the test file
dev_file: the name of the dev file, if None, dev data is sampled from train
truncate_to_max_tokens: If set, truncates each Sentence to a maximum number of tokens
truncate_to_max_chars: If set, truncates each Sentence to a maximum number of chars
filter_if_longer_than: If set, filters documents that are longer that the specified number of tokens.
tokenizer: Tokenizer for dataset, default is SegtokTokenizer
memory_mode: Set to what degree to keep corpus in memory ('full', 'partial' or 'disk'). Use 'full' if full corpus and all embeddings fits into memory for speedups during training. Otherwise use 'partial' and if even this is too much for your memory, use 'disk'.
label_name_map: Optionally map label names to different schema.
allow_examples_without_labels: set to True to allow Sentences without label in the corpus.
encoding: Default is 'utf-8' but some datasets are in 'latin-1
"""
# find train, dev and test files if not specified
dev_file, test_file, train_file = find_train_dev_test_files(data_folder, dev_file, test_file, train_file)
train: FlairDataset = ClassificationDataset(
train_file,
label_type=label_type,
tokenizer=tokenizer,
truncate_to_max_tokens=truncate_to_max_tokens,
truncate_to_max_chars=truncate_to_max_chars,
filter_if_longer_than=filter_if_longer_than,
memory_mode=memory_mode,
label_name_map=label_name_map,
skip_labels=skip_labels,
allow_examples_without_labels=allow_examples_without_labels,
encoding=encoding,
)
# use test_file to create test split if available
test = (
ClassificationDataset(
test_file,
label_type=label_type,
tokenizer=tokenizer,
truncate_to_max_tokens=truncate_to_max_tokens,
truncate_to_max_chars=truncate_to_max_chars,
filter_if_longer_than=filter_if_longer_than,
memory_mode=memory_mode,
label_name_map=label_name_map,
skip_labels=skip_labels,
allow_examples_without_labels=allow_examples_without_labels,
encoding=encoding,
)
if test_file is not None
else None
)
# use dev_file to create test split if available
dev = (
ClassificationDataset(
dev_file,
label_type=label_type,
tokenizer=tokenizer,
truncate_to_max_tokens=truncate_to_max_tokens,
truncate_to_max_chars=truncate_to_max_chars,
filter_if_longer_than=filter_if_longer_than,
memory_mode=memory_mode,
label_name_map=label_name_map,
skip_labels=skip_labels,
allow_examples_without_labels=allow_examples_without_labels,
encoding=encoding,
)
if dev_file is not None
else None
)
super().__init__(train, dev, test, name=str(data_folder), sample_missing_splits=sample_missing_splits)
log.info(f"Initialized corpus {self.name} (label type name is '{label_type}')")
class ClassificationDataset(FlairDataset):
"""Dataset for classification instantiated from a single FastText-formatted file."""
def __init__(
self,
path_to_file: Union[str, Path],
label_type: str,
truncate_to_max_tokens=-1,
truncate_to_max_chars=-1,
filter_if_longer_than: int = -1,
tokenizer: Union[bool, Tokenizer] = SegtokTokenizer(),
memory_mode: str = "partial",
label_name_map: Optional[Dict[str, str]] = None,
skip_labels: Optional[List[str]] = None,
allow_examples_without_labels=False,
encoding: str = "utf-8",
) -> None:
"""Reads a data file for text classification.
The file should contain one document/text per line.
The line should have the following format:
__label__<class_name> <text>
If you have a multi class task, you can have as many labels as you want at the beginning of the line, e.g.,
__label__<class_name_1> __label__<class_name_2> <text>
:param path_to_file: the path to the data file
:param label_type: name of the label
:param truncate_to_max_tokens: If set, truncates each Sentence to a maximum number of tokens
:param truncate_to_max_chars: If set, truncates each Sentence to a maximum number of chars
:param filter_if_longer_than: If set, filters documents that are longer that the specified number of tokens.
:param tokenizer: Custom tokenizer to use (default is SegtokTokenizer)
:param memory_mode: Set to what degree to keep corpus in memory ('full', 'partial' or 'disk'). Use 'full'
if full corpus and all embeddings fits into memory for speedups during training. Otherwise use 'partial' and if
even this is too much for your memory, use 'disk'.
:param label_name_map: Optionally map label names to different schema.
:param allow_examples_without_labels: set to True to allow Sentences without label in the Dataset.
:param encoding: Default is 'utf-8' but some datasets are in 'latin-1
:return: list of sentences
"""
path_to_file = Path(path_to_file)
assert path_to_file.exists()
self.label_prefix = "__label__"
self.label_type = label_type
self.memory_mode = memory_mode
self.tokenizer = tokenizer
if self.memory_mode == "full":
self.sentences = []
if self.memory_mode == "partial":
self.lines = []
if self.memory_mode == "disk":
self.indices = []
self.total_sentence_count: int = 0
self.truncate_to_max_chars = truncate_to_max_chars
self.truncate_to_max_tokens = truncate_to_max_tokens
self.filter_if_longer_than = filter_if_longer_than
self.label_name_map = label_name_map
self.allow_examples_without_labels = allow_examples_without_labels
self.path_to_file = path_to_file
with open(str(path_to_file), encoding=encoding) as f:
line = f.readline()
position = 0
while line:
if ("__label__" not in line and not allow_examples_without_labels) or (
" " not in line and "\t" not in line
):
position = f.tell()
line = f.readline()
continue
if 0 < self.filter_if_longer_than < len(line.split(" ")):
position = f.tell()
line = f.readline()
continue
# if data point contains black-listed label, do not use
if skip_labels:
skip = False
for skip_label in skip_labels:
if "__label__" + skip_label in line:
skip = True
if skip:
line = f.readline()
continue
if self.memory_mode == "full":
sentence = self._parse_line_to_sentence(line, self.label_prefix, tokenizer)
if sentence is not None and len(sentence.tokens) > 0:
self.sentences.append(sentence)
self.total_sentence_count += 1
if self.memory_mode == "partial" or self.memory_mode == "disk":
# first check if valid sentence
words = line.split()
l_len = 0
label = False
for i in range(len(words)):
if words[i].startswith(self.label_prefix):
l_len += len(words[i]) + 1
label = True
else:
break
text = line[l_len:].strip()
# if so, add to indices
if text and (label or allow_examples_without_labels):
if self.memory_mode == "partial":
self.lines.append(line)
self.total_sentence_count += 1
if self.memory_mode == "disk":
self.indices.append(position)
self.total_sentence_count += 1
position = f.tell()
line = f.readline()
def _parse_line_to_sentence(self, line: str, label_prefix: str, tokenizer: Union[bool, Tokenizer]):
words = line.split()
labels = []
l_len = 0
for i in range(len(words)):
if words[i].startswith(label_prefix):
l_len += len(words[i]) + 1
label = words[i].replace(label_prefix, "")
if self.label_name_map and label in self.label_name_map:
label = self.label_name_map[label]
labels.append(label)
else:
break
text = line[l_len:].strip()
if self.truncate_to_max_chars > 0:
text = text[: self.truncate_to_max_chars]
if text and (labels or self.allow_examples_without_labels):
sentence = Sentence(text, use_tokenizer=tokenizer)
for label in labels:
sentence.add_label(self.label_type, label)
if sentence is not None and 0 < self.truncate_to_max_tokens < len(sentence):
sentence.tokens = sentence.tokens[: self.truncate_to_max_tokens]
return sentence
return None
def is_in_memory(self) -> bool:
if self.memory_mode == "disk":
return False
if self.memory_mode == "partial":
return False
return True
def __len__(self) -> int:
return self.total_sentence_count
def __getitem__(self, index: int = 0) -> Sentence:
if self.memory_mode == "full":
return self.sentences[index]
if self.memory_mode == "partial":
sentence = self._parse_line_to_sentence(self.lines[index], self.label_prefix, self.tokenizer)
return sentence
if self.memory_mode == "disk":
with open(str(self.path_to_file), encoding="utf-8") as file:
file.seek(self.indices[index])
line = file.readline()
sentence = self._parse_line_to_sentence(line, self.label_prefix, self.tokenizer)
return sentence
raise AssertionError
class CSVClassificationCorpus(Corpus):
"""Classification corpus instantiated from CSV data files."""
def __init__(
self,
data_folder: Union[str, Path],
column_name_map: Dict[int, str],
label_type: str,
name: str = "csv_corpus",
train_file=None,
test_file=None,
dev_file=None,
max_tokens_per_doc=-1,
max_chars_per_doc=-1,
tokenizer: Tokenizer = SegtokTokenizer(),
in_memory: bool = False,
skip_header: bool = False,
encoding: str = "utf-8",
no_class_label=None,
sample_missing_splits: Union[bool, str] = True,
**fmtparams,
) -> None:
"""Instantiates a Corpus for text classification from CSV column formatted data.
:param data_folder: base folder with the task data
:param column_name_map: a column name map that indicates which column is text and which the label(s)
:param label_type: name of the label
:param train_file: the name of the train file
:param test_file: the name of the test file
:param dev_file: the name of the dev file, if None, dev data is sampled from train
:param max_tokens_per_doc: If set, truncates each Sentence to a maximum number of Tokens
:param max_chars_per_doc: If set, truncates each Sentence to a maximum number of chars
:param tokenizer: Tokenizer for dataset, default is SegtokTokenizer
:param in_memory: If True, keeps dataset as Sentences in memory, otherwise only keeps strings
:param skip_header: If True, skips first line because it is header
:param encoding: Default is 'utf-8' but some datasets are in 'latin-1
:param fmtparams: additional parameters for the CSV file reader
:return: a Corpus with annotated train, dev and test data
"""
# find train, dev and test files if not specified
dev_file, test_file, train_file = find_train_dev_test_files(data_folder, dev_file, test_file, train_file)
train: FlairDataset = CSVClassificationDataset(
train_file,
column_name_map,
label_type=label_type,
tokenizer=tokenizer,
max_tokens_per_doc=max_tokens_per_doc,
max_chars_per_doc=max_chars_per_doc,
in_memory=in_memory,
skip_header=skip_header,
encoding=encoding,
no_class_label=no_class_label,
**fmtparams,
)
test = (
CSVClassificationDataset(
test_file,
column_name_map,
label_type=label_type,
tokenizer=tokenizer,
max_tokens_per_doc=max_tokens_per_doc,
max_chars_per_doc=max_chars_per_doc,
in_memory=in_memory,
skip_header=skip_header,
encoding=encoding,
no_class_label=no_class_label,
**fmtparams,
)
if test_file is not None
else None
)
dev = (
CSVClassificationDataset(
dev_file,
column_name_map,
label_type=label_type,
tokenizer=tokenizer,
max_tokens_per_doc=max_tokens_per_doc,
max_chars_per_doc=max_chars_per_doc,
in_memory=in_memory,
skip_header=skip_header,
encoding=encoding,
no_class_label=no_class_label,
**fmtparams,
)
if dev_file is not None
else None
)
super().__init__(train, dev, test, name=name, sample_missing_splits=sample_missing_splits)
class CSVClassificationDataset(FlairDataset):
"""Dataset for text classification from CSV column formatted data."""
def __init__(
self,
path_to_file: Union[str, Path],
column_name_map: Dict[int, str],
label_type: str,
max_tokens_per_doc: int = -1,
max_chars_per_doc: int = -1,
tokenizer: Tokenizer = SegtokTokenizer(),
in_memory: bool = True,
skip_header: bool = False,
encoding: str = "utf-8",
no_class_label=None,
**fmtparams,
) -> None:
"""Instantiates a Dataset for text classification from CSV column formatted data.
:param path_to_file: path to the file with the CSV data
:param column_name_map: a column name map that indicates which column is text and which the label(s)
:param label_type: name of the label
:param max_tokens_per_doc: If set, truncates each Sentence to a maximum number of Tokens
:param max_chars_per_doc: If set, truncates each Sentence to a maximum number of chars
:param tokenizer: Tokenizer for dataset, default is SegTokTokenizer
:param in_memory: If True, keeps dataset as Sentences in memory, otherwise only keeps strings
:param skip_header: If True, skips first line because it is header
:param encoding: Most datasets are 'utf-8' but some are 'latin-1'
:param fmtparams: additional parameters for the CSV file reader
:return: a Corpus with annotated train, dev and test data
"""
path_to_file = Path(path_to_file)
assert path_to_file.exists()
# variables
self.path_to_file = path_to_file
self.in_memory = in_memory
self.tokenizer = tokenizer
self.column_name_map = column_name_map
self.max_tokens_per_doc = max_tokens_per_doc
self.max_chars_per_doc = max_chars_per_doc
self.no_class_label = no_class_label
self.label_type = label_type
# different handling of in_memory data than streaming data
if self.in_memory:
self.sentences = []
else:
self.raw_data = []
self.total_sentence_count: int = 0
# most data sets have the token text in the first column, if not, pass 'text' as column
self.text_columns: List[int] = []
self.pair_columns: List[int] = []
for column in column_name_map:
if column_name_map[column] == "text":
self.text_columns.append(column)
if column_name_map[column] == "pair":
self.pair_columns.append(column)
with open(self.path_to_file, encoding=encoding) as csv_file:
csv_reader = csv.reader(csv_file, **fmtparams)
if skip_header:
next(csv_reader, None) # skip the headers
for row in csv_reader:
# test if format is OK
wrong_format = False
for text_column in self.text_columns:
if text_column >= len(row):
wrong_format = True
if wrong_format:
continue
# test if at least one label given
has_label = False
for column in self.column_name_map:
if self.column_name_map[column].startswith("label") and row[column]:
has_label = True
break
if not has_label:
continue
if self.in_memory:
sentence = self._make_labeled_data_point(row)
self.sentences.append(sentence)
else:
self.raw_data.append(row)
self.total_sentence_count += 1
def _make_labeled_data_point(self, row):
# make sentence from text (and filter for length)
text = " ".join([row[text_column] for text_column in self.text_columns])
if self.max_chars_per_doc > 0:
text = text[: self.max_chars_per_doc]
sentence = Sentence(text, use_tokenizer=self.tokenizer)
if 0 < self.max_tokens_per_doc < len(sentence):
sentence.tokens = sentence.tokens[: self.max_tokens_per_doc]
# if a pair column is defined, make a sentence pair object
if len(self.pair_columns) > 0:
text = " ".join([row[pair_column] for pair_column in self.pair_columns])
if self.max_chars_per_doc > 0:
text = text[: self.max_chars_per_doc]
pair = Sentence(text, use_tokenizer=self.tokenizer)
if 0 < self.max_tokens_per_doc < len(sentence):
pair.tokens = pair.tokens[: self.max_tokens_per_doc]
data_point = DataPair(first=sentence, second=pair)
else:
data_point = sentence
for column in self.column_name_map:
column_value = row[column]
if (
self.column_name_map[column].startswith("label")
and column_value
and column_value != self.no_class_label
):
data_point.add_label(self.label_type, column_value)
return data_point
def is_in_memory(self) -> bool:
return self.in_memory
def __len__(self) -> int:
return self.total_sentence_count
def __getitem__(self, index: int = 0) -> Sentence:
if self.in_memory:
return self.sentences[index]
else:
row = self.raw_data[index]
sentence = self._make_labeled_data_point(row)
return sentence
class AMAZON_REVIEWS(ClassificationCorpus):
"""A very large corpus of Amazon reviews with positivity ratings.
Corpus is downloaded from and documented at
https://nijianmo.github.io/amazon/index.html.
We download the 5-core subset which is still tens of millions of
reviews.
"""
# noinspection PyDefaultArgument
def __init__(
self,
split_max: int = 30000,
label_name_map: Dict[str, str] = {
"1.0": "NEGATIVE",
"2.0": "NEGATIVE",
"3.0": "NEGATIVE",
"4.0": "POSITIVE",
"5.0": "POSITIVE",
},
skip_labels=["3.0", "4.0"],
fraction_of_5_star_reviews: int = 10,
tokenizer: Tokenizer = SegtokTokenizer(),
memory_mode="partial",
**corpusargs,
) -> None:
"""Constructs corpus object.
Split_max indicates how many data points from each of the 28 splits are used, so
set this higher or lower to increase/decrease corpus size.
:param label_name_map: Map label names to different schema. By default, the 5-star rating is mapped onto 3
classes (POSITIVE, NEGATIVE, NEUTRAL)
:param split_max: Split_max indicates how many data points from each of the 28 splits are used, so
set this higher or lower to increase/decrease corpus size.
:param memory_mode: Set to what degree to keep corpus in memory ('full', 'partial' or 'disk'). Use 'full'
if full corpus and all embeddings fits into memory for speedups during training. Otherwise use 'partial' and if
even this is too much for your memory, use 'disk'.
:param tokenizer: Custom tokenizer to use (default is SegtokTokenizer)
:param corpusargs: Arguments for ClassificationCorpus
"""
# dataset name includes the split size
dataset_name = self.__class__.__name__.lower() + "_" + str(split_max) + "_" + str(fraction_of_5_star_reviews)
# default dataset folder is the cache root
data_folder = flair.cache_root / "datasets" / dataset_name
# download data if necessary
if not (data_folder / "train.txt").is_file():
# download each of the 28 splits
self.download_and_prepare_amazon_product_file(
data_folder, "AMAZON_FASHION_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "All_Beauty_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Appliances_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Arts_Crafts_and_Sewing_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Arts_Crafts_and_Sewing_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Automotive_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Books_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "CDs_and_Vinyl_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Cell_Phones_and_Accessories_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Clothing_Shoes_and_Jewelry_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Digital_Music_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Electronics_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Gift_Cards_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Grocery_and_Gourmet_Food_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Home_and_Kitchen_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Industrial_and_Scientific_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Kindle_Store_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Luxury_Beauty_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Magazine_Subscriptions_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Movies_and_TV_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Musical_Instruments_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Office_Products_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Patio_Lawn_and_Garden_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Pet_Supplies_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Prime_Pantry_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Software_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Sports_and_Outdoors_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Tools_and_Home_Improvement_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Toys_and_Games_5.json.gz", split_max, fraction_of_5_star_reviews
)
self.download_and_prepare_amazon_product_file(
data_folder, "Video_Games_5.json.gz", split_max, fraction_of_5_star_reviews
)
super().__init__(
data_folder,
label_type="sentiment",
label_name_map=label_name_map,
skip_labels=skip_labels,
tokenizer=tokenizer,
memory_mode=memory_mode,
**corpusargs,
)
def download_and_prepare_amazon_product_file(
self, data_folder, part_name, max_data_points=None, fraction_of_5_star_reviews=None
):
amazon__path = "http://deepyeti.ucsd.edu/jianmo/amazon/categoryFilesSmall"
cached_path(f"{amazon__path}/{part_name}", Path("datasets") / "Amazon_Product_Reviews")
import gzip
# create dataset directory if necessary
if not os.path.exists(data_folder):
os.makedirs(data_folder)
with open(data_folder / "train.txt", "a") as train_file:
write_count = 0
review_5_count = 0
# download senteval datasets if necessary und unzip
with gzip.open(flair.cache_root / "datasets" / "Amazon_Product_Reviews" / part_name, "rb") as f_in:
for line in f_in:
parsed_json = json.loads(line)
if "reviewText" not in parsed_json:
continue
if parsed_json["reviewText"].strip() == "":
continue
text = parsed_json["reviewText"].replace("\n", "")
if fraction_of_5_star_reviews and str(parsed_json["overall"]) == "5.0":
review_5_count += 1
if review_5_count != fraction_of_5_star_reviews:
continue
else:
review_5_count = 0
train_file.write(f"__label__{parsed_json['overall']} {text}\n")
write_count += 1
if max_data_points and write_count >= max_data_points:
break
class IMDB(ClassificationCorpus):
"""Corpus of IMDB movie reviews labeled by sentiment (POSITIVE, NEGATIVE).
Downloaded from and documented at http://ai.stanford.edu/~amaas/data/sentiment/.
"""
def __init__(
self,
base_path: Optional[Union[str, Path]] = None,
rebalance_corpus: bool = True,
tokenizer: Tokenizer = SegtokTokenizer(),
memory_mode="partial",
**corpusargs,
) -> None:
"""Initialize the IMDB move review sentiment corpus.
Args:
base_path: Provide this only if you store the IMDB corpus in a specific folder, otherwise use default.
tokenizer: Custom tokenizer to use (default is SegtokTokenizer)
rebalance_corpus: Weather to use a 80/10/10 data split instead of the original 50/0/50 split.
memory_mode: Set to 'partial' because this is a huge corpus, but you can also set to 'full' for faster
processing or 'none' for less memory.
corpusargs: Other args for ClassificationCorpus.
"""
base_path = flair.cache_root / "datasets" if not base_path else Path(base_path)
# this dataset name
dataset_name = self.__class__.__name__.lower() + "_v4"
# download data if necessary
imdb_acl_path = "http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz"
if rebalance_corpus:
dataset_name = dataset_name + "-rebalanced"
data_folder = base_path / dataset_name
data_path = flair.cache_root / "datasets" / dataset_name
train_data_file = data_path / "train.txt"
test_data_file = data_path / "test.txt"
if not train_data_file.is_file() or (not rebalance_corpus and not test_data_file.is_file()):
for file_path in [train_data_file, test_data_file]:
if file_path.is_file():
os.remove(file_path)
cached_path(imdb_acl_path, Path("datasets") / dataset_name)
import tarfile
with tarfile.open(flair.cache_root / "datasets" / dataset_name / "aclImdb_v1.tar.gz", "r:gz") as f_in:
datasets = ["train", "test"]
labels = ["pos", "neg"]
for label in labels:
for dataset in datasets:
f_in.extractall(
data_path, members=[m for m in f_in.getmembers() if f"{dataset}/{label}" in m.name]
)
data_file = train_data_file
if not rebalance_corpus and dataset == "test":
data_file = test_data_file
with open(data_file, "at") as f_p:
current_path = data_path / "aclImdb" / dataset / label
for file_name in current_path.iterdir():
if file_name.is_file() and file_name.name.endswith(".txt"):
if label == "pos":
sentiment_label = "POSITIVE"
if label == "neg":
sentiment_label = "NEGATIVE"
f_p.write(
f"__label__{sentiment_label} "
+ file_name.open("rt", encoding="utf-8").read()
+ "\n"
)
super().__init__(
data_folder, label_type="sentiment", tokenizer=tokenizer, memory_mode=memory_mode, **corpusargs
)
class NEWSGROUPS(ClassificationCorpus):
"""20 newsgroups corpus, classifying news items into one of 20 categories.
Downloaded from http://qwone.com/~jason/20Newsgroups
Each data point is a full news article so documents may be very
long.
"""
def __init__(
self,
base_path: Optional[Union[str, Path]] = None,
tokenizer: Tokenizer = SegtokTokenizer(),
memory_mode: str = "partial",
**corpusargs,
) -> None:
"""Instantiates 20 newsgroups corpus.
:param base_path: Provide this only if you store the IMDB corpus in a specific folder, otherwise use default.
:param tokenizer: Custom tokenizer to use (default is SegtokTokenizer)
:param memory_mode: Set to 'partial' because this is a big corpus, but you can also set to 'full' for faster
processing or 'none' for less memory.
:param corpusargs: Other args for ClassificationCorpus.
"""
base_path = flair.cache_root / "datasets" if not base_path else Path(base_path)
# this dataset name
dataset_name = self.__class__.__name__.lower()
data_folder = base_path / dataset_name
# download data if necessary
twenty_newsgroups_path = "http://qwone.com/~jason/20Newsgroups/20news-bydate.tar.gz"
data_path = flair.cache_root / "datasets" / dataset_name
data_file = data_path / "20news-bydate-train.txt"
if not data_file.is_file():
cached_path(twenty_newsgroups_path, Path("datasets") / dataset_name / "original")
import tarfile
with tarfile.open(
flair.cache_root / "datasets" / dataset_name / "original" / "20news-bydate.tar.gz", "r:gz"
) as f_in:
datasets = ["20news-bydate-test", "20news-bydate-train"]
labels = [
"alt.atheism",
"comp.graphics",
"comp.os.ms-windows.misc",
"comp.sys.ibm.pc.hardware",
"comp.sys.mac.hardware",
"comp.windows.x",
"misc.forsale",
"rec.autos",
"rec.motorcycles",
"rec.sport.baseball",
"rec.sport.hockey",
"sci.crypt",
"sci.electronics",
"sci.med",
"sci.space",
"soc.religion.christian",
"talk.politics.guns",
"talk.politics.mideast",
"talk.politics.misc",
"talk.religion.misc",
]
for label in labels:
for dataset in datasets:
f_in.extractall(
data_path / "original",
members=[m for m in f_in.getmembers() if f"{dataset}/{label}" in m.name],
)
with open(f"{data_path}/{dataset}.txt", "at", encoding="utf-8") as f_p:
current_path = data_path / "original" / dataset / label
for file_name in current_path.iterdir():
if file_name.is_file():
f_p.write(
f"__label__{label} "
+ file_name.open("rt", encoding="latin1").read().replace("\n", " <n> ")
+ "\n"
)
super().__init__(data_folder, tokenizer=tokenizer, memory_mode=memory_mode, **corpusargs)
class AGNEWS(ClassificationCorpus):
"""The AG's News Topic Classification Corpus, classifying news into 4 coarse-grained topics.
Labels: World, Sports, Business, Sci/Tech.
"""
def __init__(
self,
base_path: Optional[Union[str, Path]] = None,
tokenizer: Union[bool, Tokenizer] = SpaceTokenizer(),
memory_mode="partial",
**corpusargs,
):
"""Instantiates AGNews Classification Corpus with 4 classes.
:param base_path: Provide this only if you store the AGNEWS corpus in a specific folder, otherwise use default.
:param tokenizer: Custom tokenizer to use (default is SpaceTokenizer)
:param memory_mode: Set to 'partial' by default. Can also be 'full' or 'none'.
:param corpusargs: Other args for ClassificationCorpus.
"""
base_path = flair.cache_root / "datasets" if not base_path else Path(base_path)
dataset_name = self.__class__.__name__.lower()
data_folder = base_path / dataset_name
# download data from same source as in huggingface's implementations
agnews_path = "https://raw.githubusercontent.com/mhjabreel/CharCnn_Keras/master/data/ag_news_csv/"
original_filenames = ["train.csv", "test.csv", "classes.txt"]
new_filenames = ["train.txt", "test.txt"]
for original_filename in original_filenames:
cached_path(f"{agnews_path}{original_filename}", Path("datasets") / dataset_name / "original")
data_file = data_folder / new_filenames[0]
label_dict = []
label_path = original_filenames[-1]
# read label order
with open(data_folder / "original" / label_path) as f:
for line in f:
line = line.rstrip()
label_dict.append(line)
original_filenames = original_filenames[:-1]
if not data_file.is_file():
for original_filename, new_filename in zip(original_filenames, new_filenames):
with open(data_folder / "original" / original_filename, encoding="utf-8") as open_fp, open(
data_folder / new_filename, "w", encoding="utf-8"
) as write_fp:
csv_reader = csv.reader(
open_fp, quotechar='"', delimiter=",", quoting=csv.QUOTE_ALL, skipinitialspace=True
)
for id_, row in enumerate(csv_reader):
label, title, description = row
# Original labels are [1, 2, 3, 4] -> ['World', 'Sports', 'Business', 'Sci/Tech']
# Re-map to [0, 1, 2, 3].
text = " ".join((title, description))
new_label = "__label__"
new_label += label_dict[int(label) - 1]
write_fp.write(f"{new_label} {text}\n")
super().__init__(data_folder, label_type="topic", tokenizer=tokenizer, memory_mode=memory_mode, **corpusargs)
class STACKOVERFLOW(ClassificationCorpus):
"""Stackoverflow corpus classifying questions into one of 20 labels.
The data will be downloaded from "https://github.com/jacoxu/StackOverflow",
Each data point is a question.
"""
def __init__(
self,
base_path: Optional[Union[str, Path]] = None,
tokenizer: Tokenizer = SegtokTokenizer(),
memory_mode: str = "partial",
**corpusargs,
) -> None:
"""Instantiates Stackoverflow corpus.
:param base_path: Provide this only if you store the IMDB corpus in a specific folder, otherwise use default.
:param tokenizer: Custom tokenizer to use (default is SegtokTokenizer)
:param memory_mode: Set to 'partial' because this is a big corpus, but you can also set to 'full' for faster
processing or 'none' for less memory.
:param corpusargs: Other args for ClassificationCorpus.
"""