-
Notifications
You must be signed in to change notification settings - Fork 246
/
text_data.py
644 lines (547 loc) · 27 KB
/
text_data.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
# ----------------------------------------------------------------------------
# Copyright (C) 2021-2023 Deepchecks (https://www.deepchecks.com)
#
# This file is part of Deepchecks.
# Deepchecks is distributed under the terms of the GNU Affero General
# Public License (version 3 or later).
# You should have received a copy of the GNU Affero General Public License
# along with Deepchecks. If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------
#
"""The dataset module containing the tabular Dataset class and its functions."""
import contextlib
import typing as t
import warnings
from numbers import Number
import numpy as np
import pandas as pd
from deepchecks.core.errors import DeepchecksNotSupportedError, DeepchecksValueError
from deepchecks.nlp.input_validations import (validate_length_and_calculate_column_types,
validate_length_and_type_numpy_array, validate_modify_label,
validate_raw_text, validate_tokenized_text)
from deepchecks.nlp.task_type import TaskType, TTextLabel
from deepchecks.nlp.utils.text_embeddings import calculate_default_embeddings
from deepchecks.nlp.utils.text_properties import calculate_builtin_properties
from deepchecks.utils.logger import get_logger
from deepchecks.utils.metrics import is_label_none
from deepchecks.utils.validation import is_sequence_not_str
__all__ = ['TextData']
TDataset = t.TypeVar('TDataset', bound='TextData')
class TextData:
"""
TextData wraps together the raw text data and the labels for the nlp task.
The TextData class contains metadata and methods intended for easily accessing
metadata relevant for the training or validating of ML models.
Parameters
----------
raw_text : t.Sequence[str], default: None
The raw text data, a sequence of strings representing the raw text of each sample.
If not given, tokenized_text must be given, and raw_text will be created from it by joining the tokens with
spaces.
tokenized_text : t.Sequence[t.Sequence[str]], default: None
The tokenized text data, a sequence of sequences of strings representing the tokenized text of each sample.
Only relevant for task_type 'token_classification'.
If not given, raw_text must be given, and tokenized_text will be created from it by splitting the text by
spaces.
label : t.Optional[TTextLabel], default: None
The label for the text data. Can be either a text_classification label or a token_classification label.
If None, the label is not set.
- text_classification label - For text classification the accepted label format differs between multilabel and
single label cases. For single label data, the label should be passed as a sequence of labels, with one entry
per sample that can be either a string or an integer. For multilabel data, the label should be passed as a
sequence of sequences, with the sequence for each sample being a binary vector, representing the presence of
the i-th label in that sample.
- token_classification label - For token classification the accepted label format is the IOB format or similar
to it. The Label must be a sequence of sequences of strings or integers, with each sequence corresponding to
a sample in the tokenized text, and exactly the length of the corresponding tokenized text.
task_type : str, default: None
The task type for the text data. Can be either 'text_classification' or 'token_classification'. Must be set if
label is provided.
name : t.Optional[str] , default: None
The name of the dataset. If None, the dataset name will be defined when running it within a check.
metadata : t.Optional[t.Union[pd.DataFrame, str]] , default: None
Metadata for the samples. Metadata must be given as a pandas DataFrame or a path to a pandas
DataFrame compatible csv file, with the rows representing each sample
and columns representing the different metadata columns. If None, no metadata is set.
The number of rows in the metadata DataFrame must be equal to the number of samples in the dataset, and the
order of the rows must be the same as the order of the samples in the dataset.
For more on metadata, see the `NLP Metadata Guide
<https://docs.deepchecks.com/stable/nlp/usage_guides/nlp_metadata.html>`_.
categorical_metadata : t.Optional[t.List[str]] , default: None
The names of the categorical metadata columns. If None, categorical metadata columns are automatically inferred.
Only relevant if metadata is not None.
properties : t.Optional[t.Union[pd.DataFrame, str]] , default: None
The text properties for the samples. Properties must be given as either a pandas DataFrame or a path to a pandas
DataFrame compatible csv file, with the rows representing each sample and columns representing the different
properties. If None, no properties are set.
The number of rows in the properties DataFrame must be equal to the number of samples in the dataset, and the
order of the rows must be the same as the order of the samples in the dataset.
In order to calculate the default properties, use the `TextData.calculate_builtin_properties` function after
the creation of the TextData object.
For more on properties, see the `NLP Properties Guide
<https://docs.deepchecks.com/stable/nlp/usage_guides/nlp_properties.html>`_.
categorical_properties : t.Optional[t.List[str]] , default: None
The names of the categorical properties columns. If None, categorical properties columns are automatically
inferred. Only relevant if properties is not None.
embeddings : t.Optional[Union[np.ndarray, pd.DataFrame, str]], default: None
The text embeddings for the samples. Embeddings must be given as a numpy array (or a path to an .npy
file containing a numpy array) of shape (N, E), where N is the number of samples in the TextData object and E
is the number of embeddings dimensions.
The numpy array must be in the same order as the samples in the TextData.
If None, no embeddings are set.
In order to use the default embeddings, use the `TextData.calculate_default_embeddings` function after
the creation of the TextData object.
For more on embeddings, see the :ref:`Text Embeddings Guide <nlp__embeddings_guide>`
"""
_text: np.ndarray
_label: TTextLabel
task_type: t.Optional[TaskType]
_tokenized_text: t.Optional[t.Sequence[t.Sequence[str]]] = None # Outer sequence is np array
name: t.Optional[str] = None
_embeddings: t.Optional[t.Union[pd.DataFrame, str]] = None
_metadata: t.Optional[t.Union[pd.DataFrame, str]] = None
_properties: t.Optional[t.Union[pd.DataFrame, str]] = None
_cat_properties: t.Optional[t.List[str]] = None
_cat_metadata: t.Optional[t.List[str]] = None
_original_text_index: t.Optional[t.Sequence[int]] = None # Sequence is np array
def __init__(
self,
raw_text: t.Optional[t.Sequence[str]] = None,
tokenized_text: t.Optional[t.Sequence[t.Sequence[str]]] = None,
label: t.Optional[TTextLabel] = None,
task_type: t.Optional[str] = None,
name: t.Optional[str] = None,
embeddings: t.Optional[t.Union[pd.DataFrame, np.ndarray, str]] = None,
metadata: t.Optional[pd.DataFrame] = None,
categorical_metadata: t.Optional[t.List[str]] = None,
properties: t.Optional[pd.DataFrame] = None,
categorical_properties: t.Optional[t.List[str]] = None,
):
# Require explicitly setting task type if label is provided
if task_type in [None, 'other']:
if label is not None:
raise DeepchecksValueError('task_type must be set when label is provided')
self._task_type = TaskType.OTHER
elif task_type == 'text_classification':
self._task_type = TaskType.TEXT_CLASSIFICATION
elif task_type == 'token_classification':
if tokenized_text is None:
raise DeepchecksValueError('tokenized_text must be provided for token_classification task type')
validate_tokenized_text(tokenized_text)
modified = [[str(token) for token in tokens_per_sample] for tokens_per_sample in tokenized_text]
self._tokenized_text = np.asarray(modified, dtype=object)
self._task_type = TaskType.TOKEN_CLASSIFICATION
else:
raise DeepchecksNotSupportedError(f'task_type {task_type} is not supported, must be one of '
'text_classification, token_classification, other')
if raw_text is None:
if tokenized_text is None:
raise DeepchecksValueError('Either raw_text or tokenized_text must be provided')
self._text = np.asarray([' '.join(tokens) for tokens in tokenized_text]) # Revisit this decision
else:
validate_raw_text(raw_text)
self._text = np.asarray([str(x) for x in raw_text])
if tokenized_text is not None and len(raw_text) != len(tokenized_text):
raise DeepchecksValueError('raw_text and tokenized_text sequences must have the same length')
self._label = validate_modify_label(label, self._task_type, len(self), tokenized_text)
if name is not None and not isinstance(name, str):
raise DeepchecksNotSupportedError(f'name must be a string, got {type(name)}')
self.name = name
if metadata is not None:
self.set_metadata(metadata, categorical_metadata)
if properties is not None:
self.set_properties(properties, categorical_properties)
if embeddings is not None:
self.set_embeddings(embeddings)
# Used for display purposes
self._original_text_index = np.arange(len(self))
def is_multi_label_classification(self) -> bool:
"""Check if the dataset is multi-label."""
if self.task_type == TaskType.TEXT_CLASSIFICATION and self._label is not None:
return is_sequence_not_str(self._label[0])
return False
# pylint: disable=protected-access
def copy(self: TDataset, rows_to_use: t.Optional[t.Sequence[int]] = None) -> TDataset:
"""Create a copy of this Dataset with new data.
Parameters
----------
rows_to_use : t.Optional[t.List[int]] , default: None
The rows to use in the new copy. If None, the new copy will contain all the rows.
"""
cls = type(self)
# NOTE:
# Make sure we won't get the warning for setting class in the non multilabel case
with disable_deepchecks_logger():
if rows_to_use is None:
new_copy = cls(
raw_text=self._text,
tokenized_text=self._tokenized_text,
label=self._label,
task_type=self._task_type.value,
name=self.name
)
if self._metadata is not None:
new_copy.set_metadata(self._metadata, self._cat_metadata)
if self._properties is not None:
new_copy.set_properties(self._properties, self._cat_properties)
if self._embeddings is not None:
new_copy.set_embeddings(self._embeddings)
new_copy._original_text_index = self._original_text_index
return new_copy
if not isinstance(rows_to_use, t.Sequence) or any(not isinstance(x, Number) for x in rows_to_use):
raise DeepchecksValueError('rows_to_use must be a list of integers')
rows_to_use = sorted(rows_to_use)
new_copy = cls(
raw_text=self._text[rows_to_use],
tokenized_text=(
self._tokenized_text[rows_to_use]
if self._tokenized_text is not None
else None
),
label=self._label[rows_to_use] if self.has_label() else None,
task_type=self._task_type.value, name=self.name
)
if self._metadata is not None:
metadata = self._metadata.iloc[rows_to_use, :]
new_copy.set_metadata(metadata, self._cat_metadata)
if self._properties is not None:
properties = self._properties.iloc[rows_to_use, :]
new_copy.set_properties(properties, self._cat_properties)
if self._embeddings is not None:
embeddings = self._embeddings[rows_to_use]
new_copy.set_embeddings(embeddings)
new_copy._original_text_index = self._original_text_index[rows_to_use]
return new_copy
def sample(self: TDataset, n_samples: int, replace: bool = False, random_state: t.Optional[int] = None,
drop_na_label: bool = False) -> TDataset:
"""Create a copy of the dataset object, with the internal data being a sample of the original data.
Parameters
----------
n_samples : int
Number of samples to draw.
replace : bool, default: False
Whether to sample with replacement.
random_state : t.Optional[int] , default None
Random state.
drop_na_label : bool, default: False
Whether to take sample only from rows with exiting label.
Returns
-------
Dataset
instance of the Dataset with sampled internal dataframe.
"""
samples = np.arange(len(self))
if drop_na_label and self.has_label():
samples = samples[[not is_label_none(x) for x in self._label]]
n_samples = min(n_samples, len(samples))
np.random.seed(random_state)
sample_idx = np.random.choice(range(len(samples)), n_samples, replace=replace)
return self.copy(rows_to_use=sorted(sample_idx))
def __len__(self) -> int:
"""Return number of samples in the dataset."""
return self.n_samples
@property
def n_samples(self) -> int:
"""Return number of samples in the dataset."""
if self._text is not None:
return len(self._text)
elif self._label is not None:
return len(self._label)
else:
return 0
@property
def embeddings(self) -> pd.DataFrame:
"""Return the metadata of for the dataset."""
return self._embeddings
def calculate_default_embeddings(self, model: str = 'miniLM', file_path: str = 'embeddings.csv'):
"""Calculate the default properties of the dataset.
Parameters
----------
model : str, default: 'miniLM'
The model to use for calculating the embeddings. Possible values are:
'miniLM': using the miniLM model in the sentence-transformers library.
'open_ai': using the ADA model in the open_ai library. Requires an API key.
file_path : str, default: 'embeddings.csv'
The path to save the embeddings to.
"""
if self._embeddings is not None:
warnings.warn('Embeddings already exist, overwriting them', UserWarning)
self._embeddings = calculate_default_embeddings(text=self.text, model=model, file_path=file_path)
def set_embeddings(self, embeddings: np.ndarray, verbose: bool = True):
"""Set the metadata of the dataset.
Parameters
----------
embeddings : pd.DataFrame
Embeddings to set.
verbose : bool, default: True
Whether to print information about the process.
"""
if self._embeddings is not None and verbose is True:
warnings.warn('Embeddings already exist, overwriting it', UserWarning)
if isinstance(embeddings, pd.DataFrame):
embeddings = embeddings.to_numpy()
if isinstance(embeddings, str):
embeddings = np.load(embeddings)
if embeddings is not None:
validate_length_and_type_numpy_array(embeddings, 'Embeddings', len(self))
self._embeddings = embeddings
@property
def metadata(self) -> pd.DataFrame:
"""Return the metadata of for the dataset."""
if self._metadata is None:
raise DeepchecksValueError(
'Functionality requires metadata, but the the TextData object had none. '
'To use this functionality, use the '
'set_metadata method to set your own metadata with a pandas.DataFrame.'
)
return self._metadata
@property
def categorical_metadata_columns(self) -> t.List[str]:
"""Return categorical metadata column names."""
return self._cat_metadata
def set_metadata(
self,
metadata: pd.DataFrame,
categorical_metadata: t.Optional[t.Sequence[str]] = None
):
"""Set the metadata of the dataset."""
if self._metadata is not None:
warnings.warn('Metadata already exist, overwriting it', UserWarning)
if isinstance(metadata, str):
metadata = pd.read_csv(metadata)
column_types = validate_length_and_calculate_column_types(
data_table=metadata,
data_table_name='Metadata',
expected_size=len(self),
categorical_columns=categorical_metadata
)
self._metadata = metadata.reset_index(drop=True)
self._cat_metadata = column_types.categorical_columns
def calculate_builtin_properties(
self,
include_properties: t.Optional[t.List[str]] = None,
ignore_properties: t.Optional[t.List[str]] = None,
include_long_calculation_properties: bool = False,
device: t.Optional[str] = None
):
"""Calculate the default properties of the dataset.
Parameters
----------
include_properties : List[str], default None
The properties to calculate. If None, all default properties will be calculated. Cannot be used together
with ignore_properties parameter.
ignore_properties : List[str], default None
The properties to ignore. If None, no properties will be ignored. Cannot be used together with
properties parameter.
include_long_calculation_properties : bool, default False
Whether to include properties that may take a long time to calculate. If False, these properties will be
ignored.
device : int, default None
The device to use for the calculation. If None, the default device will be used.
"""
if self._properties is not None:
warnings.warn('Properties already exist, overwriting them', UserWarning)
properties, properties_types = calculate_builtin_properties(
list(self.text),
include_properties=include_properties,
ignore_properties=ignore_properties,
include_long_calculation_properties=include_long_calculation_properties,
device=device
)
self._properties = pd.DataFrame(properties, index=self.get_original_text_indexes())
self._cat_properties = [k for k, v in properties_types.items() if v == 'categorical']
def set_properties(
self,
properties: pd.DataFrame,
categorical_properties: t.Optional[t.Sequence[str]] = None
):
"""Set the properties of the dataset."""
if self._properties is not None:
warnings.warn('Properties already exist, overwriting them', UserWarning)
if isinstance(properties, str):
properties = pd.read_csv(properties)
column_types = validate_length_and_calculate_column_types(
data_table=properties,
data_table_name='Properties',
expected_size=len(self),
categorical_columns=categorical_properties
)
self._properties = properties.reset_index(drop=True)
self._cat_properties = column_types.categorical_columns
def save_properties(self, path: str):
"""Save the dataset properties to csv.
Parameters
----------
path : str
Path to save the properties to.
"""
if self._properties is None:
raise DeepchecksNotSupportedError(
'TextData does not contain properties, add them by using '
'"calculate_builtin_properties" or "set_properties" functions'
)
self._properties.to_csv(path, index=False)
@property
def properties(self) -> pd.DataFrame:
"""Return the properties of the dataset."""
if self._properties is None:
raise DeepchecksNotSupportedError(
'Functionality requires properties, but the the TextData object had none. To use this functionality, '
'use the set_properties method to set your own properties with a pandas.DataFrame or use '
'TextData.calculate_builtin_properties to add the default deepchecks properties.'
)
return self._properties
@property
def categorical_properties(self) -> t.List[str]:
"""Return categorical properties names."""
return self._cat_properties
@property
def task_type(self) -> t.Optional[TaskType]:
"""Return the task type.
Returns
-------
t.Optional[TaskType]
Task type
"""
return self._task_type
@property
def text(self) -> t.Sequence[str]:
"""Return sequence of raw text samples.
Returns
-------
t.Sequence[str]
Sequence of raw text samples.
"""
return self._text
@property
def tokenized_text(self) -> t.Sequence[t.Sequence[str]]:
"""Return sequence of tokenized text samples.
Returns
-------
t.Sequence[t.Sequence[str]]
Sequence of tokenized text samples.
"""
if self._tokenized_text is None:
raise DeepchecksValueError('Tokenized text is not set, provide it when initializing the TextData object '
'to run the requested functionalities')
return self._tokenized_text
@property
def label(self) -> TTextLabel:
"""Return the label defined in the dataset.
Returns
-------
TTextLabel
"""
if not self.has_label():
raise DeepchecksValueError('Label is not set, provide it when initializing the TextData object '
'to run the requested functionalities')
return self._label
def label_for_display(self, model_classes: list = None) -> TTextLabel:
"""Return the label defined in the dataset in a format that can be displayed.
Parameters
----------
model_classes : list, default None
List of classes names to use for multi-label display. Only used if the dataset is multi-label.
Returns
-------
TTextLabel
"""
if self.is_multi_label_classification():
ret_labels = [np.argwhere(x == 1).flatten().tolist() for x in self.label]
if model_classes:
ret_labels = [[model_classes[i] for i in x] for x in ret_labels]
return ret_labels
else:
return self.label
def has_label(self) -> bool:
"""Return True if label was set.
Returns
-------
bool
True if label was set.
"""
return self._label is not None
def get_original_text_indexes(self) -> t.Sequence[int]:
"""Return the original indexes of the text samples.
Returns
-------
t.Sequence[int]
Original indexes of the text samples.
"""
assert self._original_text_index is not None, 'Internal Error'
return self._original_text_index
@classmethod
def cast_to_dataset(cls, obj: t.Any) -> 'TextData':
"""Verify Dataset or transform to Dataset.
Function verifies that provided value is a non-empty instance of Dataset,
otherwise raises an exception, but if the 'cast' flag is set to True it will
also try to transform provided value to the Dataset instance.
Parameters
----------
obj
value to verify
Raises
------
DeepchecksValueError
if the provided value is not a TextData instance;
if the provided value cannot be transformed into Dataset instance;
"""
if not isinstance(obj, cls):
raise DeepchecksValueError(f'{obj} is not a {cls.__name__} instance')
return obj.copy()
def validate_textdata_compatibility(self, other_text_data: 'TextData') -> bool:
"""Verify that all provided datasets share same label name and task types.
Parameters
----------
other_text_data : TextData
The other dataset TextData object to compare with.
Returns
-------
bool
True if provided dataset share same label name and task types.
"""
assert other_text_data is not None
if self.task_type != other_text_data.task_type:
return False
return True
def head(self, n_samples: int = 5, model_classes: list = None) -> pd.DataFrame:
"""Return a copy of the dataset as a pandas Dataframe with the first n_samples samples.
Parameters
----------
n_samples : int, default 5
Number of samples to return.
model_classes : list, default None
List of classes names to use for multi-label display. Only used if the dataset is multi-label.
Returns
-------
pd.DataFrame
A copy of the dataset as a pandas Dataframe with the first n_samples samples.
"""
if n_samples > len(self):
n_samples = len(self) - 1
result = pd.DataFrame({'text': self.text[:n_samples]}, index=self.get_original_text_indexes()[:n_samples])
if self.has_label():
result['label'] = self.label_for_display(model_classes=model_classes)[:n_samples]
if self._tokenized_text is not None:
result['tokenized_text'] = self.tokenized_text[:n_samples]
if self._metadata is not None:
result = result.join(self.metadata.loc[result.index])
return result
def len_when_sampled(self, n_samples: t.Optional[int]):
"""Return number of samples in the sampled dataframe this dataset is sampled with n_samples samples."""
if n_samples is None:
return self.n_samples
return min(self.n_samples, n_samples)
def is_sampled(self, n_samples: t.Optional[int]):
"""Return True if the dataset number of samples will decrease when sampled with n_samples samples."""
if n_samples is None:
return False
return self.n_samples > n_samples
@contextlib.contextmanager
def disable_deepchecks_logger():
"""Disable deepchecks root logger."""
logger = get_logger()
logger_state = logger.disabled
logger.disabled = True
yield
logger.disabled = logger_state