text stringlengths 1 1.02k | class_index int64 0 271 | source stringclasses 76
values |
|---|---|---|
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 |
```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 |
'label': tensor(1),
'input_ids': tensor([ 101, 18027, 16310, 16001, 1103, 9321, 178, 11604, 7235, 6617,
1742, 2165, 2820, 1206, 6588, 22572, 12937, 1811, 2153, 1105,
1147, 12890, 19587, 6463, 1105, 15026, 1482, 119, 102, 0,
0, 0, ... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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]),
'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
def with_transform(
self,
transform: Optional[Callable],
columns: Optional[List] = None,
output_all_columns: bool = False,
) -> "DatasetDict":
"""Set `__getitem__` return format using this transform. The transform is applied on-the-fly on batches when `__getitem__` is called.... | 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 [`~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 appl... | 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")
>>> def encode(example):
... return tokenizer(example['text'], truncation=T... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
179, 7766, 118, 172, 15554, 1181, 3498, 6961, 3263, 1137,
188, 1566, 7912, 14516, 6997, 119, 102]),
'token_type_ids': tensor([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, 0, 0, 0, 0, 0, 0, 0... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
def map(
self,
function: Optional[Callable] = None,
with_indices: bool = False,
with_rank: bool = False,
input_columns: Optional[Union[str, List[str]]] = None,
batched: bool = False,
batch_size: Optional[int] = 1000,
drop_last_batch: bool = False,
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
The transformation is applied to all the datasets of the dataset dictionary. | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
function (`callable`): with one of the following signature:
- `function(example: Dict[str, Any]) -> Dict[str, Any]` if `batched=False` and `with_indices=False`
- `function(example: Dict[str, Any], indices: int) -> Dict[str, Any]` if `batched=False` and `with_indices=Tru... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
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): ...`.
with_rank (`bool`, defaults to `False`):
Provide process rank to `function`. Note that in this ca... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
`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 should be
dropped instead of being processed by the function.
r... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
can be identified, use it instead of recomputing.
cache_file_names (`[Dict[str, str]]`, *optional*, defaults to `None`):
Provide the name of a path for the cache file. It is used to store the
results of the computation instead of the automatically generated cache file name.
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
disable_nullable (`bool`, defaults to `False`):
Disallow null values in the table.
fn_kwargs (`Dict`, *optional*, defaults to `None`):
Keyword arguments to be passed to `function`
num_proc (`int`, *optional*, defaults to `None`):
Number of processe... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Example:
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> def add_prefix(example):
... example["text"] = "Review: " + example["text"]
... return example
>>> ds = ds.map(add_prefix)
>>> ds["train"][0:3]["text... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
# process a batch of examples
>>> ds = ds.map(lambda example: tokenizer(example["text"]), batched=True)
# set number of processors
>>> ds = ds.map(add_prefix, num_proc=4)
```
"""
self._check_values_type()
if cache_file_names is None:
cache_file_names =... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
features=features,
disable_nullable=disable_nullable,
fn_kwargs=fn_kwargs,
num_proc=num_proc,
desc=desc,
)
for k, dataset in self.items()
}
) | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
def filter(
self,
function: Optional[Callable] = None,
with_indices: bool = False,
with_rank: bool = False,
input_columns: Optional[Union[str, List[str]]] = None,
batched: bool = False,
batch_size: Optional[int] = 1000,
keep_in_memory: bool = False,
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
- `function(example: Dict[str, Any]) -> bool` if `batched=False` and `with_indices=False` and `with_rank=False`
- `function(example: Dict[str, Any], *extra_args) -> bool` if `batched=False` and `with_indices=True` and/or `with_rank=True` (one extra arg for each)
- `function(batch: Dict[s... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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[, rank]): ...`.
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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`.
keep_in_memory (`bool`, defaults to `False`):
Keep the dataset in memory instead of writing it to a c... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Number of rows per write operation for the cache file writer.
This value is a good trade-off between memory usage during the processing, and processing speed.
Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.
fn... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Example: | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.filter(lambda x: x["label"] == 1)
DatasetDict({
train: Dataset({
features: ['text', 'label'],
num_rows: 4265
})
validation: Data... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
batch_size=batch_size,
keep_in_memory=keep_in_memory,
load_from_cache_file=load_from_cache_file,
cache_file_name=cache_file_names[k],
writer_batch_size=writer_batch_size,
fn_kwargs=fn_kwargs,
num_proc... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
def flatten_indices(
self,
keep_in_memory: bool = False,
cache_file_names: Optional[Dict[str, Optional[str]]] = None,
writer_batch_size: Optional[int] = 1000,
features: Optional[Features] = None,
disable_nullable: bool = False,
num_proc: Optional[int] = None,
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
keep_in_memory (`bool`, defaults to `False`):
Keep the dataset in memory instead of writing it to a cache file.
cache_file_names (`Dict[str, str]`, *optional*, default `None`):
Provide the name of a path for the cache file. It is used to store the
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Use a specific [`Features`] to store the cache file
instead of the automatically generated one.
disable_nullable (`bool`, defaults to `False`):
Allow null values in the table.
num_proc (`int`, optional, default `None`):
Max number of processes when... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
writer_batch_size=writer_batch_size,
features=features,
disable_nullable=disable_nullable,
num_proc=num_proc,
new_fingerprint=new_fingerprint,
)
for k, dataset in self.items()
}
) | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
def sort(
self,
column_names: Union[str, Sequence[str]],
reverse: Union[bool, Sequence[bool]] = False,
null_placement: str = "at_end",
keep_in_memory: bool = False,
load_from_cache_file: Optional[bool] = None,
indices_cache_file_names: Optional[Dict[str, Optional[... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
column_names (`Union[str, Sequence[str]]`):
Column name(s) to sort by.
reverse (`Union[bool, Sequence[bool]]`, defaults to `False`):
If `True`, sort by descending order rather than ascending. If a single bool is provided,
the value is applied... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
indices_cache_file_names (`[Dict[str, str]]`, *optional*, defaults to `None`):
Provide the name of a path for the cache file. It is used to store the
indices mapping instead of the automatically generated cache file name.
You have to provide one `cache_file_name` per data... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Example: | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset('rotten_tomatoes')
>>> ds['train']['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> sorted_ds = ds.sort('label')
>>> sorted_ds['train']['label'][:10]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> anoth... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
indices_cache_file_name=indices_cache_file_names[k],
writer_batch_size=writer_batch_size,
)
for k, dataset in self.items()
}
) | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
def shuffle(
self,
seeds: Optional[Union[int, Dict[str, Optional[int]]]] = None,
seed: Optional[int] = None,
generators: Optional[Dict[str, np.random.Generator]] = None,
keep_in_memory: bool = False,
load_from_cache_file: Optional[bool] = None,
indices_cache_file_... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
seeds (`Dict[str, int]` or `int`, *optional*):
A seed to initialize the default BitGenerator if `generator=None`.
If `None`, then fresh, unpredictable entropy will be pulled from the OS.
If an `int` or `array_like[ints]` is passed, then it will be passed... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
You have to provide one `generator` per dataset in the dataset dictionary.
keep_in_memory (`bool`, defaults to `False`):
Keep the dataset in memory instead of writing it to a cache file.
load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled):
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
This value is a good trade-off between memory usage during the processing, and processing speed.
Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Example:
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds["train"]["label"][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
# set a seed
>>> shuffled_ds = ds.shuffle(seed=42)
>>> shuffled_ds["train"]["label"][:10]
[0, 1, 0, 1, 0, 0, 0, 0, 0, 0]
```
"""
self._check_values_type()
if seed is not None and seeds is not None:
raise ValueError("Please specify seed or seeds, but no... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
indices_cache_file_name=indices_cache_file_names[k],
writer_batch_size=writer_batch_size,
)
for k, dataset in self.items()
}
) | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
def save_to_disk(
self,
dataset_dict_path: PathLike,
max_shard_size: Optional[Union[str, int]] = None,
num_shards: Optional[Dict[str, int]] = None,
num_proc: Optional[int] = None,
storage_options: Optional[dict] = None,
):
"""
Saves a dataset dict to a... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
dataset_dict_path (`path-like`):
Path (e.g. `dataset/train`) or remote URI (e.g. `s3://my-bucket/dataset/train`)
of the dataset dict directory where the dataset dict will be saved to.
max_shard_size (`int` or `str`, *optional*, defaults to `"500MB"`):
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
<Added version="2.8.0"/>
num_proc (`int`, *optional*, default `None`):
Number of processes when downloading and generating the dataset locally.
Multiprocessing is disabled by default.
<Added version="2.8.0"/>
storage_options (`dict`, *optional*):
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
if num_shards is None:
num_shards = {k: None for k in self}
elif not isinstance(num_shards, dict):
raise ValueError(
"Please provide one `num_shards` per dataset in the dataset dictionary, e.g. {{'train': 128, 'test': 4}}"
)
fs.makedirs(dataset_dict_p... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
@staticmethod
def load_from_disk(
dataset_dict_path: PathLike,
keep_in_memory: Optional[bool] = None,
storage_options: Optional[dict] = None,
) -> "DatasetDict":
"""
Load a dataset that was previously saved using [`save_to_disk`] from a filesystem using `fsspec.spec.Abstr... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
dataset_dict_path (`path-like`):
Path (e.g. `"dataset/train"`) or remote URI (e.g. `"s3//my-bucket/dataset/train"`)
of the dataset dict directory where the dataset dict will be loaded from.
keep_in_memory (`bool`, defaults to `None`):
Whether... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> ds = load_from_disk('path/to/dataset/directory')
```
"""
fs: fsspec.AbstractFileSystem
fs, dataset_dict_path = url_to_fs(dataset_dict_path, **(storage_options or {})) | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
dataset_dict_json_path = posixpath.join(dataset_dict_path, config.DATASETDICT_JSON_FILENAME)
dataset_state_json_path = posixpath.join(dataset_dict_path, config.DATASET_STATE_JSON_FILENAME)
dataset_info_path = posixpath.join(dataset_dict_path, config.DATASET_INFO_FILENAME)
if not fs.isfile(datase... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
dataset_dict = DatasetDict()
for k in splits:
dataset_dict_split_path = posixpath.join(fs.unstrip_protocol(dataset_dict_path), k)
dataset_dict[k] = Dataset.load_from_disk(
dataset_dict_split_path, keep_in_memory=keep_in_memory, storage_options=storage_options
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
path_or_paths (`dict` of path-like):
Path(s) of the CSV file(s).
features ([`Features`], *optional*):
Dataset features.
cache_dir (str, *optional*, defaults to `"~/.cache/huggingface/datasets"`):
Directory to cache data.
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
return CsvDatasetReader(
path_or_paths, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, **kwargs
).read()
@staticmethod
def from_json(
path_or_paths: Dict[str, PathLike],
features: Optional[Features] = None,
cache_dir: str = None,
keep_... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
path_or_paths (`path-like` or list of `path-like`):
Path(s) of the JSON Lines file(s).
features ([`Features`], *optional*):
Dataset features.
cache_dir (str, *optional*, defaults to `"~/.cache/huggingface/datasets"`):
Directory to... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
return JsonDatasetReader(
path_or_paths, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, **kwargs
).read()
@staticmethod
def from_parquet(
path_or_paths: Dict[str, PathLike],
features: Optional[Features] = None,
cache_dir: str = None,
k... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
path_or_paths (`dict` of path-like):
Path(s) of the CSV file(s).
features ([`Features`], *optional*):
Dataset features.
cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`):
Directory to cache data.
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_parquet({'train': 'path/to/dataset/parquet'})
```
"""
# Dynamic import to avoid circular dependency
from .io.parquet import ParquetDatasetReader
return ParquetDatasetReader(
path_or_... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
path_or_paths (`dict` of path-like):
Path(s) of the text file(s).
features ([`Features`], *optional*):
Dataset features.
cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`):
Directory to cache data.
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
return TextDatasetReader(
path_or_paths, features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, **kwargs
).read()
@is_documented_by(Dataset.align_labels_with_mapping)
def align_labels_with_mapping(self, label2id: Dict, label_column: str) -> "DatasetDict":
self._check... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
def push_to_hub(
self,
repo_id,
config_name: str = "default",
set_default: Optional[bool] = None,
data_dir: Optional[str] = None,
commit_message: Optional[str] = None,
commit_description: Optional[str] = None,
private: Optional[bool] = None,
token:... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
The resulting Parquet files are self-contained by default: if your dataset contains [`Image`] or [`Audio`]
data, the Parquet files will store the bytes of your images or audio files.
You can disable this by setting `embed_external_files` to False. | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Args:
repo_id (`str`):
The ID of the repository to push to in the following format: `<user>/<dataset_name>` or
`<org>/<dataset_name>`. Also accepts `<dataset_name>`, which will default to the namespace
of the logged-in user.
config_name (`str`):
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
<Added version="2.17.0"/>
commit_message (`str`, *optional*):
Message to commit while pushing. Will default to `"Upload dataset"`.
commit_description (`str`, *optional*):
Description of the commit that will be created.
Additionally, description of ... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
<Added version="2.16.0"/>
private (`bool`, *optional*):
Whether to make the repo private. If `None` (default), the repo will be public unless the
organization's default is private. This value is ignored if the repo already exists.
token (`str`, *optional*):
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
<Added version="2.15.0"/>
max_shard_size (`int` or `str`, *optional*, defaults to `"500MB"`):
The maximum size of the dataset shards to be uploaded to the hub. If expressed as a string, needs to be digits followed by a unit
(like `"500MB"` or `"1GB"`).
num_shards ... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```python
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", private=True)
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", max_shard_size="1GB")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", nu... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```python
>>> english_dataset.push_to_hub("<organization>/<dataset_id>", "en")
>>> french_dataset.push_to_hub("<organization>/<dataset_id>", "fr")
>>> # later
>>> english_dataset = load_dataset("<organization>/<dataset_id>", "en")
>>> french_dataset = load_dataset("<organization>... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
for split in self.keys():
if not re.match(_split_re, split):
raise ValueError(f"Split name should match '{_split_re}' but got '{split}'.")
api = HfApi(endpoint=config.HF_ENDPOINT, token=token)
repo_url = api.create_repo(
repo_id,
token=token,
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
additions = []
for split in self.keys():
logger.info(f"Pushing split {split} to the Hub.")
# The split=key needs to be removed before merging
split_additions, uploaded_size, dataset_nbytes = self[split]._push_parquet_shards_to_hub(
repo_id,
dat... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
info_to_dump.dataset_size = total_dataset_nbytes
info_to_dump.size_in_bytes = total_uploaded_size + total_dataset_nbytes | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
# Check if the repo already has a README.md and/or a dataset_infos.json to update them with the new split info (size and pattern)
# and delete old split shards (if they exist)
repo_with_dataset_card, repo_with_dataset_infos = False, False
repo_splits = [] # use a list to keep the order of the s... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
and repo_file.rfilename not in repo_files_to_add
):
deletions.append(CommitOperationDelete(path_in_repo=repo_file.rfilename))
elif fnmatch.fnmatch(
repo_file.rfilename, PUSH_TO_HUB_WITHOUT_METADATA_CONFIGS_SPLIT_PATTERN_SHARDED.replace("{split}", "*")
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
# get the info from the README to update them
if repo_with_dataset_card:
dataset_card_path = api.hf_hub_download(
repo_id, config.REPOCARD_FILENAME, repo_type="dataset", revision=revision
)
dataset_card = DatasetCard.load(Path(dataset_card_path))
d... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
default_metadata_configs_to_dump = {
"data_files": [{"split": split, "path": f"data/{split}-*"} for split in repo_splits]
}
MetadataConfigs({"default": default_metadata_configs_to_dump}).to_dataset_card_data(dataset_card_data)
metadata_config_to_dump = {
"data... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
metadata_config_to_dump["default"] = True
# push to the deprecated dataset_infos.json
if repo_with_dataset_infos:
dataset_infos_path = api.hf_hub_download(
repo_id, config.DATASETDICT_INFOS_FILENAME, repo_type="dataset", revision=revision
)
with open(d... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
dataset_card = DatasetCard(f"---\n{dataset_card_data}\n---\n") if dataset_card is None else dataset_card
additions.append(
CommitOperationAdd(path_in_repo=config.REPOCARD_FILENAME, path_or_fileobj=str(dataset_card).encode())
) | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
commit_message = commit_message if commit_message is not None else "Upload dataset"
if len(additions) <= config.UPLOADS_MAX_NUMBER_PER_COMMIT:
commit_info = api.create_commit(
repo_id,
operations=additions + deletions,
commit_message=commit_message,
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
] + (deletions if i == 0 else [])
commit_info = api.create_commit(
repo_id,
operations=operations,
commit_message=commit_message + f" (part {i:05d}-of-{num_commits:05d})",
commit_description=commit_description,
... | 34 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
class IterableDatasetDict(dict):
def __repr__(self):
repr = "\n".join([f"{k}: {v}" for k, v in self.items()])
repr = re.sub(r"^", " " * 4, repr, 0, re.M)
return f"IterableDatasetDict({{\n{repr}\n}})"
def with_format(
self,
type: Optional[str] = None,
) -> "IterableDa... | 35 | /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", split="validation", streaming=True)
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], trun... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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, ... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])}
```
"""
return IterableDatasetDict({k: dataset.with_format(type=type) for k, dataset in self.items()}) | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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: int = 1000,
drop_last_batch: bool = False,
remove_columns: Optional[Union[str, List[st... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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.
... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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` ... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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 (`... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Number of examples per batch provided to `function` if `batched=True`.
drop_last_batch (`bool`, defaults to `False`):
Whether a last batch smaller than the `batch_size` should be
dropped instead of being processed by the function.
remove_columns (`[List[str]]`, *o... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Example: | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> def add_prefix(example):
... example["text"] = "Review: " + example["text"]
... return example
>>> ds = ds.map(add_prefix)
>>> next(iter(ds["train"]))
... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
)
for k, dataset in self.items()
}
) | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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,
) -> "IterableDatasetDict":
"""... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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`
... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> ds = ds.filter(lambda x: x["label"] == 0)
>>> list(ds["train"].take(3))
[{'label': 0, 'text': 'Review: simplistic , silly and tedious .'},
{'label': 0,
'text... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
for k, dataset in self.items()
}
) | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
def shuffle(
self, seed=None, generator: Optional[np.random.Generator] = None, buffer_size: int = 1000
) -> "IterableDatasetDict":
"""
Randomly shuffles the elements of this dataset.
The shuffling is applied to all the datasets of the dataset dictionary.
This dataset fills a... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
If the dataset is made of several shards, it also does `shuffle` the order of the shards.
However if the order has been fixed by using [`~datasets.IterableDataset.skip`] or [`~datasets.IterableDataset.take`]
then the order of the shards is kept unchanged.
Args:
seed (`int`, *optiona... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", streaming=True)
>>> list(ds["train"].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 arnold s... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.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 ."}]
```
"""
return Iter... | 35 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/dataset_dict.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.