text
stringlengths
1
1.02k
class_index
int64
0
271
source
stringclasses
76 values
if self._formatting and (ex_iterable.iter_arrow or self._formatting.format_type == "arrow"): if ex_iterable.iter_arrow: iterator = ex_iterable.iter_arrow() else: iterator = _convert_to_arrow(ex_iterable, batch_size=1) for key, pa_table in iterator: ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
Args: batch_size (:obj:`int`): size of each batch to yield. drop_last_batch (:obj:`bool`, default `False`): Whether a last batch smaller than the batch_size should be dropped """ if self._formatting: formatter = get_formatter(self._formatting.format_t...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
ex_iterable = self._prepare_ex_iterable_for_iteration(batch_size=batch_size, drop_last_batch=drop_last_batch) if self._formatting and (ex_iterable.iter_arrow or self._formatting == "arrow"): if ex_iterable.iter_arrow: iterator = ex_iterable.iter_arrow() else: ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
iterator = iter(ex_iterable) for key, example in iterator: # If batched, first build the batch examples = [example] + [example for key, example in islice(iterator, batch_size - 1)] if drop_last_batch and len(examples) < batch_size: # ignore last batch return ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
@staticmethod def from_generator( generator: Callable, features: Optional[Features] = None, gen_kwargs: Optional[dict] = None, split: NamedSplit = Split.TRAIN, ) -> "IterableDataset": """Create an Iterable Dataset from a generator. Args: generator (`C...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
<Added version="2.21.0"/> Returns: `IterableDataset` Example: ```py >>> def gen(): ... yield {"text": "Good", "label": 0} ... yield {"text": "Bad", "label": 1} ... >>> ds = IterableDataset.from_generator(gen) ```
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> def gen(shards): ... for shard in shards: ... with open(shard) as f: ... for line in f: ... yield {"line": line} ... >>> shards = [f"data{i}.txt" for i in range(32)] >>> ds = IterableDataset.from_generator(...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
@staticmethod def from_spark( df: "pyspark.sql.DataFrame", split: Optional[NamedSplit] = None, features: Optional[Features] = None, **kwargs, ) -> "IterableDataset": """Create an IterableDataset from Spark DataFrame. The dataset is streamed to the driver in batches. ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
if sys.platform == "win32": raise EnvironmentError("IterableDataset.from_spark is not currently supported on Windows") return SparkDatasetReader( df, split=split, features=features, streaming=True, **kwargs, ).read() @staticme...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def with_format( self, type: Optional[str] = None, ) -> "IterableDataset": """ Return a dataset with the specified format. The 'pandas' format is currently not implemented. Args: type (`str`, *optional*): Either output type selected in `[...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes", split="validation", streaming=True) >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(x['text'], trun...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])} ``` """ type = get_format_type_from_alias(type) # TODO(QL): add format_kwargs # TODO(QL): add format_columns and return_all_columns # TODO(QL): add pandas format return IterableDataset( ex_iterable=self._ex_iterabl...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def map( self, function: Optional[Callable] = None, with_indices: bool = False, input_columns: Optional[Union[str, List[str]]] = None, batched: bool = False, batch_size: Optional[int] = 1000, drop_last_batch: bool = False, remove_columns: Optional[Union[st...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
- If batched is `False`, then the function takes 1 example in and should return 1 example. An example is a dictionary, e.g. `{"text": "Hello there !"}`. - If batched is `True` and `batch_size` is 1, then the function takes a batch of 1 example as input and can return a batch with 1 or more examples. ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
Args: function (`Callable`, *optional*, defaults to `None`): Function applied on-the-fly on the examples when you iterate on the dataset. It must have one of the following signatures: - `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
For advanced usage, the function can also return a `pyarrow.Table`. Moreover if your function returns nothing (`None`), then `map` will run your function and return the dataset unchanged. If no function is provided, default to identity function: `lambda x: x`. with_indices (`...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
Number of examples per batch provided to `function` if `batched=True`. `batch_size <= 0` or `batch_size == None` then provide the full dataset as a single batch to `function`. drop_last_batch (`bool`, defaults to `False`): Whether a last batch smaller than the batch_size shou...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
Example:
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> def add_prefix(example): ... example["text"] = "Review: " + example["text"] ... return example >>> ds = ds.map(add_prefix) >>> list(ds.t...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
input_columns = [input_columns] if isinstance(remove_columns, str): remove_columns = [remove_columns] if function is None: function = identity_func if fn_kwargs is None: fn_kwargs = {}
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
ex_iterable = self._ex_iterable # no need to apply features if ex_iterable is typed and if there was no cast_column() input_features = ( None if (ex_iterable.is_typed and (self._info.features is None or self._info.features == ex_iterable.features)) else self._info.fea...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
if self._formatting and self._formatting.format_type == "arrow": # apply formatting before iter_arrow to keep map examples iterable happy ex_iterable = FormattedExamplesIterable( ex_iterable, formatting=copy.deepcopy(self._formatting), features=inp...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
ex_iterable = FormattedExamplesIterable( ex_iterable, formatting=copy.deepcopy(self._formatting), features=input_features, token_per_repo_id=self._token_per_repo_id, )
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
ex_iterable = MappedExamplesIterable( ex_iterable, function=function, with_indices=with_indices, input_columns=input_columns, batched=batched, batch_size=batch_size, drop_last_batch=drop_last_batch, remove_columns=remove_col...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def filter( self, function: Optional[Callable] = None, with_indices=False, input_columns: Optional[Union[str, List[str]]] = None, batched: bool = False, batch_size: Optional[int] = 1000, fn_kwargs: Optional[dict] = None, ) -> "IterableDataset": """Appl...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
- `function(example: Dict[str, Any]) -> bool` if `with_indices=False, batched=False` - `function(example: Dict[str, Any], indices: int) -> bool` if `with_indices=True, batched=False` - `function(example: Dict[str, List]) -> List[bool]` if `with_indices=False, batched=True` ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
If no function is provided, defaults to an always True function: `lambda x: True`. with_indices (`bool`, defaults to `False`): Provide example indices to `function`. Note that in this case the signature of `function` should be `def function(example, idx): ...`. input_columns (`st...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> ds = ds.filter(lambda x: x["label"] == 0) >>> list(ds.take(3)) [{'label': 0, 'movie_review': 'simplistic , silly and tedious .'}, {'label': 0, ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
# We need the examples to be decoded for certain feature types like Image or Audio, # format and type before filtering ex_iterable = self._ex_iterable if self._info.features or self._formatting: ex_iterable = FormattedExamplesIterable( ex_iterable, for...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
ex_iterable = FilteredExamplesIterable( ex_iterable, function=function, with_indices=with_indices, input_columns=input_columns, batched=batched, batch_size=batch_size, fn_kwargs=fn_kwargs, formatting=self._formatting, ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
This dataset fills a buffer with `buffer_size` elements, then randomly samples elements from this buffer, replacing the selected elements with new elements. For perfect shuffling, a buffer size greater than or equal to the full size of the dataset is required. For instance, if your dataset cont...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
Args: seed (`int`, *optional*, defaults to `None`): Random seed that will be used to shuffle the dataset. It is used to sample from the shuffle buffer and also to shuffle the data shards. generator (`numpy.random.Generator`, *optional*): Numpy rand...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> list(ds.take(3)) [{'label': 1, 'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than ar...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
'text': 'at its best , the good girl is a refreshingly adult take on adultery . . .'}, {'label': 1, 'text': "sam jones became a very lucky filmmaker the day wilco got dropped from their record label , proving that one man's ruin may be another's fortune ."}] ``` """ if generato...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def set_epoch(self, epoch: int): self._epoch += epoch - self._epoch # update torch value in shared memory in-place def skip(self, n: int) -> "IterableDataset": """ Create a new [`IterableDataset`] that skips the first `n` elements. Args: n (`int`): Numb...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> list(ds.take(3)) [{'label': 1, 'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than ar...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
'text': 'the gorgeously elaborate continuation of " the lord of the rings " trilogy is so huge that a column of words cannot adequately describe co-writer/director peter jackson\'s expanded vision of j . r . r . tolkien\'s middle-earth .'}, {'label': 1, 'text': 'effective but too-tepid biopic'}, {'lab...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
token_per_repo_id=self._token_per_repo_id, )
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def take(self, n: int) -> "IterableDataset": """ Create a new [`IterableDataset`] with only the first `n` elements. Args: n (`int`): Number of elements to take. Example:
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> small_ds = ds.take(2) >>> list(small_ds) [{'label': 1, 'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to ma...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
info=self._info.copy(), split=self._split, formatting=self._formatting, shuffling=copy.deepcopy(self._shuffling), distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, )
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def shard( self, num_shards: int, index: int, contiguous: bool = True, ) -> "IterableDataset": """Return the `index`-nth shard from dataset split into `num_shards` pieces. This shards deterministically. `dataset.shard(n, i)` splits the dataset into contiguous chunks,...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
On the other hand, `dataset.shard(n, i, contiguous=False)` contains all the shards of the dataset whose index mod `n = i`. Be sure to shard before using any randomizing operator (such as `shuffle`). It is best if the shard operator is used early in the dataset pipeline. Args: num_s...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("amazon_polarity", split="train", streaming=True) >>> ds Dataset({ features: ['label', 'title', 'content'], num_shards: 4 }) >>> ds.shard(num_shards=2, index=0) Dataset({ ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
@property def column_names(self) -> Optional[List[str]]: """Names of the columns in the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation", streaming=True) >>> ds.column_names ['text', 'l...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def rename_column(self, original_column_name: str, new_column_name: str) -> "IterableDataset": """ Rename a column in the dataset, and move the features associated to the original column under the new column name. Args: original_column_name (`str`): Name of t...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> next(iter(ds)) {'label': 1, 'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnol...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def rename_columns(self, column_mapping: Dict[str, str]) -> "IterableDataset": """ Rename several columns in the dataset, and move the features associated to the original columns under the new column names. Args: column_mapping (`Dict[str, str]`): A mapping of columns to ren...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def remove_columns(self, column_names: Union[str, List[str]]) -> "IterableDataset": """ Remove one or several column(s) in the dataset and the features associated to them. The removal is done on-the-fly on the examples when iterating over the dataset. Args: column_names (`U...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> next(iter(ds)) {'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , je...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
del ds_iterable._info.features[col]
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
return ds_iterable def select_columns(self, column_names: Union[str, List[str]]) -> "IterableDataset": """Select one or several column(s) in the dataset and the features associated to them. The selection is done on-the-fly on the examples when iterating over the dataset. Args: ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> next(iter(ds)) {'text': 'the rock is destined to be the 21st century\'s new " conan " and that he\'s going to make a splash even greater than arnold schwarzenegger , je...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
if self._info: info = copy.deepcopy(self._info) if self._info.features is not None: missing_columns = set(column_names) - set(self._info.features.keys()) if missing_columns: raise ValueError( f"Column name {list(missing_...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def cast_column(self, column: str, feature: FeatureType) -> "IterableDataset": """Cast column to feature for decoding. Args: column (`str`): Column name. feature (`Feature`): Target feature. Returns: `IterableDataset` ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset, Audio >>> ds = load_dataset("PolyAI/minds14", name="en-US", split="train", streaming=True) >>> ds.features {'audio': Audio(sampling_rate=8000, mono=True, decode=True, id=None), 'english_transcription': Value(dtype='string', id=None), ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
{'audio': Audio(sampling_rate=16000, mono=True, decode=True, id=None), 'english_transcription': Value(dtype='string', id=None), 'intent_class': ClassLabel(num_classes=14, names=['abroad', 'address', 'app_error', 'atm_limit', 'balance', 'business_loan', 'card_issues', 'cash_deposit', 'direct_debit', '...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
shuffling=copy.deepcopy(self._shuffling), distributed=copy.deepcopy(self._distributed), token_per_repo_id=self._token_per_repo_id, )
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def cast( self, features: Features, ) -> "IterableDataset": """ Cast the dataset to a new set of features. Args: features ([`Features`]): New features to cast the dataset to. The name of the fields in the features must match the cu...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
```py >>> from datasets import load_dataset, ClassLabel, Value >>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True) >>> ds.features {'label': ClassLabel(names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} >>> new_features = ds.featu...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
token_per_repo_id=self._token_per_repo_id, )
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def _step(self, step: int, offset: int) -> "IterableDataset": ex_iterable = StepExamplesIterable(self._ex_iterable, step=step, offset=offset) return IterableDataset( ex_iterable=ex_iterable, info=self._info.copy(), split=self._split, formatting=self._forma...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
def _resolve_features(self): if self.features is not None: return self elif self._ex_iterable.is_typed: features = self._ex_iterable.features else: features = _infer_features_from_batch(self.with_format(None)._head()) info = self.info.copy() in...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
Args: batch_size (`int`): The number of samples in each batch. drop_last_batch (`bool`, defaults to `False`): Whether to drop the last incomplete batch. Example: ```py >>> ds = load_dataset("some_dataset", streaming=True) >>> batched_ds = ds.batch(batch_size=32) ...
33
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/iterable_dataset.py
class DatasetDict(dict): """A dictionary (dict of str: datasets.Dataset) with dataset transforms methods (map, filter, etc.)""" def _check_values_type(self): for dataset in self.values(): if not isinstance(dataset, Dataset): raise TypeError(f"Values in `DatasetDict` should b...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def __exit__(self, exc_type, exc_val, exc_tb): # Here `del` is used to del the pyarrow tables. This properly closes the files used for memory mapped tables for dataset in self.values(): if hasattr(dataset, "_data"): del dataset._data if hasattr(dataset, "_indices"...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def __getitem__(self, k) -> Dataset: if isinstance(k, (str, NamedSplit)) or len(self) == 0: return super().__getitem__(k) else: available_suggested_splits = [ split for split in (Split.TRAIN, Split.TEST, Split.VALIDATION) if split in self ] ...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.data ``` """ self._check_values_type() return {k: dataset.data for k, dataset in self.items()} @property def cache_files(self) -> Dict[str, Dict]: """The c...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.cache_files {'test': [{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_mo...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
@property def num_columns(self) -> Dict[str, int]: """Number of columns in each split of the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.num_columns {'test': 2, 'train': 2, 'validation': 2} ...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
@property def column_names(self) -> Dict[str, List[str]]: """Names of the columns in each split of the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.column_names {'test': ['text', 'label'], ...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def flatten(self, max_depth=16) -> "DatasetDict": """Flatten the Apache Arrow Table of each split (nested features are flatten). Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged. Example:
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("squad") >>> ds["train"].features {'answers': Sequence(feature={'text': Value(dtype='string', id=None), 'answer_start': Value(dtype='int32', id=None)}, length=-1, id=None), 'context': Value(dtype='string', id=None...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
return DatasetDict({k: dataset.flatten(max_depth=max_depth) for k, dataset in self.items()})
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def unique(self, column: str) -> Dict[str, List]: """Return a list of the unique elements in a column for each split. This is implemented in the low-level backend and as such, very fast. Args: column (`str`): column name (list all the column names with [`~datasets.D...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def cleanup_cache_files(self) -> Dict[str, int]: """Clean up all cache files in the dataset cache directory, excepted the currently used cache file if there is one. Be careful when running this command that no other process is currently using other cache files. Return: `Dict` with t...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def cast(self, features: Features) -> "DatasetDict": """ Cast the dataset to a new set of features. The transformation is applied to all the datasets of the dataset dictionary. Args: features ([`Features`]): New features to cast the dataset to. ...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
```py >>> from datasets import load_dataset, ClassLabel, Value >>> ds = load_dataset("rotten_tomatoes") >>> ds["train"].features {'label': ClassLabel(names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} >>> new_features = ds["train"].features.copy() ...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
Args: column (`str`): Column name. feature ([`Feature`]): Target feature. Returns: [`DatasetDict`] Example: ```py >>> from datasets import load_dataset, ClassLabel >>> ds = load_dataset("rotten_tomatoes") ...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def remove_columns(self, column_names: Union[str, List[str]]) -> "DatasetDict": """ Remove one or several column(s) from each split in the dataset and the features associated to the column(s). The transformation is applied to all the splits of the dataset dictionary. You can al...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds = ds.remove_columns("label") DatasetDict({ train: Dataset({ features: ['text'], num_rows: 8530 }) validation: Dataset({ ...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
You can also rename a column using [`~DatasetDict.map`] with `remove_columns` but the present method: - takes care of moving the original features under the new column name. - doesn't copy the data to a new dataset and is thus much faster. Args: original_column_name (`str`):...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds = ds.rename_column("label", "label_new") DatasetDict({ train: Dataset({ features: ['text', 'label_new'], num_rows: 8530 }) valid...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def rename_columns(self, column_mapping: Dict[str, str]) -> "DatasetDict": """ Rename several columns in the dataset, and move the features associated to the original columns under the new column names. The transformation is applied to all the datasets of the dataset dictionary. ...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes") >>> ds.rename_columns({'text': 'text_new', 'label': 'label_new'}) DatasetDict({ train: Dataset({ features: ['text_new', 'label_new'], num_rows: 8530 ...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
The transformation is applied to all the splits of the dataset dictionary. Args: column_names (`Union[str, List[str]]`): Name of the column(s) to keep. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomato...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def class_encode_column(self, column: str, include_nulls: bool = False) -> "DatasetDict": """Casts the given column as [`~datasets.features.ClassLabel`] and updates the tables. Args: column (`str`): The name of the column to cast. include_nulls (`bool`, defaults ...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("boolq") >>> ds["train"].features {'answer': Value(dtype='bool', id=None), 'passage': Value(dtype='string', id=None), 'question': Value(dtype='string', id=None)} >>> ds = ds.class_encode_column("a...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
@contextlib.contextmanager def formatted_as( self, type: Optional[str] = None, columns: Optional[List] = None, output_all_columns: bool = False, **format_kwargs, ): """To be used in a `with` statement. Set `__getitem__` return format (type and columns). Th...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
Args: type (`str`, *optional*): Output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default). columns (`List[str]`, *optional*): Columns to format in the out...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
old_format_columns = {k: dataset._format_columns for k, dataset in self.items()} old_output_all_columns = {k: dataset._output_all_columns for k, dataset in self.items()} try: self.set_format(type, columns, output_all_columns, **format_kwargs) yield finally: fo...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def set_format( self, type: Optional[str] = None, columns: Optional[List] = None, output_all_columns: bool = False, **format_kwargs, ): """Set `__getitem__` return format (type and columns). The format is set for every dataset in the dataset dictionary.
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
Args: type (`str`, *optional*): Output type selected in `[None, 'numpy', 'torch', 'tensorflow', 'pandas', 'arrow', 'jax']`. `None` means `__getitem__` returns python objects (default). columns (`List[str]`, *optional*): Columns to format in the out...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
`new formatted columns = (all columns - previously unformatted columns)` Example: ```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def reset_format(self): """Reset `__getitem__` return format to python objects and all columns. The transformation is applied to all the datasets of the dataset dictionary. Same as `self.set_format()` Example:
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
```py >>> from datasets import load_dataset >>> from transformers import AutoTokenizer >>> ds = load_dataset("rotten_tomatoes") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") >>> ds = ds.map(lambda x: tokenizer(x["text"], truncation=True, padding=True), batched=...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def set_transform( self, transform: Optional[Callable], columns: Optional[List] = None, output_all_columns: bool = False, ): """Set ``__getitem__`` return format using this transform. The transform is applied on-the-fly on batches when ``__getitem__`` is called. The t...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
Args: transform (`Callable`, optional): user-defined formatting transform, replaces the format defined by :func:`datasets.Dataset.set_format` A formatting function is a callable that takes a batch (as a dict) as input and returns a batch. This function is applied right before...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py
def with_format( self, type: Optional[str] = None, columns: Optional[List] = None, output_all_columns: bool = False, **format_kwargs, ) -> "DatasetDict": """Set `__getitem__` return format (type and columns). The data formatting is applied on-the-fly. The form...
34
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py