text
stringlengths
1
1.02k
class_index
int64
0
271
source
stringclasses
76 values
class DatasetInfoMixin: """This base class exposes some attributes of DatasetInfo at the base level of the Dataset for easy access. """ def __init__(self, info: DatasetInfo, split: Optional[NamedSplit]): self._info = info self._split = split @property def info(self): ""...
0
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@property def download_checksums(self) -> Optional[dict]: return self._info.download_checksums @property def download_size(self) -> Optional[int]: return self._info.download_size @property def features(self) -> Optional[Features]: return self._info.features.copy() if self._...
0
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
class TensorflowDatasetMixin: _TF_DATASET_REFS = set() @staticmethod def _get_output_signature( dataset: "Dataset", collate_fn: Callable, collate_fn_args: dict, cols_to_retain: Optional[List[str]] = None, batch_size: Optional[int] = None, num_test_batches: in...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: dataset (`Dataset`): Dataset to load samples from. collate_fn(`bool`): Shuffle the dataset order when loading. Recommended True for training, False for validation/evaluation. collate_fn(`Callable`): A function or callable object (such as a `DataCollator`) that w...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Returns: `dict`: Dict mapping column names to tf.Tensorspec objects `dict`: Dict mapping column names to np.dtype objects """ if config.TF_AVAILABLE: import tensorflow as tf else: raise ImportError("Called a Tensorflow-specific function but Tensorf...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
test_batches = [] for _ in range(num_test_batches): indices = sample(range(len(dataset)), test_batch_size) test_batch = dataset[indices] if cols_to_retain is not None: test_batch = {key: value for key, value in test_batch.items() if key in cols_to_retain} ...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
tf_columns_to_signatures = {} np_columns_to_dtypes = {} for column in test_batches[0].keys(): raw_arrays = [batch[column] for batch in test_batches] # In case the collate_fn returns something strange np_arrays = [] for array in raw_arrays: ...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if np.issubdtype(np_arrays[0].dtype, np.integer) or np_arrays[0].dtype == bool: tf_dtype = tf.int64 np_dtype = np.int64 elif np.issubdtype(np_arrays[0].dtype, np.number): tf_dtype = tf.float32 np_dtype = np.float32 elif np_arrays[0]...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if len(sizes) == 1: # This dimension looks constant static_shape.append(sizes.pop()) else: # Use None for variable dimensions static_shape.append(None) tf_columns_to_signatures[column] = tf.TensorSpec(shape=static_shape, dtype=tf_dtype) n...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
return tf_columns_to_signatures, np_columns_to_dtypes def to_tf_dataset( self, batch_size: Optional[int] = None, columns: Optional[Union[str, List[str]]] = None, shuffle: bool = False, collate_fn: Optional[Callable] = None, drop_remainder: bool = False, colla...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: batch_size (`int`, *optional*): Size of batches to load from the dataset. Defaults to `None`, which implies that the dataset won't be batched, but the returned dataset can be batched later with `tf_dataset.batch(batch_size)`. columns (`List[str]` or `str`, *...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
A function or callable object (such as a `DataCollator`) that will collate lists of samples into a batch. collate_fn_args (`Dict`, *optional*): An optional `dict` of keyword arguments to be passed to the `collate_fn`. label_cols (`List[str]` or `st...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Number of workers to use for loading the dataset. num_test_batches (`int`, defaults to `20`): Number of batches to use to infer the output signature of the dataset. The higher this number, the more accurate the signature will be, but the longer it will take to ...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Returns: `tf.data.Dataset` Example: ```py >>> ds_train = ds["train"].to_tf_dataset( ... columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'], ... shuffle=True, ... batch_size=16, ... collate_fn=data_collator, ... ) ...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if (isinstance(columns, list) and len(columns) == 1) or ( isinstance(label_cols, list) and len(label_cols) == 1 ): warnings.warn( "The output of `to_tf_dataset` will change when a passing single element list for `labels` or " "`columns` in the next dataset...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if isinstance(tf.distribute.get_strategy(), tf.distribute.TPUStrategy): logger.warning( "Note that to_tf_dataset() loads the data with a generator rather than a full tf.data " "pipeline and is not compatible with remote TPU connections. If you encounter errors, please " ...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if collate_fn is None: # Set a very simple default collator that just stacks things together collate_fn = minimal_tf_collate_fn if collate_fn_args is None: collate_fn_args = {} if label_cols and not columns: raise ValueError("Cannot specify label_cols with...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if self.format["type"] not in ["custom", "numpy"]: dataset = self.with_format("numpy") else: dataset = self # TODO(Matt, QL): deprecate the retention of label_ids and label output_signature, columns_to_np_types = dataset._get_output_signature( dataset, ...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
for col in columns: if col not in output_signature: raise ValueError(f"Column {col} not found in dataset!") for col in label_cols: if col not in output_signature: raise ValueError(f"Label column {col} not found in dataset!")
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if num_workers == 0: tf_dataset = dataset_to_tf( dataset=dataset, cols_to_retain=cols_to_retain, collate_fn=collate_fn, collate_fn_args=collate_fn_args, columns_to_np_types=columns_to_np_types, output_signature=o...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
collate_fn_args=collate_fn_args, columns_to_np_types=columns_to_np_types, output_signature=output_signature, shuffle=shuffle, batch_size=batch_size, drop_remainder=drop_remainder, num_workers=num_workers, ) ...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def split_features_and_labels(input_batch): # TODO(Matt, QL): deprecate returning the dict content when there's only one key features = {key: tensor for key, tensor in input_batch.items() if key in columns} labels = {key: tensor for key, tensor in input_batch.items() if key in label_...
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# Remove a reference to the open Arrow file on delete def cleanup_callback(ref): dataset.__del__() self._TF_DATASET_REFS.remove(ref) self._TF_DATASET_REFS.add(weakref.ref(tf_dataset, cleanup_callback)) return tf_dataset
1
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
class DatasetTransformationNotAllowedError(Exception): pass
2
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
class NonExistentDatasetError(Exception): """Used when we expect the existence of a dataset""" pass
3
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
class Dataset(DatasetInfoMixin, IndexableMixin, TensorflowDatasetMixin): """A Dataset backed by an Arrow table.""" def __init__( self, arrow_table: Table, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, indices_table: Optional[Table] = None, ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if self._data.schema.metadata is not None and b"huggingface" in self._data.schema.metadata: metadata = json.loads(self._data.schema.metadata[b"huggingface"].decode()) if ( "fingerprint" in metadata and self._fingerprint is None ): # try to load fingerprint from the a...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# In case there are types like pa.dictionary that we need to convert to the underlying type if self.data.schema != self.info.features.arrow_schema: self._data = self.data.cast(self.info.features.arrow_schema) # Infer fingerprint if None if self._fingerprint is None: se...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if self._indices is not None: if not pa.types.is_unsigned_integer(self._indices.column(0).type): raise ValueError( f"indices must be an Arrow table of unsigned integers, current type is {self._indices.column(0).type}" ) _check_column_names(self._da...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: filename (`str`): File name of the dataset. info (`DatasetInfo`, *optional*): Dataset information, like description, citation, etc. split (`NamedSplit`, *optional*): Name of the dataset split. indices_filename (`str`, ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@classmethod def from_buffer( cls, buffer: pa.Buffer, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, indices_buffer: Optional[pa.Buffer] = None, ) -> "Dataset": """Instantiate a Dataset backed by an Arrow buffer. Args: ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@classmethod def from_pandas( cls, df: pd.DataFrame, features: Optional[Features] = None, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, preserve_index: Optional[bool] = None, ) -> "Dataset": """ Convert `pandas.DataFrame` ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Be aware that Series of the `object` dtype don't carry enough information to always lead to a meaningful Arrow type. In the case that we cannot infer a type, e.g. because the DataFrame is of length 0 or the Series only contains `None/nan` objects, the type is set to `null`. This behavior can be avoided ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: df (`pandas.DataFrame`): Dataframe that contains the dataset. features ([`Features`], *optional*): Dataset features. info (`DatasetInfo`, *optional*): Dataset information, like description, citation, etc. split (`Named...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> ds = Dataset.from_pandas(df) ``` """ if info is not None and features is not None and info.features != features: raise ValueError( f"Features specified in `features` and `info.features` can't be different:\n{features}\n{info.features}" ) ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@classmethod def from_polars( cls, df: "pl.DataFrame", features: Optional[Features] = None, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, ) -> "Dataset": """ Collect the underlying arrow arrays in an Arrow Table. This ope...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Examples: ```py >>> ds = Dataset.from_polars(df) ``` """ if info is not None and features is not None and info.features != features: raise ValueError( f"Features specified in `features` and `info.features` can't be different:\n{features}\n{info.feature...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@classmethod def from_dict( cls, mapping: dict, features: Optional[Features] = None, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, ) -> "Dataset": """ Convert `dict` to a `pyarrow.Table` to create a [`Dataset`]. Important...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: mapping (`Mapping`): Mapping of strings to Arrays or Python lists. features ([`Features`], *optional*): Dataset features. info (`DatasetInfo`, *optional*): Dataset information, like description, citation, etc. split (`...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Returns: [`Dataset`] """ if info is not None and features is not None and info.features != features: raise ValueError( f"Features specified in `features` and `info.features` can't be different:\n{features}\n{info.features}" ) features = feature...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
pa_table = InMemoryTable.from_pydict(mapping=mapping) if info is None: info = DatasetInfo() info.features = features if info.features is None: info.features = Features( { col: generate_from_arrow_type(data.type) if i...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@classmethod def from_list( cls, mapping: List[dict], features: Optional[Features] = None, info: Optional[DatasetInfo] = None, split: Optional[NamedSplit] = None, ) -> "Dataset": """ Convert a list of dicts to a `pyarrow.Table` to create a [`Dataset`]`. ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: mapping (`List[dict]`): A list of mappings of strings to row values. features (`Features`, optional): Dataset features. info (`DatasetInfo`, optional): Dataset information, like description, citation, etc. split (`NamedSplit`, optional): Name of the dataset split. ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: path_or_paths (`path-like` or list of `path-like`): Path(s) of the CSV file(s). split ([`NamedSplit`], *optional*): Split name to be assigned to the dataset. features ([`Features`], *optional*): Dataset features. cache...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Returns: [`Dataset`] Example: ```py >>> ds = Dataset.from_csv('path/to/dataset.csv') ``` """ # Dynamic import to avoid circular dependency from .io.csv import CsvDatasetReader return CsvDatasetReader( path_or_paths, s...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: generator (:`Callable`): A generator function that `yields` examples. features ([`Features`], *optional*): Dataset features. cache_dir (`str`, *optional*, defaults to `"~/.cache/huggingface/datasets"`): Directory to cache data. ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
If `num_proc` is greater than one, then all list values in `gen_kwargs` must be the same length. These values will be split between calls to the generator. The number of shards will be the minimum of the shortest list in `gen_kwargs` and `num_proc`.
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
<Added version="2.7.0"/> split ([`NamedSplit`], defaults to `Split.TRAIN`): Split name to be assigned to the dataset. <Added version="2.21.0"/> **kwargs (additional keyword arguments): Keyword arguments to be passed to :[`GeneratorConfig`]. ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_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 = Dataset.from_generator(gen, gen...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@staticmethod def from_json( path_or_paths: Union[PathLike, List[PathLike]], split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, field: Optional[str] = None, num_proc: Optional[int] = No...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: path_or_paths (`path-like` or list of `path-like`): Path(s) of the JSON or JSON Lines file(s). split ([`NamedSplit`], *optional*): Split name to be assigned to the dataset. features ([`Features`], *optional*): Dataset features. ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
<Added version="2.8.0"/> **kwargs (additional keyword arguments): Keyword arguments to be passed to [`JsonConfig`]. Returns: [`Dataset`] Example: ```py >>> ds = Dataset.from_json('path/to/dataset.json') ``` """ # Dynamic ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@staticmethod def from_parquet( path_or_paths: Union[PathLike, List[PathLike]], split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, columns: Optional[List[str]] = None, num_proc: Optiona...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: path_or_paths (`path-like` or list of `path-like`): Path(s) of the Parquet file(s). split (`NamedSplit`, *optional*): Split name to be assigned to the dataset. features (`Features`, *optional*): Dataset features. cache...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
This is helpful if the dataset is made of multiple files. Multiprocessing is disabled by default.
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
<Added version="2.8.0"/> **kwargs (additional keyword arguments): Keyword arguments to be passed to [`ParquetConfig`]. Returns: [`Dataset`] Example: ```py >>> ds = Dataset.from_parquet('path/to/dataset.parquet') ``` """ #...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@staticmethod def from_text( path_or_paths: Union[PathLike, List[PathLike]], split: Optional[NamedSplit] = None, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, num_proc: Optional[int] = None, **kwargs, ): ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: path_or_paths (`path-like` or list of `path-like`): Path(s) of the text file(s). split (`NamedSplit`, *optional*): Split name to be assigned to the dataset. features (`Features`, *optional*): Dataset features. cache_di...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Example: ```py >>> ds = Dataset.from_text('path/to/dataset.txt') ``` """ # Dynamic import to avoid circular dependency from .io.text import TextDatasetReader return TextDatasetReader( path_or_paths, split=split, features=featu...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: df (`pyspark.sql.DataFrame`): The DataFrame containing the desired data. split (`NamedSplit`, *optional*): Split name to be assigned to the dataset. features (`Features`, *optional*): Dataset features. cache_dir (`str`...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Returns: [`Dataset`] Example: ```py >>> df = spark.createDataFrame( >>> data=[[1, "Elia"], [2, "Teo"], [3, "Fang"]], >>> columns=["id", "name"], >>> ) >>> ds = Dataset.from_spark(df) ``` """ # Dynamic import to avoid c...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@staticmethod def from_sql( sql: Union[str, "sqlalchemy.sql.Selectable"], con: Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"], features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, **kwa...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: sql (`str` or `sqlalchemy.sql.Selectable`): SQL query to be executed or a table name. con (`str` or `sqlite3.Connection` or `sqlalchemy.engine.Connection` or `sqlalchemy.engine.Connection`): A [URI string](https://docs.sqlalchemy.org/en/13/core/engines.html#...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> # Fetch a database table >>> ds = Dataset.from_sql("test_data", "postgres:///db_name") >>> # Execute a SQL query on the table >>> ds = Dataset.from_sql("SELECT sentence FROM test_data", "postgres:///db_name") >>> # Use a Selectable object to specify the query >>...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def __setstate__(self, state): self.__dict__.update(state) maybe_register_dataset_for_temp_dir_deletion(self) return self def __del__(self): if hasattr(self, "_data"): del self._data if hasattr(self, "_indices"): del self._indices def __enter__(s...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
All the Image(), Audio() and Video() data are stored in the arrow files. If you want to store paths or urls, please use the Value("string") type. Args: dataset_path (`path-like`): Path (e.g. `dataset/train`) or remote URI (e.g. `s3://my-bucket/dataset/train`) ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
<Added version="2.8.0"/> num_proc (`int`, *optional*): Number of processes when downloading and generating the dataset locally. Multiprocessing is disabled by default. <Added version="2.8.0"/> storage_options (`dict`, *optional*): ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> ds.save_to_disk("path/to/dataset/directory") >>> ds.save_to_disk("path/to/dataset/directory", max_shard_size="1GB") >>> ds.save_to_disk("path/to/dataset/directory", num_shards=1024) ``` """ if max_shard_size is not None and num_shards is not None: ra...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
num_proc = num_proc if num_proc is not None else 1 num_shards = num_shards if num_shards is not None else num_proc fs: fsspec.AbstractFileSystem fs, _ = url_to_fs(dataset_path, **(storage_options or {})) if not is_remote_filesystem(fs): parent_cache_files_paths = { ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# Get json serializable state state = { key: self.__dict__[key] for key in [ "_fingerprint", "_format_columns", "_format_kwargs", "_format_type", "_output_all_columns", ] } state["...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
shards_done = 0 pbar = hf_tqdm( unit=" examples", total=len(self), desc=f"Saving the dataset ({shards_done}/{num_shards} shards)", ) kwargs_per_job = ( { "job_id": shard_idx, "shard": self.shard(num_shards=num_shards...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
shards_done += 1 pbar.set_description(f"Saving the dataset ({shards_done}/{num_shards} shards)") logger.debug(f"Finished writing shard number {job_id} of {num_shards}.") shard_lengths[job_id], shard_sizes[job_id] = content ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
pbar.update(content) with fs.open( posixpath.join(dataset_path, config.DATASET_STATE_JSON_FILENAME), "w", encoding="utf-8" ) as state_file: json.dump(state, state_file, indent=2, sort_keys=True) with fs.open( posixpath.join(dataset_path, config.DATASET_INFO_FI...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@staticmethod def _save_to_disk_single(job_id: int, shard: "Dataset", fpath: str, storage_options: Optional[dict]): batch_size = config.DEFAULT_MAX_BATCH_SIZE
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
num_examples_progress_update = 0 writer = ArrowWriter( features=shard.features, path=fpath, storage_options=storage_options, embed_local_files=True, ) try: _time = time.time() for pa_table in shard.with_format("arrow").iter(...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@staticmethod def _build_local_temp_path(uri_or_path: str) -> Path: """ Builds and returns a Path concatenating a local temporary dir with the dir path (or absolute/relative path extracted from the uri) passed. Args: uri_or_path (`str`): Path (e.g. `"dataset/train"`) or ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@staticmethod def load_from_disk( dataset_path: PathLike, keep_in_memory: Optional[bool] = None, storage_options: Optional[dict] = None, ) -> "Dataset": """ Loads a dataset that was previously saved using [`save_to_disk`] from a dataset directory, or from a filesy...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: dataset_path (`path-like`): Path (e.g. `"dataset/train"`) or remote URI (e.g. `"s3//my-bucket/dataset/train"`) of the dataset directory where the dataset will be loaded from. keep_in_memory (`bool`, defaults to `None`): Whether to copy the da...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Returns: [`Dataset`] or [`DatasetDict`]: - If `dataset_path` is a path of a dataset directory, the dataset requested. - If `dataset_path` is a path of a dataset dict directory, a `datasets.DatasetDict` with each split. Example: ```py >>> ds = load_from_disk(...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
dataset_dict_is_file = fs.isfile(dataset_dict_json_path) dataset_info_is_file = fs.isfile(dataset_info_path) dataset_state_is_file = fs.isfile(dataset_state_json_path) if not dataset_info_is_file and not dataset_state_is_file: if dataset_dict_is_file: raise FileNotFou...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
f"No such file: '{dataset_info_path}' found. Expected to load a `Dataset` object, but got a `DatasetDict`. Please use either `datasets.load_from_disk` or `DatasetDict.load_from_disk` instead." ) raise FileNotFoundError( f"No such file: '{dataset_info_path}'. Expected to load ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
# copies file from filesystem if it is remote filesystem to local filesystem and modifies dataset_path to temp directory containing local copies if is_remote_filesystem(fs): src_dataset_path = dest_dataset_path dest_dataset_path = Dataset._build_local_temp_path(src_dataset_path) ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
dataset_size = estimate_dataset_size( Path(dest_dataset_path, data_file["filename"]) for data_file in state["_data_files"] ) keep_in_memory = keep_in_memory if keep_in_memory is not None else is_small_dataset(dataset_size) table_cls = InMemoryTable if keep_in_memory else MemoryMapped...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
dataset = Dataset( arrow_table=arrow_table, info=dataset_info, split=split, fingerprint=state["_fingerprint"], ) format = { "type": state["_format_type"], "format_kwargs": state["_format_kwargs"], "columns": state["_for...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.data MemoryMappedTable text: string label: int64 ----
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
text: [["compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .","the soundtrack alone is worth the price of admission .","rodriguez does a splendid job of racial profiling hollywood style--casting excellent latin actors of a...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
something original against the backdrop of a corporate music industry that only seems to care about the bottom line .",...,"ultimately , jane learns her place as a girl , softens up and loses some of the intensity that made her an interesting character to begin with .","ah-nuld's action hero days might be over .","it's...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
drugs , death and mind-numbing indifference on the inner-city streets .","the feature-length stretch . . . strains the show's concept ."]]
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
label: [[1,1,1,1,1,1,1,1,1,1,...,0,0,0,0,0,0,0,0,0,0]] ``` """ return self._data
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
@property def cache_files(self) -> List[dict]: """The cache files containing the Apache Arrow table backing the dataset. Example: ```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.cache_files [{'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="validation") >>> ds.num_columns 2 ``` """ return self._data.num_columns @property def num_rows(self) -> int: """Number of rows in the dataset (same as [`Da...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("rotten_tomatoes", split="validation") >>> ds.column_names ['text', 'label'] ``` """ return self._data.column_names @property def shape(self) -> Tuple[int, int]: """Shape of the dat...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: column (`str`): Column name (list all the column names with [`~datasets.Dataset.column_names`]). Returns: `list`: List of unique elements in the given column. Example: ```py >>> from datasets import load_dataset >>> ds = load_datas...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
Args: column (`str`): The name of the column to cast (list all the column names with [`~datasets.Dataset.column_names`]) include_nulls (`bool`, defaults to `False`): Whether to include null values in the class labels. If `True`, the null values will be encoded as ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("boolq", split="validation") >>> ds.features {'answer': Value(dtype='bool', id=None), 'passage': Value(dtype='string', id=None), 'question': Value(dtype='string', id=None)} >>> ds = ds.class_encod...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
if src_feat.dtype != "string" or (include_nulls and None in self.unique(column)): def stringify_column(batch): batch[column] = [ str(sample) if include_nulls or sample is not None else None for sample in batch[column] ] return batch ...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
new_features = dset.features.copy() new_features[column] = dst_feat dset = dset.map( cast_to_class_labels, batched=True, features=new_features, desc="Casting to class labels", ) return dset @fingerprint_transform(inplace=False) d...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
```py >>> from datasets import load_dataset >>> ds = load_dataset("squad", split="train") >>> ds.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', i...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
dataset.info.features = self._info.features.flatten(max_depth=max_depth) dataset.info.features = Features({col: dataset.info.features[col] for col in dataset.data.column_names}) dataset._data = update_metadata_with_features(dataset._data, dataset.features) logger.info(f"Flattened dataset from de...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py
def cast( self, features: Features, batch_size: Optional[int] = 1000, keep_in_memory: bool = False, load_from_cache_file: Optional[bool] = None, cache_file_name: Optional[str] = None, writer_batch_size: Optional[int] = 1000, num_proc: Optional[int] = None,...
4
/Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/arrow_dataset.py