text
stringlengths
1
1.02k
class_index
int64
0
271
source
stringclasses
76 values
num_examples_progress_update = 0 # If `update_data` is True after processing the first example/batch, initalize these resources with `init_buffer_and_writer` buf_writer, writer, tmp_file = None, None, None # Check if Polars is available and import it if so if config.POLARS_AVAILABLE and...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# Loop over single examples or batches and write to buffer/file if examples are to be updated if not batched: shard_iterable = enumerate(arrow_formatted_shard) else: num_rows = len(shard) if not drop_last_batch else len(shard) // batch_size * batch...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if isinstance(example, pa.Table): writer.write_row(example) elif isinstance(example, pd.DataFrame): writer.write_row(pa.Table.from_pandas(example)) elif ( config.POLARS...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
else: _time = time.time() for i, batch in shard_iterable: num_examples_in_batch = len(batch) indices = list( range(*(slice(i, i + batch_size).indices(shard.num_rows))) ) # Somethi...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
"Using `.map` in batched mode on a dataset with attached indexes is allowed only if it doesn't create or remove existing examples. You can first run `.drop_index() to remove your index and then re-add it." ) from None if update_data: if i =...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
else: writer.write_batch(batch) num_examples_progress_update += num_examples_in_batch if time.time() > _time + config.PBAR_REFRESH_TIME_INTERVAL: _time = time.time() yield rank, False,...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
os.remove(tmp_file.name) raise
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
yield rank, False, num_examples_progress_update if update_data and tmp_file is not None: tmp_file.close() shutil.move(tmp_file.name, cache_file_name) umask = os.umask(0o666) os.umask(umask) os.chmod(cache_file_name, 0o666 & ~umask) if update_d...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@transmit_format @fingerprint_transform(inplace=False) def batch( self, batch_size: int, drop_last_batch: bool = False, num_proc: Optional[int] = None, new_fingerprint: Optional[str] = None, ) -> "Dataset": """ Group samples from the dataset into batch...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Returns: [`Dataset`]: A new Dataset where each item is a batch of multiple samples from the original dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train") >>> batched_ds = ds.batch(batch_size=4) ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@transmit_format @fingerprint_transform( inplace=False, ignore_kwargs=["load_from_cache_file", "cache_file_name", "desc"], version="2.0.1" ) def filter( self, function: Optional[Callable] = None, with_indices: bool = False, with_rank: bool = False, input_colum...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
and update the table so that the dataset only includes examples according to the filter function.
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: function (`Callable`): Callable with one of the following signatures: - `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...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_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[, rank]): ...`. ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Number of examples per batch provided to `function` if `batched = True`. If `batched = False`, one example per batch is passed to `function`. If `batch_size <= 0` or `batch_size == None`, provide the full dataset as a single batch to `function`. keep_in_memory (`bool`, defaul...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.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...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
new_fingerprint (`str`, *optional*): The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments. desc (`str`, *optional*, defaults to `None`): Meaningful ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.filter(lambda x: x["label"] == 1) Dataset({ features: ['text', 'label'], num_rows: 533 }) ``` """ if l...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
indices = self.map( function=partial( get_indices_from_mask_function, function, batched, with_indices, with_rank, input_columns, self._indices, ), with_indices=True, ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
new_dataset._indices = indices.data new_dataset._fingerprint = new_fingerprint return new_dataset
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@transmit_format @fingerprint_transform(inplace=False, ignore_kwargs=["cache_file_name"]) def flatten_indices( self, keep_in_memory: bool = False, cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, features: Optional[Features] = None, ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: keep_in_memory (`bool`, defaults to `False`): Keep the dataset in memory instead of writing it to a cache file. cache_file_name (`str`, *optional*, default `None`): Provide the name of a path for the cache file. It is used to store the result...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
disable_nullable (`bool`, defaults to `False`): Allow null values in the table. num_proc (`int`, optional, default `None`): Max number of processes when generating cache. Already cached shards are loaded sequentially new_fingerprint (`str`, *optional*, defaults to...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
return self.map( batched=True, # for speed keep_in_memory=keep_in_memory, cache_file_name=cache_file_name, writer_batch_size=writer_batch_size, features=features, disable_nullable=disable_nullable, new_fingerprint=new_fingerprint, ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if fingerprint is None: raise ValueError("please specify a fingerprint for the dataset with indices") if indices_cache_file_name is not None: indices_table = MemoryMappedTable.from_file(indices_cache_file_name) else: indices_table = InMemoryTable.from_buffer(indices_...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@transmit_format @fingerprint_transform(inplace=False, ignore_kwargs=["indices_cache_file_name"]) def select( self, indices: Iterable, keep_in_memory: bool = False, indices_cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, new_fingerp...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: indices (`range`, `list`, `iterable`, `ndarray` or `Series`): Range, list or 1D-array of integer indices for indexing. If the indices correspond to a contiguous range, the Arrow table is simply sliced. However passing a list of indices that are not conti...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.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`. new_fingerprint (`str`, *optional*, defaults to `None`): The new...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.select(range(4)) Dataset({ features: ['text', 'label'], num_rows: 4 }) ``` """ if keep_in_memory and i...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# If indices is a PyArrow array, we convert to NumPy if isinstance(indices, (pa.Array, pa.ChunkedArray)): indices = indices.to_numpy().astype(np.int64) # Convert generator objects to lists if isinstance(indices, Iterator): indices = list(indices)
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# If the indices are contiguous, simply slice the arrow table if isinstance(indices, range): if _is_range_contiguous(indices) and indices.start >= 0: start, length = indices.start, indices.stop - indices.start return self._select_contiguous(start, length, new_fingerpr...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# If not contiguous, we need to create a new indices mapping return self._select_with_indices_mapping( indices, keep_in_memory=keep_in_memory, indices_cache_file_name=indices_cache_file_name, writer_batch_size=writer_batch_size, new_fingerprint=new_fin...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: start (`int`): start index. length (`int`): length of the slice to select. new_fingerprint (`str`, optional, default `None`): the new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint,...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# If the array is empty we do nothing if len(self) == 0: return self _check_valid_indices_value(start, len(self)) _check_valid_indices_value(start + length - 1, len(self)) if self._indices is None or length == 0: return Dataset( self.data.slice(st...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@transmit_format @fingerprint_transform(inplace=False, ignore_kwargs=["indices_cache_file_name"]) def _select_with_indices_mapping( self, indices: Iterable, keep_in_memory: bool = False, indices_cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 100...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: indices (sequence, iterable, range, ndarray or Series): List or 1D-array of integer indices for indexing. keep_in_memory (`bool`, default `False`): Keep the indices mapping in memory instead of writing it to a cache file. indices_cache_file_name (`str`, optional, default `None`...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds._select_with_indices_mapping(range(4)) Dataset({ features: ['text', 'label'], num_rows: 4 }) ``` """ i...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# Prepare the writer for our indices arrow table if keep_in_memory or indices_cache_file_name is None: buf_writer = pa.BufferOutputStream() tmp_file = None writer = ArrowWriter( stream=buf_writer, writer_batch_size=writer_batch_size, fingerprint=new_fingerprin...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
size = len(self) if indices: _check_valid_indices_value(int(max(indices)), size=size) _check_valid_indices_value(int(min(indices)), size=size) else: return self._select_contiguous(0, 0, new_fingerprint=new_fingerprint) indices_array = pa.array(indices, type=p...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
with writer: try: writer.write_table(indices_table) writer.finalize() # close_stream=bool(buf_writer is None)) We only close if we are writing in a file except (Exception, KeyboardInterrupt): if tmp_file is not None: tmp_file....
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# Return new Dataset object if buf_writer is None: return self._new_dataset_with_indices( indices_cache_file_name=indices_cache_file_name, fingerprint=new_fingerprint ) else: return self._new_dataset_with_indices(indices_buffer=buf_writer.getvalue(), f...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="train") >>> 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 arnold schwarzeneg...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_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...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def take(self, n: int) -> "Dataset": """ Create a new [`Dataset`] with only the first `n` elements. Args: n (`int`): Number of elements to take. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomat...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@transmit_format @fingerprint_transform(inplace=False, ignore_kwargs=["load_from_cache_file", "indices_cache_file_name"]) def sort( self, column_names: Union[str, Sequence_[str]], reverse: Union[bool, Sequence_[bool]] = False, null_placement: str = "at_end", keep_in_memor...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.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...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
<Added version="1.14.2"/> keep_in_memory (`bool`, defaults to `False`): Keep the sorted indices in memory instead of writing it to a cache file. load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled): If a cache file storing the sorted i...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
The new fingerprint of the dataset after transform. If `None`, the new fingerprint is computed using a hash of the previous fingerprint, and the transform arguments
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset('rotten_tomatoes', split='validation') >>> ds['label'][:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] >>> sorted_ds = ds.sort('label') >>> sorted_ds['label'][:10] [0, 0, 0, 0, 0, 0, 0, 0, 0, ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# Check proper format of and for duplicates in column_names if isinstance(column_names, str): column_names = [column_names] # Check proper format and length of reverse if not isinstance(reverse, bool): if len(reverse) != len(column_names): raise ValueErro...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# Change null_placement to conform to pyarrow's sort_indices() while ensuring backwards compatability if null_placement not in ["at_start", "at_end"]: if null_placement == "first": null_placement = "at_start" elif null_placement == "last": null_placement =...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# Check if we've already cached this computation (indexed by a hash) if self.cache_files: if indices_cache_file_name is None: # we create a unique hash from the function, current dataset file and the mapping args indices_cache_file_name = self._get_cache_file_path(new...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
indices = pc.sort_indices(sort_table, sort_keys=sort_keys, null_placement=null_placement) return self.select( indices=indices, keep_in_memory=keep_in_memory, indices_cache_file_name=indices_cache_file_name, writer_batch_size=writer_batch_size, new_fin...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Currently shuffling uses numpy random generators. You can either supply a NumPy BitGenerator to use, or a seed to initiate NumPy's default random generator (PCG64). Shuffling takes the list of indices `[0:len(my_dataset)]` and shuffles it to create an indices mapping. However as soon as your [`...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```python my_dataset[0] # fast my_dataset = my_dataset.shuffle(seed=42) my_dataset[0] # up to 10x slower my_dataset = my_dataset.flatten_indices() # rewrite the shuffled dataset on disk as contiguous chunks of data my_dataset[0] # fast again ``` In this case,...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: seed (`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 to SeedSequence to d...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
indices_cache_file_name (`str`, *optional*): Provide the name of a path for the cache file. It is used to store the shuffled indices instead of the automatically generated cache file name. writer_batch_size (`int`, defaults to `1000`): Number of rows per write...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds['label'][:10] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # set a seed >>> shuffled_ds = ds.shuffle(seed=42) >>> shuffled_ds['label'][:10] ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if seed is not None and generator is not None: raise ValueError("Both `seed` and `generator` were provided. Please specify just one of them.") if generator is not None and not isinstance(generator, np.random.Generator): raise ValueError("The provided generator must be an instance of num...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# Check if we've already cached this computation (indexed by a hash) if self.cache_files: if indices_cache_file_name is None: # we create a unique hash from the function, current dataset file and the mapping args indices_cache_file_name = self._get_cache_file_path(new...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
return self.select( indices=permutation, keep_in_memory=keep_in_memory, indices_cache_file_name=indices_cache_file_name if not keep_in_memory else None, writer_batch_size=writer_batch_size, new_fingerprint=new_fingerprint, )
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@transmit_format @fingerprint_transform( inplace=False, randomized_function=True, fingerprint_names=["train_new_fingerprint", "test_new_fingerprint"], ignore_kwargs=["load_from_cache_file", "train_indices_cache_file_name", "test_indices_cache_file_name"], ) def train_test_spl...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
"""Return a dictionary ([`datasets.DatasetDict`]) with two random train and test subsets (`train` and `test` `Dataset` splits). Splits are created from the dataset according to `test_size`, `train_size` and `shuffle`.
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
This method is similar to scikit-learn `train_test_split`.
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: test_size (`numpy.random.Generator`, *optional*): Size of the test split If `float`, should be between `0.0` and `1.0` and represent the proportion of the dataset to include in the test split. If `int`, represents the absolute number of test samples. ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
stratify_by_column (`str`, *optional*, defaults to `None`): The column name of labels to be used to perform stratified split of data. seed (`int`, *optional*): A seed to initialize the default BitGenerator if `generator=None`. If `None`, then fresh, unpredicta...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
load_from_cache_file (`Optional[bool]`, defaults to `True` if caching is enabled): If a cache file storing the splits indices can be identified, use it instead of recomputing. train_cache_file_name (`str`, *optional*): Provide the name of a path for the cache ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`. train_new_fingerprint (`str`, *optional*, defaults to `None`): The new fingerprint of the train set after transform. If `None`, the new fingerprint is computed u...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds = ds.train_test_split(test_size=0.2, shuffle=True) DatasetDict({ train: Dataset({ features: ['text', 'label'], num...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# stratified split >>> ds = load_dataset("imdb",split="train") Dataset({ features: ['text', 'label'], num_rows: 25000 }) >>> ds = ds.train_test_split(test_size=0.2, stratify_by_column="label") DatasetDict({ train: Dataset({ feat...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if len(self.list_indexes()) > 0: raise DatasetTransformationNotAllowedError( "Using `.train_test_split` on a dataset with attached indexes is not allowed. You can first run `.drop_index() to remove your index and then re-add it." ) # If the array is empty we do nothing ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# Safety checks similar to scikit-learn's ones. # (adapted from https://github.com/scikit-learn/scikit-learn/blob/fd237278e895b42abe8d8d09105cbb82dc2cbba7/sklearn/model_selection/_split.py#L1750) n_samples = len(self) if ( isinstance(test_size, int) and (test_size >= n_sa...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if ( isinstance(train_size, int) and (train_size >= n_samples or train_size <= 0) or isinstance(train_size, float) and (train_size <= 0 or train_size >= 1) ): raise ValueError( f"train_size={train_size} should be either positive and sma...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if isinstance(train_size, float) and isinstance(test_size, float) and train_size + test_size > 1: raise ValueError( f"The sum of test_size and train_size = {train_size + test_size}, should be in the (0, 1)" " range. Reduce test_size and/or train_size." ) ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if n_train + n_test > n_samples: raise ValueError( f"The sum of train_size and test_size = {n_train + n_test}, " "should be smaller than the number of " f"samples {n_samples}. Reduce test_size and/or " "train_size." ) n_tra...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if generator is None and shuffle is True: if seed is None: _, seed, pos, *_ = np.random.get_state() seed = seed[pos] if pos < 624 else seed[0] _ = np.random.random() # do 1 step of rng generator = np.random.default_rng(seed) # Check if we...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if train_indices_cache_file_name is None: train_indices_cache_file_name = self._get_cache_file_path(train_new_fingerprint) if test_indices_cache_file_name is None: test_indices_cache_file_name = self._get_cache_file_path(test_new_fingerprint) if ( ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
"test": self._new_dataset_with_indices( fingerprint=test_new_fingerprint, indices_cache_file_name=test_indices_cache_file_name ), } ) if not shuffle: if stratify_by_column is not None: raise Value...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
f"Stratifying by column is only supported for {ClassLabel.__name__} column, and column {stratify_by_column} is {type(self._info.features[stratify_by_column]).__name__}." ) try: train_indices, test_indices = next( stratified_shuffle_split_ge...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
raise error
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# random partition else: permutation = generator.permutation(len(self)) test_indices = permutation[:n_test] train_indices = permutation[n_test : (n_test + n_train)] train_split = self.select( indices=train_indices, keep_in_memo...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def shard( self, num_shards: int, index: int, contiguous: bool = True, keep_in_memory: bool = False, indices_cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, ) -> "Dataset": """Return the `index`-nth shard from dataset sp...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
On the other hand, `dataset.shard(n, i, contiguous=False)` contains all elements 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.
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: num_shards (`int`): How many shards to split the dataset into. index (`int`): Which shard to select and return. contiguous: (`bool`, defaults to `True`): Whether to select contiguous blocks of indices for shards. keep_...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Higher value makes the processing do fewer lookups, lower value consume less temporary memory while running `map`.
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds Dataset({ features: ['text', 'label'], num_rows: 1066 }) >>> ds.shard(num_shards=2, index=0) Dataset({ ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
return self.select( indices=indices, keep_in_memory=keep_in_memory, indices_cache_file_name=indices_cache_file_name, writer_batch_size=writer_batch_size, ) def to_csv( self, path_or_buf: Union[PathLike, BinaryIO], batch_size: Optional[...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: path_or_buf (`PathLike` or `FileOrBuffer`): Either a path to a file (e.g. `file.csv`), a remote URI (e.g. `hf://datasets/username/my_dataset_name/data.csv`), or a BinaryIO, where the dataset will be saved to in the specified format. batch_size (`int`, *optio...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
<Added version="2.19.0"/> **to_csv_kwargs (additional keyword arguments): Parameters to pass to pandas's [`pandas.DataFrame.to_csv`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html). <Changed version="2.10.0"> Now, `index` defaults ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
return CsvDatasetWriter( self, path_or_buf, batch_size=batch_size, num_proc=num_proc, storage_options=storage_options, **to_csv_kwargs, ).write() def to_dict(self, batch_size: Optional[int] = None) -> Union[dict, Iterator[dict]]: ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Example: ```py >>> ds.to_list() ``` """ return query_table( table=self._data, key=slice(0, len(self)), indices=self._indices, ).to_pylist() def to_json( self, path_or_buf: Union[PathLike, BinaryIO], batch_s...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: path_or_buf (`PathLike` or `FileOrBuffer`): Either a path to a file (e.g. `file.json`), a remote URI (e.g. `hf://datasets/username/my_dataset_name/data.json`), or a BinaryIO, where the dataset will be saved to in the specified format. batch_size (`int`, *opt...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
<Added version="2.19.0"/> **to_json_kwargs (additional keyword arguments): Parameters to pass to pandas's [`pandas.DataFrame.to_json`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html). Default arguments are `lines=True` and `orient="records". ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
return JsonDatasetWriter( self, path_or_buf, batch_size=batch_size, num_proc=num_proc, storage_options=storage_options, **to_json_kwargs, ).write() def to_pandas( self, batch_size: Optional[int] = None, batched: bool = False ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> ds.to_pandas() ``` """ if not batched: return query_table( table=self._data, key=slice(0, len(self)), indices=self._indices, ).to_pandas(types_mapper=pandas_types_mapper) else: batch_siz...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def to_polars( self, batch_size: Optional[int] = None, batched: bool = False, schema_overrides: Optional[dict] = None, rechunk: bool = True, ) -> Union["pl.DataFrame", Iterator["pl.DataFrame"]]: """Returns the dataset as a `polars.DataFrame`. Can also return a generat...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: batched (`bool`): Set to `True` to return a generator that yields the dataset as batches of `batch_size` rows. Defaults to `False` (returns the whole datasets once). batch_size (`int`, *optional*): The size (number of rows) of the batches if ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if not batched: return pl.from_arrow( query_table( table=self._data, key=slice(0, len(self)), indices=self._indices if self._indices is not None else None, ), schema_overri...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
for offset in range(0, len(self), batch_size) ) else: raise ValueError("Polars needs to be installed to be able to return Polars dataframes.")
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py