Datasets 文件

主要類

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

主類

DatasetInfo

class datasets.DatasetInfo

< >

( description: str = <factory> citation: str = <factory> homepage: str = <factory> license: str = <factory> features: typing.Optional[datasets.features.features.Features] = None post_processed: typing.Optional[datasets.info.PostProcessedInfo] = None supervised_keys: typing.Optional[datasets.info.SupervisedKeysData] = None builder_name: typing.Optional[str] = None dataset_name: typing.Optional[str] = None config_name: typing.Optional[str] = None version: typing.Union[str, datasets.utils.version.Version, NoneType] = None splits: typing.Optional[dict] = None download_checksums: typing.Optional[dict] = None download_size: typing.Optional[int] = None post_processing_size: typing.Optional[int] = None dataset_size: typing.Optional[int] = None size_in_bytes: typing.Optional[int] = None )

引數

  • description (str) — 資料集的描述。
  • citation (str) — 資料集的 BibTeX 引用。
  • homepage (str) — 資料集官方主頁的 URL。
  • license (str) — 資料集的許可證。它可以是許可證的名稱,也可以是包含許可證條款的段落。
  • features (Features, 可選) — 用於指定資料集列型別的特徵。
  • post_processed (PostProcessedInfo, 可選) — 關於資料集可能進行的後處理資源的資訊。例如,它可以包含索引的資訊。
  • supervised_keys (SupervisedKeysData, 可選) — 如果適用於資料集,則指定監督學習的輸入特徵和標籤(繼承自 TFDS)。
  • builder_name (str, 可選) — 用於建立資料集的 GeneratorBasedBuilder 子類的名稱。它也是資料集構建器類名的蛇形命名法(snake_case)版本。
  • config_name (str, 可選) — 從 BuilderConfig 派生的配置名稱。
  • version (strVersion, 可選) — 資料集的版本。
  • splits (dict, 可選) — 資料集劃分名稱與元資料之間的對映。
  • download_checksums (dict, 可選) — 下載資料集校驗和的 URL 與相應元資料之間的對映。
  • download_size (int, 可選) — 生成資料集需要下載的檔案大小,以位元組為單位。
  • post_processing_size (int, 可選) — 資料集在後處理後的大小,以位元組為單位(如果進行了後處理)。
  • dataset_size (int, 可選) — 所有資料集劃分的 Arrow 表的總大小,以位元組為單位。
  • size_in_bytes (int, 可選) — 與資料集相關的所有檔案的總大小,以位元組為單位(下載的檔案 + Arrow 檔案)。
  • **config_kwargs (額外的關鍵字引數) — 將傳遞給 BuilderConfig 並在 DatasetBuilder 中使用的關鍵字引數。

關於資料集的資訊。

DatasetInfo 記錄了資料集的各種資訊,包括其名稱、版本和特徵。完整的列表請參見建構函式引數和屬性。

並非所有欄位在構建時都是已知的,可能會在之後更新。

from_directory

< >

( dataset_info_dir: str storage_options: typing.Optional[dict] = None )

引數

  • dataset_info_dir (str) — 包含元資料檔案的目錄。這應該是特定資料集版本的根目錄。
  • storage_options (dict, 可選) — 傳遞給檔案系統後端的鍵/值對(如果有)。

    在 2.9.0 版本中新增

從 `dataset_info_dir` 中的 JSON 檔案建立 DatasetInfo

此函式會更新 DatasetInfo 的所有動態生成欄位(例如,示例數量、雜湊值、建立時間等)。

這將覆蓋所有先前的元資料。

示例

>>> from datasets import DatasetInfo
>>> ds_info = DatasetInfo.from_directory("/path/to/directory/")

write_to_directory

< >

( dataset_info_dir pretty_print = False storage_options: typing.Optional[dict] = None )

引數

  • dataset_info_dir (str) — 目標目錄。
  • pretty_print (bool, 預設為 False) — 如果為 True,JSON 將以 4 個空格的縮排級別進行美化列印。
  • storage_options (dict, 可選) — 傳遞給檔案系統後端的鍵/值對(如果有)。

    在 2.9.0 版本中新增

將 `DatasetInfo` 和許可證(如果存在)作為 JSON 檔案寫入 `dataset_info_dir`。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.info.write_to_directory("/path/to/directory/")

Dataset

基類 Dataset 實現了一個由 Apache Arrow 表支援的資料集。

class datasets.Dataset

< >

( arrow_table: Table info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None indices_table: typing.Optional[datasets.table.Table] = None fingerprint: typing.Optional[str] = None )

一個由 Arrow 表支援的資料集。

add_column

< >

( name: str column: typing.Union[list, numpy.ndarray] new_fingerprint: str feature: typing.Union[dict, list, tuple, datasets.features.features.Value, datasets.features.features.ClassLabel, datasets.features.translation.Translation, datasets.features.translation.TranslationVariableLanguages, datasets.features.features.LargeList, datasets.features.features.List, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image, datasets.features.video.Video, datasets.features.pdf.Pdf, NoneType] = None )

引數

  • name (str) — 列名。
  • column (listnp.array) — 要新增的列資料。
  • feature (FeatureTypeNone, 預設為 None) — 列的資料型別。

向資料集中新增列。

在 1.7 版本中新增

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> more_text = ds["text"]
>>> ds.add_column(name="text_2", column=more_text)
Dataset({
    features: ['text', 'label', 'text_2'],
    num_rows: 1066
})

add_item

< >

( item: dict new_fingerprint: str )

引數

  • item (dict) — 要新增的專案資料。

向資料集中新增專案。

在 1.7 版本中新增

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> new_review = {'label': 0, 'text': 'this movie is the absolute worst thing I have ever seen'}
>>> ds = ds.add_item(new_review)
>>> ds[-1]
{'label': 0, 'text': 'this movie is the absolute worst thing I have ever seen'}

from_file

< >

( filename: str info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None indices_filename: typing.Optional[str] = None in_memory: bool = False )

引數

  • filename (str) — 資料集的檔名。
  • info (DatasetInfo, 可選) — 資料集資訊,如描述、引用等。
  • split (NamedSplit, 可選) — 資料集劃分的名稱。
  • indices_filename (str, 可選) — 索引的檔名。
  • in_memory (bool, 預設為 False) — 是否將資料複製到記憶體中。

例項化一個由位於指定檔名的 Arrow 表支援的資料集。

from_buffer

< >

( buffer: Buffer info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None indices_buffer: typing.Optional[pyarrow.lib.Buffer] = None )

引數

  • buffer (pyarrow.Buffer) — Arrow 緩衝區。
  • info (DatasetInfo, 可選) — 資料集資訊,如描述、引用等。
  • split (NamedSplit, 可選) — 資料集劃分的名稱。
  • indices_buffer (pyarrow.Buffer, 可選) — 索引的 Arrow 緩衝區。

例項化一個由 Arrow 緩衝區支援的資料集。

from_pandas

< >

( df: DataFrame features: typing.Optional[datasets.features.features.Features] = None info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None preserve_index: typing.Optional[bool] = None )

引數

  • df (pandas.DataFrame) — 包含資料集的資料幀(Dataframe)。
  • features (Features, optional) — 資料集特徵。
  • info (DatasetInfo, optional) — 資料集資訊,如描述、引用等。
  • split (NamedSplit, optional) — 資料集拆分的名稱。
  • preserve_index (bool, optional) — 是否將索引作為額外的一列儲存在生成的資料集中。預設值 `None` 會將索引儲存為一列,但 `RangeIndex` 除外,它僅作為元資料儲存。使用 `preserve_index=True` 強制將其儲存為一列。

將 `pandas.DataFrame` 轉換為 `pyarrow.Table` 以建立一個 Dataset

生成的 Arrow Table 中的列型別是根據 DataFrame 中 `pandas.Series` 的 dtypes 推斷的。對於非物件 Series,NumPy dtype 會被轉換為其等效的 Arrow 型別。對於 `object` 型別,我們需要透過檢視該 Series 中的 Python 物件來猜測資料型別。

請注意,`object` 型別的 Series 所攜帶的資訊不足以總是能推匯出有意義的 Arrow 型別。如果我們無法推斷型別(例如,因為 DataFrame 長度為 0 或 Series 中只包含 `None/nan` 物件),則型別將被設定為 `null`。可以透過構建顯式特徵並將其傳遞給此函式來避免此行為。

重要提示:使用 from_pandas() 建立的資料集存在於記憶體中,因此沒有關聯的快取目錄。這在未來可能會改變,但在此期間,如果您想減少記憶體使用,應該將其寫回磁碟並使用例如 save_to_disk / load_from_disk 重新載入。

示例

>>> ds = Dataset.from_pandas(df)

from_dict

< >

( mapping: dict features: typing.Optional[datasets.features.features.Features] = None info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None )

引數

  • mapping (Mapping) — 字串到陣列或 Python 列表的對映。
  • features (Features, optional) — 資料集特徵。
  • info (DatasetInfo, optional) — 資料集資訊,如描述、引用等。
  • split (NamedSplit, optional) — 資料集拆分的名稱。

將 `dict` 轉換為 `pyarrow.Table` 以建立一個 Dataset

重要提示:使用 from_dict() 建立的資料集存在於記憶體中,因此沒有關聯的快取目錄。這在未來可能會改變,但在此期間,如果您想減少記憶體使用,應該將其寫回磁碟並使用例如 save_to_disk / load_from_disk 重新載入。

from_generator

< >

( generator: typing.Callable features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False gen_kwargs: typing.Optional[dict] = None num_proc: typing.Optional[int] = None split: NamedSplit = NamedSplit('train') **kwargs )

引數

  • generator ( —Callable): 一個 `yield` 樣本的生成器函式。
  • features (Features, optional) — 資料集特徵。
  • cache_dir (str, optional, defaults to "~/.cache/huggingface/datasets") — 快取資料的目錄。
  • keep_in_memory (bool, defaults to False) — 是否將資料複製到記憶體中。
  • gen_kwargs(dict, optional) — 將傳遞給 `generator` 可呼叫物件的關鍵字引數。您可以透過在 `gen_kwargs` 中傳遞分片列表並將 `num_proc` 設定為大於 1 的值來定義分片資料集。
  • num_proc (int, optional, defaults to None) — 在本地下載和生成資料集時的程序數。如果資料集由多個檔案組成,這會很有幫助。多程序處理預設是停用的。如果 `num_proc` 大於 1,則 `gen_kwargs` 中的所有列表值必須具有相同的長度。這些值將在對生成器的呼叫之間進行分割。分片的數量將是 `gen_kwargs` 中最短列表的長度與 `num_proc` 之間的最小值。

    2.7.0 版本新增

  • split (NamedSplit, defaults to Split.TRAIN) — 分配給資料集的拆分名稱。

    2.21.0 版本新增

  • **kwargs (附加關鍵字引數) — 將傳遞給 :`GeneratorConfig` 的關鍵字引數。

從生成器建立資料集。

示例

>>> def gen():
...     yield {"text": "Good", "label": 0}
...     yield {"text": "Bad", "label": 1}
...
>>> ds = Dataset.from_generator(gen)
>>> 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_kwargs={"shards": shards})

data

< >

( )

支援該資料集的 Apache Arrow 表。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.data
MemoryMappedTable
text: string
label: int64
----
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 all ages--a trend long overdue .","beneath the film's obvious determination to shock at any cost lies considerable skill and determination , backed by sheer nerve .","bielinsky is a filmmaker of impressive talent .","so beautifully acted and directed , it's clear that washington most certainly has a new career ahead of him if he so chooses .","a visual spectacle full of stunning images and effects .","a gentle and engrossing character study .","it's enough to watch huppert scheming , with her small , intelligent eyes as steady as any noir villain , and to enjoy the perfectly pitched web of tension that chabrol spins .","an engrossing portrait of uncompromising artists trying to create 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 clear why deuces wild , which was shot two years ago , has been gathering dust on mgm's shelf .","feels like nothing quite so much as a middle-aged moviemaker's attempt to surround himself with beautiful , half-naked women .","when the precise nature of matthew's predicament finally comes into sharp focus , the revelation fails to justify the build-up .","this picture is murder by numbers , and as easy to be bored by as your abc's , despite a few whopping shootouts .","hilarious musical comedy though stymied by accents thick as mud .","if you are into splatter movies , then you will probably have a reasonably good time with the salton sea .","a dull , simple-minded and stereotypical tale of drugs , death and mind-numbing indifference on the inner-city streets .","the feature-length stretch . . . strains the show's concept ."]]
label: [[1,1,1,1,1,1,1,1,1,1,...,0,0,0,0,0,0,0,0,0,0]]

cache_files

< >

( )

包含支援該資料集的 Apache Arrow 表的快取檔案。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.cache_files
[{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-validation.arrow'}]

num_columns

< >

( )

資料集中的列數。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.num_columns
2

num_rows

< >

( )

資料集中的行數(與 Dataset.len() 相同)。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.num_rows
1066

column_names

< >

( )

資料集中的列名。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.column_names
['text', 'label']

shape

< >

( )

資料集的形狀(列數,行數)。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.shape
(1066, 2)

unique

< >

( column: str ) list

引數

  • column (str) — 列名(使用 column_names 列出所有列名)。

返回

list

給定列中唯一元素的列表。

返回列中唯一元素的列表。

此功能在底層後端實現,因此速度非常快。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.unique('label')
[1, 0]

flatten

< >

( new_fingerprint: typing.Optional[str] = None max_depth = 16 ) Dataset

引數

  • new_fingerprint (str, optional) — 轉換後資料集的新指紋。如果為 `None`,則新指紋將使用前一個指紋的雜湊值和轉換引數計算。

返回

資料集

一份列已展平的資料集副本。

展平表格。每個具有結構型別的列都將展平為每個結構欄位一個列。其他列保持不變。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("rajpurkar/squad", split="train")
>>> ds.features
{'id': Value('string'),
 'title': Value('string'),
 'context': Value('string'),
 'question': Value('string'),
 'answers': {'text': List(Value('string')),
 'answer_start': List(Value('int32'))}}
>>> ds.flatten()
Dataset({
    features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'],
    num_rows: 87599
})

cast

< >

( features: Features batch_size: typing.Optional[int] = 1000 keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 num_proc: typing.Optional[int] = None ) Dataset

引數

  • features (Features) — 用於轉換資料集的新特徵。特徵中欄位的名稱必須與當前列名匹配。資料型別也必須能夠從一種型別轉換為另一種型別。對於非平凡的轉換,例如 `str` <-> `ClassLabel`,您應該使用 map() 來更新資料集。
  • batch_size (int, defaults to 1000) — 提供給 cast 的每批樣本數。如果 `batch_size <= 0` 或 `batch_size == None`,則將整個資料集作為一個批次提供給 cast。
  • keep_in_memory (bool, defaults to False) — 是否將資料複製到記憶體中。
  • load_from_cache_file (bool, defaults to True if caching is enabled) — 如果可以識別儲存當前 `function` 計算結果的快取檔案,則使用它而不是重新計算。
  • cache_file_name (str, optional, defaults to None) — 提供快取檔案的路徑名稱。它用於儲存計算結果,而不是使用自動生成的快取檔名。
  • writer_batch_size (int, defaults to 1000) — 快取檔案寫入器的每次寫入操作的行數。此值在處理過程中的記憶體使用和處理速度之間是一個很好的權衡。較高的值使處理過程中的查詢次數減少,較低的值在執行 map() 時消耗較少的臨時記憶體。
  • num_proc (int, optional, defaults to None) — 多程序處理的程序數。預設情況下不使用多程序處理。

返回

資料集

一份具有轉換後特徵的資料集副本。

將資料集轉換為一組新的特徵。

示例

>>> from datasets import load_dataset, ClassLabel, Value
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> new_features = ds.features.copy()
>>> new_features['label'] = ClassLabel(names=['bad', 'good'])
>>> new_features['text'] = Value('large_string')
>>> ds = ds.cast(new_features)
>>> ds.features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('large_string')}

cast_column

< >

( column: str feature: typing.Union[dict, list, tuple, datasets.features.features.Value, datasets.features.features.ClassLabel, datasets.features.translation.Translation, datasets.features.translation.TranslationVariableLanguages, datasets.features.features.LargeList, datasets.features.features.List, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image, datasets.features.video.Video, datasets.features.pdf.Pdf] new_fingerprint: typing.Optional[str] = None )

引數

  • column (str) — 列名。
  • feature (FeatureType) — 目標特徵。
  • new_fingerprint (str, optional) — 轉換後資料集的新指紋。如果為 `None`,則新指紋將使用前一個指紋的雜湊值和轉換引數計算。

將列轉換為特徵以進行解碼。

示例

>>> from datasets import load_dataset, ClassLabel
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds.features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('string')}

remove_columns

< >

( column_names: typing.Union[str, list[str]] new_fingerprint: typing.Optional[str] = None ) Dataset

引數

  • column_names (Union[str, List[str]]) — 要移除的列的名稱。
  • new_fingerprint (str, optional) — 轉換後資料集的新指紋。如果為 `None`,則新指紋將使用前一個指紋的雜湊值和轉換引數計算。

返回

資料集

移除了指定列的資料集物件副本。

移除資料集中的一列或多列以及與之相關的特徵。

您也可以使用帶有 `remove_columns` 的 map() 來移除列,但本方法不會複製剩餘列的資料,因此速度更快。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds = ds.remove_columns('label')
Dataset({
    features: ['text'],
    num_rows: 1066
})
>>> ds = ds.remove_columns(column_names=ds.column_names) # Removing all the columns returns an empty dataset with the `num_rows` property set to 0
Dataset({
    features: [],
    num_rows: 0
})

rename_column

< >

( original_column_name: str new_column_name: str new_fingerprint: typing.Optional[str] = None ) Dataset

引數

  • original_column_name (str) — 要重新命名的列的名稱。
  • new_column_name (str) — 列的新名稱。
  • new_fingerprint (str, optional) — 轉換後資料集的新指紋。如果為 `None`,則新指紋將使用前一個指紋的雜湊值和轉換引數計算。

返回

資料集

一列已重新命名的資料集副本。

重新命名資料集中的一列,並將與原始列關聯的特徵移動到新的列名下。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds = ds.rename_column('label', 'label_new')
Dataset({
    features: ['text', 'label_new'],
    num_rows: 1066
})

rename_columns

< >

( column_mapping: dict new_fingerprint: typing.Optional[str] = None ) Dataset

引數

  • column_mapping (Dict[str, str]) — 一個將要重新命名的列對映到其新名稱的字典
  • new_fingerprint (str, optional) — 轉換後資料集的新指紋。如果為 `None`,則新指紋將使用前一個指紋的雜湊值和轉換引數計算。

返回

資料集

列已重新命名的資料集副本

重新命名資料集中的多個列,並將與原始列關聯的特徵移動到新的列名下。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds = ds.rename_columns({'text': 'text_new', 'label': 'label_new'})
Dataset({
    features: ['text_new', 'label_new'],
    num_rows: 1066
})

select_columns

< >

( column_names: typing.Union[str, list[str]] new_fingerprint: typing.Optional[str] = None ) Dataset

引數

  • column_names (Union[str, List[str]]) — 要保留的列的名稱。
  • new_fingerprint (str, optional) — 轉換後資料集的新指紋。如果為 `None`,則新指紋將使用前一個指紋的雜湊值和轉換引數計算。

返回

資料集

僅包含所選列的資料集物件副本。

選擇資料集中的一列或多列以及與之相關的特徵。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.select_columns(['text'])
Dataset({
    features: ['text'],
    num_rows: 1066
})

class_encode_column

< >

( column: str include_nulls: bool = False )

引數

  • column (str) — 要轉換的列名(使用 column_names 列出所有列名)
  • include_nulls (bool, 預設為 False) — 是否在類別標籤中包含空值。如果為 True,空值將被編碼為 "None" 類別標籤。

    1.14.2 版本新增

將給定列轉換為 ClassLabel 型別並更新表。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("boolq", split="validation")
>>> ds.features
{'answer': Value('bool'),
 'passage': Value('string'),
 'question': Value('string')}
>>> ds = ds.class_encode_column('answer')
>>> ds.features
{'answer': ClassLabel(num_classes=2, names=['False', 'True']),
 'passage': Value('string'),
 'question': Value('string')}

__len__

< >

( )

資料集中的行數。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.__len__
<bound method Dataset.__len__ of Dataset({
    features: ['text', 'label'],
    num_rows: 1066
})>

__iter__

< >

( )

遍歷樣本。

如果使用 Dataset.set_format() 設定了格式,將返回所選格式的行。

iter

< >

( batch_size: int drop_last_batch: bool = False )

引數

  • batch_size (int) — 每個要生成的批次的大小。
  • drop_last_batch (bool, 預設 False) — 是否應丟棄小於 batch_size 的最後一個批次。

按批次大小 batch_size 遍歷。

如果使用 [~datasets.Dataset.set_format] 設定了格式,將返回所選格式的行。

formatted_as

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

引數

  • type (str, optional) — 在 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars'] 中選擇的輸出型別。None 表示 `getitem` 返回 python 物件(預設)。
  • columns (List[str], optional) — 輸出中要格式化的列。None 表示 __getitem__ 返回所有列(預設)。
  • output_all_columns (bool, 預設為 False) — 在輸出中也保留未格式化的列(作為 python 物件)。
  • **format_kwargs (附加關鍵字引數) — 傳遞給轉換函式的關鍵字引數,如 np.arraytorch.tensortensorflow.ragged.constant

with 語句中使用。設定 __getitem__ 返回格式(型別和列)。

set_format

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

引數

  • type (str, optional) — 在 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars'] 中選擇的輸出型別。None 表示 __getitem__ 返回 python 物件(預設)。
  • columns (List[str], optional) — 輸出中要格式化的列。None 表示 __getitem__ 返回所有列(預設)。
  • output_all_columns (bool, 預設為 False) — 在輸出中也保留未格式化的列(作為 python 物件)。
  • **format_kwargs (附加關鍵字引數) — 傳遞給轉換函式的關鍵字引數,如 np.arraytorch.tensortensorflow.ragged.constant

設定 __getitem__ 返回格式(型別和列)。資料格式化是即時應用的。格式 type(例如 “numpy”)用於在使用 __getitem__ 時格式化批次。也可以使用 set_transform() 使用自定義轉換進行格式化。

在呼叫 set_format 後可以呼叫 map()。由於 map 可能會新增新列,因此格式化列的列表

會得到更新。在這種情況下,如果您對資料集應用 map 來新增新列,則此列將被格式化。

new formatted columns = (all columns - previously unformatted columns)

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds.set_format(type='numpy', columns=['text', 'label'])
>>> ds.format
{'type': 'numpy',
'format_kwargs': {},
'columns': ['text', 'label'],
'output_all_columns': False}

set_transform

< >

( transform: typing.Optional[typing.Callable] columns: typing.Optional[list] = None output_all_columns: bool = False )

引數

  • transform (Callable, optional) — 使用者定義的格式化轉換,取代 set_format() 定義的格式。格式化函式是一個可呼叫物件,它接收一個批次(作為 dict)作為輸入並返回一個批次。此函式在 __getitem__ 返回物件之前立即應用。
  • columns (List[str], optional) — 輸出中要格式化的列。如果指定,則轉換的輸入批次僅包含這些列。
  • output_all_columns (bool, 預設為 False) — 在輸出中也保留未格式化的列(作為 python 物件)。如果設定為 True,則其他未格式化的列將與轉換的輸出一起保留。

使用此轉換設定 __getitem__ 返回格式。當呼叫 __getitem__ 時,轉換會即時應用於批次。與 set_format() 一樣,這可以使用 reset_format() 重置。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
>>> def encode(batch):
...     return tokenizer(batch['text'], padding=True, truncation=True, return_tensors='pt')
>>> ds.set_transform(encode)
>>> ds[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]),
 'input_ids': tensor([  101, 29353,  2135, 15102,  1996,  9428, 20868,  2890,  8663,  6895,
         20470,  2571,  3663,  2090,  4603,  3017,  3008,  1998,  2037, 24211,
         5637,  1998, 11690,  2336,  1012,   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])}

reset_format

< >

( )

__getitem__ 返回格式重置為 python 物件和所有列。

self.set_format() 相同

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds.set_format(type='numpy', columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds.format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'numpy'}
>>> ds.reset_format()
>>> ds.format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}

with_format

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

引數

  • type (str, optional) — 在 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars'] 中選擇的輸出型別。None 表示 __getitem__ 返回 python 物件(預設)。
  • columns (List[str], optional) — 輸出中要格式化的列。None 表示 __getitem__ 返回所有列(預設)。
  • output_all_columns (bool, 預設為 False) — 在輸出中也保留未格式化的列(作為 python 物件)。
  • **format_kwargs (附加關鍵字引數) — 傳遞給轉換函式的關鍵字引數,如 np.arraytorch.tensortensorflow.ragged.constant

設定 __getitem__ 返回格式(型別和列)。資料格式化是即時應用的。格式 type(例如 “numpy”)用於在使用 __getitem__ 時格式化批次。

也可以使用 with_transform() 使用自定義轉換進行格式化。

set_format() 不同,with_format 返回一個新的 Dataset 物件。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds.format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}
>>> ds = ds.with_format("torch")
>>> ds.format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'torch'}
>>> ds[0]
{'text': 'compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .',
 '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,     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,     0,     0,
            0,     0,     0,     0]),
 '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, 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]),
 '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,
        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])}

with_transform

< >

( transform: typing.Optional[typing.Callable] columns: typing.Optional[list] = None output_all_columns: bool = False )

引數

  • transform (Callable, optional) — 使用者定義的格式化轉換,取代 set_format() 定義的格式。格式化函式是一個可呼叫物件,它接收一個批次(作為 dict)作為輸入並返回一個批次。此函式在 __getitem__ 返回物件之前立即應用。
  • columns (List[str], optional) — 輸出中要格式化的列。如果指定,則轉換的輸入批次僅包含這些列。
  • output_all_columns (bool, 預設為 False) — 在輸出中也保留未格式化的列(作為 python 物件)。如果設定為 True,則其他未格式化的列將與轉換的輸出一起保留。

使用此轉換設定 __getitem__ 返回格式。當呼叫 __getitem__ 時,轉換會即時應用於批次。

set_format() 一樣,這可以使用 reset_format() 重置。

set_transform() 不同,with_transform 返回一個新的 Dataset 物件。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> def encode(example):
...     return tokenizer(example["text"], padding=True, truncation=True, return_tensors='pt')
>>> ds = ds.with_transform(encode)
>>> ds[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]),
 '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]),
 '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])}

__getitem__

< >

( key )

可用於索引列(透過字串名稱)或行(透過整數索引、索引的可迭代物件或布林值)。

cleanup_cache_files

< >

( ) int

返回

int

已刪除的檔案數。

清理資料集快取目錄中的所有快取檔案,但當前使用的快取檔案(如果有)除外。

執行此命令時要小心,確保沒有其他程序當前正在使用其他快取檔案。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.cleanup_cache_files()
10

map

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False with_rank: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 drop_last_batch: bool = False remove_columns: typing.Union[str, list[str], NoneType] = None keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 features: typing.Optional[datasets.features.features.Features] = None disable_nullable: bool = False fn_kwargs: typing.Optional[dict] = None num_proc: typing.Optional[int] = None suffix_template: str = '_{rank:05d}_of_{num_proc:05d}' new_fingerprint: typing.Optional[str] = None desc: typing.Optional[str] = None try_original_type: typing.Optional[bool] = True )

引數

  • function (Callable) — 具有以下簽名之一的函式:

    • function(example: Dict[str, Any]) -> Dict[str, Any] 如果 batched=Falsewith_indices=Falsewith_rank=False
    • function(example: Dict[str, Any], *extra_args) -> Dict[str, Any] 如果 batched=Falsewith_indices=True 和/或 with_rank=True (每個對應一個額外引數)
    • function(batch: Dict[str, List]) -> Dict[str, List] 如果 batched=Truewith_indices=Falsewith_rank=False
    • function(batch: Dict[str, List], *extra_args) -> Dict[str, List] 如果 batched=Truewith_indices=True 和/或 with_rank=True (每個對應一個額外引數)

    對於高階用法,函式也可以返回一個 pyarrow.Table。如果函式是非同步的,那麼 map 將並行執行您的函式。此外,如果您的函式不返回任何內容(None),那麼 map 將執行您的函式並返回未更改的資料集。如果沒有提供函式,則預設為恆等函式:lambda x: x

  • with_indices (bool, 預設為 False) — 向 function 提供樣本索引。請注意,在這種情況下,function 的簽名應為 def function(example, idx[, rank]): ...
  • with_rank (bool, 預設為 False) — 向 function 提供程序等級。請注意,在這種情況下,function 的簽名應為 def function(example[, idx], rank): ...
  • input_columns (Optional[Union[str, List[str]]], 預設為 None) — 要作為位置引數傳遞給 function 的列。如果為 None,則將一個對映到所有格式化列的 dict 作為單個引數傳遞。
  • batched (bool, 預設為 False) — 向 function 提供批次的樣本。
  • batch_size (int, optional, 預設為 1000) — 如果 batched=True,提供給 function 的每個批次的樣本數。如果 batch_size <= 0batch_size == None,則將整個資料集作為單個批次提供給 function
  • drop_last_batch (bool, 預設為 False) — 是否應丟棄小於 batch_size 的最後一個批次,而不是由函式處理。
  • remove_columns (Optional[Union[str, List[str]]], 預設為 None) — 在對映時移除選定的列。列將在使用 function 的輸出更新樣本之前被移除,即如果 function 正在新增名稱在 remove_columns 中的列,這些列將被保留。
  • keep_in_memory (bool, 預設為 False) — 將資料集保留在記憶體中,而不是寫入快取檔案。
  • load_from_cache_file (Optional[bool], 如果啟用了快取,則預設為 True) — 如果可以識別出儲存當前 function 計算結果的快取檔案,則使用它而不是重新計算。
  • cache_file_name (str, optional, 預設為 None) — 提供快取檔案的路徑名稱。它用於儲存計算結果,而不是自動生成的快取檔名。
  • writer_batch_size (int, 預設為 1000) — 快取檔案寫入器每次寫入操作的行數。此值是在處理過程中的記憶體使用和處理速度之間的一個良好權衡。較高的值使處理過程中的查詢次數減少,較低的值在執行 map 時消耗較少的臨時記憶體。
  • features (Optional[datasets.Features], 預設為 None) — 使用特定的 Features 來儲存快取檔案,而不是自動生成的。
  • disable_nullable (bool, 預設為 False) — 不允許表中有空值。
  • fn_kwargs (Dict, optional, 預設為 None) — 要傳遞給 function 的關鍵字引數。
  • num_proc (int, optional, 預設為 None) — 生成快取時的最大程序數。已快取的分片將按順序載入。
  • suffix_template (str) — 如果指定了 cache_file_name,則此後綴將新增到每個基本名稱的末尾。預設為 "_{rank:05d}_of_{num_proc:05d}"。例如,如果 cache_file_name 是 “processed.arrow”,那麼對於 rank=1num_proc=4,對於預設字尾,生成的檔案將是 "processed_00001_of_00004.arrow"
  • new_fingerprint (str, optional, 預設為 None) — 轉換後資料集的新指紋。如果為 None,則使用先前指紋和轉換引數的雜湊值計算新指紋。
  • desc (str, optional, 預設為 None) — 有意義的描述,在對映樣本時與進度條一起顯示。
  • try_original_type (Optional[bool], 預設為 True) — 嘗試保留原始列的型別(例如,int32 -> int32)。如果您希望總是推斷新型別,請設定為 False。

對錶中的所有示例(單個或批次)應用一個函式並更新表。如果您的函式返回一個已存在的列,那麼它將被覆蓋。

您可以使用 `batched` 引數指定函式是否應批次處理。

  • 如果 `batched` 為 `False`,則函式接收 1 個示例作為輸入,並應返回 1 個示例。一個示例是一個字典,例如 `{"text": "Hello there !"}`。
  • 如果 `batched` 為 `True` 且 `batch_size` 為 1,則函式接收一個包含 1 個示例的批次作為輸入,並可以返回一個包含 1 個或多個示例的批次。一個批次是一個字典,例如,一個包含 1 個示例的批次是 `{"text": ["Hello there !"]}`。
  • 如果 `batched` 為 `True` 且 `batch_size` 為 `n > 1`,則函式接收一個包含 `n` 個示例的批次作為輸入,並可以返回一個包含 `n` 個示例或任意數量示例的批次。請注意,最後一個批次可能少於 `n` 個示例。一個批次是一個字典,例如,一個包含 `n` 個示例的批次是 `{"text": ["Hello there !"] * n}`。

如果函式是非同步的,那麼 `map` 將並行執行您的函式,最多可同時進行一千次呼叫。如果您想設定可以同時執行的最大運算元,建議在您的函式中使用 `asyncio.Semaphore`。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> ds[0:3]["text"]
['Review: compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .',
 'Review: the soundtrack alone is worth the price of admission .',
 'Review: rodriguez does a splendid job of racial profiling hollywood style--casting excellent latin actors of all ages--a trend long overdue .']

# 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)

過濾器

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False with_rank: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 fn_kwargs: typing.Optional[dict] = None num_proc: typing.Optional[int] = None suffix_template: str = '_{rank:05d}_of_{num_proc:05d}' new_fingerprint: typing.Optional[str] = None desc: typing.Optional[str] = None )

引數

  • function (Callable) — 具有以下簽名之一的可呼叫物件:

    • function(example: Dict[str, Any]) -> bool 如果 batched=Falsewith_indices=Falsewith_rank=False
    • function(example: Dict[str, Any], *extra_args) -> bool 如果 batched=Falsewith_indices=True 和/或 with_rank=True(每個對應一個額外引數)
    • function(batch: Dict[str, List]) -> List[bool] 如果 batched=Truewith_indices=Falsewith_rank=False
    • function(batch: Dict[str, List], *extra_args) -> List[bool] 如果 batched=Truewith_indices=True 和/或 with_rank=True(每個對應一個額外引數)

    如果函式是非同步的,那麼 `filter` 將並行執行您的函式。如果未提供函式,則預設為始終返回 `True` 的函式:`lambda x: True`。

  • with_indices (bool, 預設為 False) — 向 `function` 提供示例索引。請注意,在這種情況下,`function` 的簽名應為 `def function(example, idx[, rank]): ...`。
  • with_rank (bool, 預設為 False) — 向 `function` 提供程序排名。請注意,在這種情況下,`function` 的簽名應為 `def function(example[, idx], rank): ...`。
  • input_columns (strList[str], *可選*) — 要作為位置引數傳遞給 `function` 的列。如果為 `None`,則將一個對映到所有格式化列的 `dict` 作為單個引數傳遞。
  • batched (bool, 預設為 False) — 向 `function` 提供一批示例。
  • batch_size (int, *可選*, 預設為 1000) — 如果 `batched = True`,提供給 `function` 的每批示例數。如果 `batched = False`,則每個批次向 `function` 傳遞一個示例。如果 `batch_size <= 0` 或 `batch_size == None`,則將整個資料集作為單個批次提供給 `function`。
  • keep_in_memory (bool, 預設為 False) — 將資料集保留在記憶體中,而不是寫入快取檔案。
  • load_from_cache_file (Optional[bool], 如果啟用快取則預設為 True) — 如果可以識別儲存當前 `function` 計算結果的快取檔案,則使用它而不是重新計算。
  • cache_file_name (str, *可選*) — 提供快取檔案的路徑名稱。它用於儲存計算結果,而不是使用自動生成的快取檔名。
  • writer_batch_size (int, 預設為 1000) — 快取檔案寫入器的每次寫入操作的行數。此值是在處理過程中的記憶體使用和處理速度之間的一個良好權衡。較高的值使處理過程中的查詢次數減少,較低的值在執行 `map` 時消耗更少的臨時記憶體。
  • fn_kwargs (dict, *可選*) — 要傳遞給 `function` 的關鍵字引數。
  • num_proc (int, *可選*) — 用於多程序處理的程序數。預設情況下不使用多程序處理。
  • suffix_template (str) — 如果指定了 `cache_file_name`,則此後綴將新增到每個基本名稱的末尾。例如,如果 `cache_file_name` 是 `"processed.arrow"`,那麼對於 `rank = 1` 和 `num_proc = 4`,對於預設字尾(預設為 `_{rank:05d}_of_{num_proc:05d}`),生成的檔案將是 `"processed_00001_of_00004.arrow"`。
  • new_fingerprint (str, *可選*) — 轉換後資料集的新指紋。如果為 `None`,則使用前一個指紋的雜湊值和轉換引數計算新指紋。
  • desc (str, *可選*, 預設為 None) — 在過濾示例時與進度條一起顯示的富有意義的描述。

對錶中的所有元素批次應用一個過濾函式,並更新表,使得資料集只包含符合過濾函式的示例。

如果函式是非同步的,那麼 `filter` 將並行執行您的函式,最多可同時進行一千次呼叫(可配置)。如果您想設定可以同時執行的最大運算元,建議在您的函式中使用 `asyncio.Semaphore`。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.filter(lambda x: x["label"] == 1)
Dataset({
    features: ['text', 'label'],
    num_rows: 533
})

選擇

< >

( indices: Iterable keep_in_memory: bool = False indices_cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 new_fingerprint: typing.Optional[str] = None )

引數

  • indices (range, list, iterable, ndarraySeries) — 用於索引的整數索引的範圍、列表或一維陣列。如果索引對應一個連續範圍,Arrow 表將被簡單地切片。然而,傳遞一個不連續的索引列表會建立索引對映,這效率要低得多,但仍然比重新建立一個由所請求行組成的 Arrow 表要快。
  • keep_in_memory (bool, 預設為 False) — 將索引對映保留在記憶體中,而不是寫入快取檔案。
  • indices_cache_file_name (str, *可選*, 預設為 None) — 提供快取檔案的路徑名稱。它用於儲存索引對映,而不是使用自動生成的快取檔名。
  • writer_batch_size (int, 預設為 1000) — 快取檔案寫入器的每次寫入操作的行數。此值是在處理過程中的記憶體使用和處理速度之間的一個良好權衡。較高的值使處理過程中的查詢次數減少,較低的值在執行 `map` 時消耗更少的臨時記憶體。
  • new_fingerprint (str, *可選*, 預設為 None) — 轉換後資料集的新指紋。如果為 `None`,則使用前一個指紋的雜湊值和轉換引數計算新指紋。

根據索引列表/陣列建立一個新的資料集,其中包含選定的行。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds.select(range(4))
Dataset({
    features: ['text', 'label'],
    num_rows: 4
})

sort

< >

( column_names: typing.Union[str, collections.abc.Sequence[str]] reverse: typing.Union[bool, collections.abc.Sequence[bool]] = False null_placement: str = 'at_end' keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None indices_cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 new_fingerprint: typing.Optional[str] = None )

引數

  • column_names (Union[str, Sequence[str]]) — 用於排序的列名。
  • reverse (Union[bool, Sequence[bool]], 預設為 False) — 如果為 `True`,則按降序而非升序排序。如果提供單個布林值,則該值將應用於所有列名的排序。否則,必須提供一個與 column_names 長度和順序相同的布林值列表。
  • null_placement (str, 預設為 at_end) — 如果為 `at_start` 或 `first`,則將 `None` 值放在開頭;如果為 `at_end` 或 `last`,則放在末尾。

    1.14.2 版本新增

  • keep_in_memory (bool, 預設為 False) — 將排序後的索引保留在記憶體中,而不是寫入快取檔案。
  • load_from_cache_file (Optional[bool], 如果啟用快取則預設為 True) — 如果可以識別儲存排序後索引的快取檔案,則使用它而不是重新計算。
  • indices_cache_file_name (str, *可選*, 預設為 None) — 提供快取檔案的路徑名稱。它用於儲存排序後的索引,而不是使用自動生成的快取檔名。
  • writer_batch_size (int, 預設為 1000) — 快取檔案寫入器的每次寫入操作的行數。較高的值會產生較小的快取檔案,較低的值會消耗較少的臨時記憶體。
  • new_fingerprint (str, *可選*, 預設為 None) — 轉換後資料集的新指紋。如果為 `None`,則使用前一個指紋的雜湊值和轉換引數計算新指紋。

根據單個或多個列建立一個新的已排序的資料集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset('cornell-movie-review-data/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, 0]
>>> another_sorted_ds = ds.sort(['label', 'text'], reverse=[True, False])
>>> another_sorted_ds['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

shuffle

< >

( seed: typing.Optional[int] = None generator: typing.Optional[numpy.random._generator.Generator] = None keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None indices_cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 new_fingerprint: typing.Optional[str] = None )

引數

  • seed (int, *可選*) — 如果 `generator=None`,用於初始化預設 BitGenerator 的種子。如果為 `None`,則將從作業系統中獲取新的、不可預測的熵。如果傳遞一個 `int` 或 `array_like[ints]`,則它將被傳遞給 SeedSequence 以派生初始 BitGenerator 狀態。
  • generator (numpy.random.Generator, *可選*) — 用於計算資料集行排列的 Numpy 隨機生成器。如果 `generator=None`(預設),則使用 `np.random.default_rng`(NumPy 的預設 BitGenerator (PCG64))。
  • keep_in_memory (bool, 預設為 False) — 將打亂後的索引保留在記憶體中,而不是寫入快取檔案。
  • load_from_cache_file (Optional[bool], 如果啟用快取則預設為 True) — 如果可以識別儲存打亂後索引的快取檔案,則使用它而不是重新計算。
  • indices_cache_file_name (str, *可選*) — 提供快取檔案的路徑名稱。它用於儲存打亂後的索引,而不是使用自動生成的快取檔名。
  • writer_batch_size (int, 預設為 1000) — 快取檔案寫入器的每次寫入操作的行數。此值是在處理過程中的記憶體使用和處理速度之間的一個良好權衡。較高的值使處理過程中的查詢次數減少,較低的值在執行 `map` 時消耗更少的臨時記憶體。
  • new_fingerprint (str, *可選*, 預設為 None) — 轉換後資料集的新指紋。如果為 `None`,則使用前一個指紋的雜湊值和轉換引數計算新指紋。

建立一個新的資料集,其中的行被打亂。

目前,打亂操作使用 numpy 隨機生成器。您可以提供一個 NumPy BitGenerator 來使用,或者提供一個種子來初始化 NumPy 的預設隨機生成器(PCG64)。

打亂操作會取索引列表 `[0:len(my_dataset)]` 並將其打亂以建立一個索引對映。然而,一旦您的 Dataset 有了索引對映,速度可能會慢 10 倍。這是因為需要額外一步透過索引對映來獲取要讀取的行索引,更重要的是,您不再是讀取連續的資料塊。要恢復速度,您需要使用 Dataset.flatten_indices() 在磁碟上重寫整個資料集,這會移除索引對映。

不過,這可能會花費很多時間,具體取決於您的資料集大小。

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

在這種情況下,我們建議切換到 IterableDataset 並利用其快速的近似打亂方法 IterableDataset.shuffle()

它只打亂分片的順序,併為您的資料集新增一個打亂緩衝區,這可以保持資料集的最佳速度。

my_iterable_dataset = my_dataset.to_iterable_dataset(num_shards=128)
for example in enumerate(my_iterable_dataset):  # fast
    pass

shuffled_iterable_dataset = my_iterable_dataset.shuffle(seed=42, buffer_size=100)

for example in enumerate(shuffled_iterable_dataset):  # as fast as before
    pass

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/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]
[1, 0, 1, 1, 0, 0, 0, 0, 0, 0]

skip

< >

( n: int )

引數

  • n (int) — 要跳過的元素數量。

建立一個新的 Dataset,它會跳過前 `n` 個元素。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/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 schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 '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'}]
>>> ds = ds.skip(1)
>>> list(ds.take(3))
[{'label': 1,
 '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'},
 {'label': 1,
 'text': 'if you sometimes like to go to the movies to have fun , wasabi is a good place to start .'}]

take

< >

( n: int )

引數

  • n (int) — 要獲取的元素數量。

建立一個新的 Dataset,其中只包含前 `n` 個元素。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> small_ds = ds.take(2)
>>> list(small_ds)
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 '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 .'}]

train_test_split

< >

( test_size: typing.Union[float, int, NoneType] = None train_size: typing.Union[float, int, NoneType] = None shuffle: bool = True stratify_by_column: typing.Optional[str] = None seed: typing.Optional[int] = None generator: typing.Optional[numpy.random._generator.Generator] = None keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None train_indices_cache_file_name: typing.Optional[str] = None test_indices_cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 train_new_fingerprint: typing.Optional[str] = None test_new_fingerprint: typing.Optional[str] = None )

引數

  • test_size (numpy.random.Generator, *可選*) — 測試集的大小。如果為 `float`,應在 `0.0` 和 `1.0` 之間,表示要包含在測試集中的資料集比例。如果為 `int`,表示測試樣本的絕對數量。如果為 `None`,則該值設定為訓練集大小的補集。如果 `train_size` 也為 `None`,則它將被設定為 `0.25`。
  • train_size (numpy.random.Generator, *可選*) — 訓練集的大小。如果為 `float`,應在 `0.0` 和 `1.0` 之間,表示要包含在訓練集中的資料集比例。如果為 `int`,表示訓練樣本的絕對數量。如果為 `None`,則該值自動設定為測試集大小的補集。
  • shuffle (bool, *可選*, 預設為 True) — 是否在分割前打亂資料。
  • stratify_by_column (str, *可選*, 預設為 None) — 用於執行資料分層分割的標籤列名。
  • seed (int, *可選*) — 如果 `generator=None`,用於初始化預設 BitGenerator 的種子。如果為 `None`,則將從作業系統中獲取新的、不可預測的熵。如果傳遞一個 `int` 或 `array_like[ints]`,則它將被傳遞給 SeedSequence 以派生初始 BitGenerator 狀態。
  • generator (numpy.random.Generator, *可選*) — 用於計算資料集行排列的 Numpy 隨機生成器。如果 `generator=None`(預設),則使用 `np.random.default_rng`(NumPy 的預設 BitGenerator (PCG64))。
  • keep_in_memory (bool,預設為 False) — 將拆分索引保留在記憶體中,而不是將其寫入快取檔案。
  • load_from_cache_file (Optional[bool],如果啟用快取,預設為 True) — 如果可以識別儲存拆分索引的快取檔案,則使用它而不是重新計算。
  • train_cache_file_name (str可選) — 提供快取檔案的路徑名稱。它用於儲存訓練集拆分索引,而不是使用自動生成的快取檔名。
  • test_cache_file_name (str可選) — 提供快取檔案的路徑名稱。它用於儲存測試集拆分索引,而不是使用自動生成的快取檔名。
  • writer_batch_size (int,預設為 1000) — 快取檔案寫入器每次寫入操作的行數。這個值是在處理過程中的記憶體使用和處理速度之間的一個很好的權衡。較高的值會使處理過程中的查詢次數減少,較低的值在執行 map 時消耗的臨時記憶體更少。
  • train_new_fingerprint (str可選,預設為 None) — 轉換後訓練集的新指紋。如果為 None,則新指紋將使用先前指紋的雜湊值和轉換引數計算得出。
  • test_new_fingerprint (str可選,預設為 None) — 轉換後測試集的新指紋。如果為 None,則新指紋將使用先前指紋的雜湊值和轉換引數計算得出。

返回一個包含兩個隨機訓練和測試子集的字典(datasets.DatasetDict)(traintest Dataset 拆分)。拆分是根據 test_sizetrain_sizeshuffle 從資料集中建立的。

此方法類似於 scikit-learn 的 train_test_split

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds = ds.train_test_split(test_size=0.2, shuffle=True)
DatasetDict({
    train: Dataset({
        features: ['text', 'label'],
        num_rows: 852
    })
    test: Dataset({
        features: ['text', 'label'],
        num_rows: 214
    })
})

# set a seed
>>> ds = ds.train_test_split(test_size=0.2, seed=42)

# 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({
        features: ['text', 'label'],
        num_rows: 20000
    })
    test: Dataset({
        features: ['text', 'label'],
        num_rows: 5000
    })
})

shard

< >

( num_shards: int index: int contiguous: bool = True keep_in_memory: bool = False indices_cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 )

引數

  • num_shards (int) — 將資料集拆分成多少個分片。
  • index (int) — 選擇並返回哪個分片。
  • contiguous — (bool,預設為 True):是否為分片選擇連續的索引塊。
  • keep_in_memory (bool,預設為 False) — 將資料集保留在記憶體中,而不是將其寫入快取檔案。
  • indices_cache_file_name (str可選) — 提供快取檔案的路徑名稱。它用於儲存每個分片的索引,而不是使用自動生成的快取檔名。
  • writer_batch_size (int,預設為 1000) — 這僅涉及索引對映。快取檔案寫入器每次寫入操作的索引數。這個值是在處理過程中的記憶體使用和處理速度之間的一個很好的權衡。較高的值會使處理過程中的查詢次數減少,較低的值在執行 map 時消耗的臨時記憶體更少。

返回將資料集拆分成 num_shards 份後的第 index 個分片。

此分片操作是確定性的。`dataset.shard(n, i)` 將資料集拆分為連續的塊,因此在處理後可以輕鬆地將其連接回來。如果 `len(dataset) % n == l`,那麼前 `l` 個數據集的長度為 `(len(dataset) // n) + 1`,其餘資料集的長度為 `(len(dataset) // n)`。`datasets.concatenate_datasets([dset.shard(n, i) for i in range(n)])` 返回一個與原始資料集順序相同的的資料集。

注意:n 應小於或等於資料集中的元素數量 `len(dataset)`。

另一方面,`dataset.shard(n, i, contiguous=False)` 包含資料集中所有索引模 `n` 等於 `i` 的元素。

在使用任何隨機化運算子(如 `shuffle`)之前,請務必進行分片。最好在資料集管道的早期使用分片運算子。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation")
>>> ds
Dataset({
    features: ['text', 'label'],
    num_rows: 1066
})
>>> ds.shard(num_shards=2, index=0)
Dataset({
    features: ['text', 'label'],
    num_rows: 533
})

repeat

< >

( num_times: int )

引數

  • num_times (int) — 重複資料集的次數。

建立一個新的 Dataset,它將底層資料集重複 `num_times` 次。

與 itertools.repeat 類似,重複一次僅返回完整的資料集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> ds = ds.take(2).repeat(2)
>>> list(ds)
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 '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'},
 {'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 schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 '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'}]

to_tf_dataset

< >

( batch_size: typing.Optional[int] = None columns: typing.Union[str, list[str], NoneType] = None shuffle: bool = False collate_fn: typing.Optional[typing.Callable] = None drop_remainder: bool = False collate_fn_args: typing.Optional[dict[str, typing.Any]] = None label_cols: typing.Union[str, list[str], NoneType] = None prefetch: bool = True num_workers: int = 0 num_test_batches: int = 20 )

引數

  • batch_size (int可選) — 從資料集中載入的批次大小。預設為 None,表示資料集不會被批處理,但返回的資料集可以稍後使用 tf_dataset.batch(batch_size) 進行批處理。
  • columns (List[str]str可選) — 在 tf.data.Dataset 中載入的資料集列。可以使用由 collate_fn 建立且在原始資料集中不存在的列名。
  • shuffle(bool預設為 False) — 載入時打亂資料集順序。建議在訓練時為 True,在驗證/評估時為 False
  • drop_remainder(bool預設為 False) — 載入時丟棄最後一個不完整的批次。確保資料集產生的所有批次在批次維度上具有相同的長度。
  • collate_fn(Callable可選) — 一個函式或可呼叫物件(例如 DataCollator),用於將樣本列表整理成一個批次。
  • collate_fn_args (Dict可選) — 一個可選的 `dict`,包含要傳遞給 `collate_fn` 的關鍵字引數。
  • label_cols (List[str]str,預設為 None) — 作為標籤載入的資料集列。請注意,許多模型在內部計算損失,而不是讓 Keras 來做,在這種情況下,只要標籤在輸入的 `columns` 中,傳遞標籤就是可選的。
  • prefetch (bool,預設為 True) — 是否在單獨的執行緒中執行資料載入器併為訓練維護一個小的批次緩衝區。透過允許在模型訓練時在後臺載入資料來提高效能。
  • num_workers (int,預設為 0) — 用於載入資料集的工作程序數。
  • num_test_batches (int,預設為 20) — 用於推斷資料集輸出簽名的批次數。這個數字越高,簽名就越準確,但建立資料集所需的時間就越長。

從底層資料集建立一個 `tf.data.Dataset`。這個 `tf.data.Dataset` 將從資料集中載入和整理批次,並適用於傳遞給 `model.fit()` 或 `model.predict()` 等方法。資料集將為輸入和標籤都產生 `dicts`,除非 `dict` 只包含一個鍵,在這種情況下,將產生一個原始的 `tf.Tensor`。

示例

>>> 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,
... )

push_to_hub

< >

( repo_id: str config_name: str = 'default' set_default: typing.Optional[bool] = None split: typing.Optional[str] = None data_dir: typing.Optional[str] = None commit_message: typing.Optional[str] = None commit_description: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Optional[str] = None revision: typing.Optional[str] = None create_pr: typing.Optional[bool] = False max_shard_size: typing.Union[str, int, NoneType] = None num_shards: typing.Optional[int] = None embed_external_files: bool = True num_proc: typing.Optional[int] = None )

引數

  • repo_id (str) — 要推送到的倉庫 ID,格式如下:`<user>/<dataset_name>` 或 `<org>/<dataset_name>`。也接受 `<dataset_name>`,這將預設為已登入使用者的名稱空間。
  • config_name (str,預設為“default”) — 資料集的配置名稱(或子集)。預設為“default”。
  • set_default (bool可選) — 是否將此配置設定為預設配置。否則,預設配置是名為“default”的配置。
  • split (str可選) — 將賦予該資料集的拆分名稱。預設為 `self.split`。
  • data_dir (str可選) — 包含上傳資料檔案的目錄名稱。如果 `config_name` 不同於“default”,則預設為 `config_name`,否則為“data”。

    在 2.17.0 中新增

  • commit_message (str可選) — 推送時要提交的訊息。將預設為 `"Upload dataset"`。
  • commit_description (str可選) — 將要建立的提交的描述。此外,如果建立了 PR(`create_pr` 為 True),則為 PR 的描述。

    在 2.16.0 中新增

  • private (bool可選) — 是否將倉庫設為私有。如果為 `None` (預設值),除非組織的預設設定為私有,否則倉庫將為公開。如果倉庫已存在,則此值將被忽略。
  • token (str可選) — 用於 Hugging Face Hub 的可選身份驗證令牌。如果未傳遞令牌,將預設為使用 `huggingface-cli login` 登入時本地儲存的令牌。如果未傳遞令牌且使用者未登入,將引發錯誤。
  • revision (str可選) — 要將上傳的檔案推送到的分支。預設為 `“main”` 分支。

    在 2.15.0 中新增

  • create_pr (bool可選,預設為 `False`) — 是建立包含上傳檔案的 PR 還是直接提交。

    在 2.15.0 中新增

  • max_shard_size (intstr可選,預設為 `"500MB"`) — 要上傳到 hub 的資料集分片的最大大小。如果以字串形式表示,需要是數字後跟一個單位(例如 `"5MB"`)。
  • num_shards (int可選) — 要寫入的分片數。預設情況下,分片數取決於 `max_shard_size`。

    在 2.8.0 中新增

  • embed_external_files (bool,預設為 `True`) — 是否在分片中嵌入檔案位元組。特別是,在推送之前,這將對以下型別的欄位執行以下操作:

    • AudioImage:刪除本地路徑資訊並在 Parquet 檔案中嵌入檔案內容。
  • num_proc (int可選,預設為 `None`) — 準備和上傳資料集時的程序數。如果資料集由許多樣本或要嵌入的媒體檔案組成,這會很有幫助。預設情況下停用多程序。

    在 4.0.0 中新增

將資料集作為 Parquet 資料集推送到 Hub。資料集使用 HTTP 請求推送,不需要安裝 git 或 git-lfs。

預設情況下,生成的 Parquet 檔案是自包含的。如果您的資料集包含 ImageAudioVideo 資料,Parquet 檔案將儲存您的影像或音訊檔案的位元組。您可以透過將 `embed_external_files` 設定為 `False` 來停用此功能。

示例

>>> dataset.push_to_hub("<organization>/<dataset_id>")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", private=True)
>>> dataset.push_to_hub("<organization>/<dataset_id>", max_shard_size="1GB")
>>> dataset.push_to_hub("<organization>/<dataset_id>", num_shards=1024)

如果您的資料集有多個拆分(例如 train/validation/test)

>>> train_dataset.push_to_hub("<organization>/<dataset_id>", split="train")
>>> val_dataset.push_to_hub("<organization>/<dataset_id>", split="validation")
>>> # later
>>> dataset = load_dataset("<organization>/<dataset_id>")
>>> train_dataset = dataset["train"]
>>> val_dataset = dataset["validation"]

如果您想向資料集新增新的配置(或子集)(例如,如果資料集有多個任務/版本/語言)

>>> 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>/<dataset_id>", "fr")

save_to_disk

< >

( dataset_path: typing.Union[str, bytes, os.PathLike] max_shard_size: typing.Union[str, int, NoneType] = None num_shards: typing.Optional[int] = None num_proc: typing.Optional[int] = None storage_options: typing.Optional[dict] = None )

引數

  • dataset_path (path-like) — 資料集目錄的路徑(例如 `dataset/train`)或遠端 URI(例如 `s3://my-bucket/dataset/train`),資料集將儲存到此處。
  • max_shard_size (intstr可選,預設為 `"500MB"`) — 要儲存到檔案系統的資料集分片的最大大小。如果以字串形式表示,需要是數字後跟一個單位(例如 `"50MB"`)。
  • num_shards (int可選) — 要寫入的分片數。預設情況下,分片數取決於 `max_shard_size` 和 `num_proc`。

    在 2.8.0 中新增

  • num_proc (int可選) — 在本地下載和生成資料集時的程序數。預設情況下停用多程序。

    在 2.8.0 中新增

  • storage_options (dict可選) — 要傳遞給檔案系統後端的鍵/值對(如果有)。

    在 2.8.0 中新增

將資料集儲存到資料集目錄中,或使用 `fsspec.spec.AbstractFileSystem` 的任何實現儲存到檔案系統中。

對於 ImageAudioVideo 資料

所有的 Image()、Audio() 和 Video() 資料都儲存在 arrow 檔案中。如果您想儲存路徑或 url,請使用 Value(“string”) 型別。

示例

>>> 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)

load_from_disk

< >

( dataset_path: typing.Union[str, bytes, os.PathLike] keep_in_memory: typing.Optional[bool] = None storage_options: typing.Optional[dict] = None ) DatasetDatasetDict

引數

  • dataset_path (path-like) — 資料集目錄的路徑(例如 `"dataset/train"`)或遠端 URI(例如 `"s3//my-bucket/dataset/train"`),將從此位置載入資料集。
  • keep_in_memory (bool,預設為 `None`) — 是否將資料集複製到記憶體中。如果為 `None`,則資料集將不會被複制到記憶體中,除非透過將 `datasets.config.IN_MEMORY_MAX_SIZE` 設定為非零值來明確啟用。更多詳細資訊請參閱提高效能部分。
  • storage_options (dict可選) — 要傳遞給檔案系統後端的鍵/值對(如果有)。

    在 2.8.0 中新增

返回

DatasetDatasetDict

  • 如果 `dataset_path` 是資料集目錄的路徑,則返回請求的資料集。
  • 如果 `dataset_path` 是資料集字典目錄的路徑,則返回一個包含每個拆分的 `datasets.DatasetDict`。

從資料集目錄載入先前使用 `save_to_disk` 儲存的資料集,或使用 `fsspec.spec.AbstractFileSystem` 的任何實現從檔案系統中載入。

示例

>>> ds = load_from_disk("path/to/dataset/directory")

flatten_indices

< >

( keep_in_memory: bool = False cache_file_name: typing.Optional[str] = None writer_batch_size: typing.Optional[int] = 1000 features: typing.Optional[datasets.features.features.Features] = None disable_nullable: bool = False num_proc: typing.Optional[int] = None new_fingerprint: typing.Optional[str] = None )

引數

  • keep_in_memory (bool, 預設為 False) — 將資料集保留在記憶體中,而不是將其寫入快取檔案。
  • cache_file_name (str, 可選, 預設為 None) — 提供快取檔案的路徑名稱。它用於儲存計算結果,而不是使用自動生成的快取檔名。
  • writer_batch_size (int, 預設為 1000) — 快取檔案寫入器每次寫入操作的行數。這個值是在處理過程中的記憶體使用和處理速度之間的一個很好的權衡。較高的值使處理過程中的查詢次數減少,較低的值在執行 map 時消耗更少的臨時記憶體。
  • features (Optional[datasets.Features], 預設為 None) — 使用特定的 Features 來儲存快取檔案,而不是使用自動生成的特性。
  • disable_nullable (bool, 預設為 False) — 允許表中的空值。
  • num_proc (int, 可選, 預設為 None) — 生成快取時使用的最大程序數。已經快取的分片會按順序載入。
  • new_fingerprint (str, 可選, 預設為 None) — 轉換後資料集的新指紋。如果為 None,則新指紋將使用前一個指紋和轉換引數的雜湊值計算。

透過扁平化索引對映建立並快取一個新的資料集。

to_csv

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None num_proc: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **to_csv_kwargs ) int

引數

  • path_or_buf (PathLike or FileOrBuffer) — 檔案路徑(例如 file.csv)、遠端 URI(例如 hf://datasets/username/my_dataset_name/data.csv)或 BinaryIO,資料集將以指定格式儲存到此處。
  • batch_size (int, 可選) — 一次載入到記憶體並寫入的批次大小。預設為 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • num_proc (int, 可選) — 用於多程序的程序數。預設情況下不使用多程序。在這種情況下,batch_size 預設為 datasets.config.DEFAULT_MAX_BATCH_SIZE,但如果您有足夠的計算能力,可以隨意將其設定為預設值的 5 倍或 10 倍。
  • storage_options (dict, 可選) — 傳遞給檔案系統後端的鍵/值對(如果有)。

    2.19.0 版本中新增

  • **to_csv_kwargs (附加關鍵字引數) — 傳遞給 pandas 的 pandas.DataFrame.to_csv 的引數。

    2.10.0 版本中更改

    現在,如果未指定,index 預設為 False

    如果您想寫入索引,請傳遞 index=True,並透過傳遞 index_label 為索引列設定名稱。

返回

int

寫入的字元或位元組數。

將資料集匯出為 csv 檔案。

示例

>>> ds.to_csv("path/to/dataset/directory")

to_pandas

< >

( batch_size: typing.Optional[int] = None batched: bool = False )

引數

  • batch_size (int, 可選) — 如果 batchedTrue,則為批次的大小(行數)。預設為 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • batched (bool) — 設定為 True 以返回一個生成器,該生成器以 batch_size 行的批次形式產生資料集。預設為 False(一次性返回整個資料集)。

將資料集作為 pandas.DataFrame 返回。對於大型資料集,也可以返回一個生成器。

示例

>>> ds.to_pandas()

to_dict

< >

( batch_size: typing.Optional[int] = None batched: bool = False )

引數

  • batch_size (int, 可選) — 如果 batchedTrue,則為批次的大小(行數)。預設為 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • batched (bool) — 設定為 True 以返回一個生成器,該生成器以 batch_size 行的批次形式產生資料集。預設為 False(一次性返回整個資料集)。

將資料集作為 Python 字典返回。對於大型資料集,也可以返回一個生成器。

示例

>>> ds.to_dict()

to_json

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None num_proc: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **to_json_kwargs ) int

引數

  • path_or_buf (PathLike or FileOrBuffer) — 檔案路徑(例如 file.json)、遠端 URI(例如 hf://datasets/username/my_dataset_name/data.json)或 BinaryIO,資料集將以指定格式儲存到此處。
  • batch_size (int, 可選) — 一次載入到記憶體並寫入的批次大小。預設為 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • num_proc (int, 可選) — 用於多程序的程序數。預設情況下,不使用多程序。在這種情況下,batch_size 預設為 datasets.config.DEFAULT_MAX_BATCH_SIZE,但如果您有足夠的計算能力,可以隨意將其設定為預設值的 5 倍或 10 倍。
  • storage_options (dict, 可選) — 傳遞給檔案系統後端的鍵/值對(如果有)。

    2.19.0 版本中新增

  • **to_json_kwargs (附加關鍵字引數) — 傳遞給 pandas 的 pandas.DataFrame.to_json 的引數。預設引數是 lines=True 和 `orient="records"`。

    2.11.0 版本中更改

    如果 orient"split""table",引數 index 預設為 False

    如果您想寫入索引,請傳遞 index=True

返回

int

寫入的字元或位元組數。

將資料集匯出為 JSON Lines 或 JSON。

預設輸出格式是 JSON Lines。要匯出為 JSON,請傳遞 lines=False 引數和所需的 orient

示例

>>> ds.to_json("path/to/dataset/directory/filename.jsonl")

to_parquet

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **parquet_writer_kwargs ) int

引數

  • path_or_buf (PathLike or FileOrBuffer) — 檔案路徑(例如 file.parquet)、遠端 URI(例如 hf://datasets/username/my_dataset_name/data.parquet)或 BinaryIO,資料集將以指定格式儲存到此處。
  • batch_size (int, 可選) — 一次載入到記憶體並寫入的批次大小。預設為 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • storage_options (dict, 可選) — 傳遞給檔案系統後端的鍵/值對(如果有)。

    2.19.0 版本中新增

  • **parquet_writer_kwargs (附加關鍵字引數) — 傳遞給 PyArrow 的 pyarrow.parquet.ParquetWriter 的引數。

返回

int

寫入的字元或位元組數。

將資料集匯出為 parquet 檔案。

示例

>>> ds.to_parquet("path/to/dataset/directory")

to_sql

< >

( name: str con: typing.Union[str, ForwardRef('sqlalchemy.engine.Connection'), ForwardRef('sqlalchemy.engine.Engine'), ForwardRef('sqlite3.Connection')] batch_size: typing.Optional[int] = None **sql_writer_kwargs ) int

引數

  • name (str) — SQL 表的名稱。
  • con (str or sqlite3.Connection or sqlalchemy.engine.Connection or sqlalchemy.engine.Connection) — 一個 URI 字串 或 SQLite3/SQLAlchemy 連線物件,用於向資料庫寫入資料。
  • batch_size (int, 可選) — 一次載入到記憶體並寫入的批次大小。預設為 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • **sql_writer_kwargs (附加關鍵字引數) — 傳遞給 pandas 的 pandas.DataFrame.to_sql 的引數。

    2.11.0 版本中更改

    現在,如果未指定,index 預設為 False

    如果您想寫入索引,請傳遞 index=True,並透過傳遞 index_label 為索引列設定名稱。

返回

int

寫入的記錄數。

將資料集匯出到 SQL 資料庫。

示例

>>> # con provided as a connection URI string
>>> ds.to_sql("data", "sqlite:///my_own_db.sql")
>>> # con provided as a sqlite3 connection object
>>> import sqlite3
>>> con = sqlite3.connect("my_own_db.sql")
>>> with con:
...     ds.to_sql("data", con)

to_iterable_dataset

< >

( num_shards: typing.Optional[int] = 1 )

引數

  • num_shards (int, 預設為 1) — 例項化可迭代資料集時定義的分片數。這對於大資料集特別有用,可以正確地進行洗牌,並且可以使用 PyTorch DataLoader 或在分散式設定中實現快速並行載入。分片是使用 datasets.Dataset.shard() 定義的:它只是對資料進行切片,而不在磁碟上寫入任何內容。

從 map-style datasets.Dataset 獲取一個 datasets.IterableDataset。這相當於使用 datasets.load_dataset() 以流式模式載入資料集,但速度要快得多,因為資料是從本地檔案流式傳輸的。

與 map-style 資料集相反,可迭代資料集是惰性的,只能進行迭代(例如使用 for 迴圈)。由於它們在訓練迴圈中是按順序讀取的,因此可迭代資料集比 map-style 資料集快得多。應用於可迭代資料集的所有轉換(如篩選或處理)都是在您開始迭代資料集時動態完成的。

儘管如此,仍然可以使用 datasets.IterableDataset.shuffle() 對可迭代資料集進行洗牌。這是一種快速的近似洗牌方法,如果您有多個分片並且指定了足夠大的緩衝區大小,效果會最好。

為了獲得最佳的速度效能,請確保您的資料集沒有索引對映。如果存在索引對映,資料將不會被連續讀取,這有時可能會很慢。您可以使用 ds = ds.flatten_indices() 將資料集寫入連續的資料塊中,以在切換到可迭代資料集之前獲得最佳速度。

示例

基本用法

>>> ids = ds.to_iterable_dataset()
>>> for example in ids:
...     pass

使用惰性篩選和處理

>>> ids = ds.to_iterable_dataset()
>>> ids = ids.filter(filter_fn).map(process_fn)  # will filter and process on-the-fly when you start iterating over the iterable dataset
>>> for example in ids:
...     pass

使用分片以實現高效洗牌

>>> ids = ds.to_iterable_dataset(num_shards=64)  # the dataset is split into 64 shards to be iterated over
>>> ids = ids.shuffle(buffer_size=10_000)  # will shuffle the shards order and use a shuffle buffer for fast approximate shuffling when you start iterating
>>> for example in ids:
...     pass

使用 PyTorch DataLoader

>>> import torch
>>> ids = ds.to_iterable_dataset(num_shards=64)
>>> ids = ids.filter(filter_fn).map(process_fn)
>>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4)  # will assign 64 / 4 = 16 shards to each worker to load, filter and process when you start iterating
>>> for example in ids:
...     pass

使用 PyTorch DataLoader 和洗牌

>>> import torch
>>> ids = ds.to_iterable_dataset(num_shards=64)
>>> ids = ids.shuffle(buffer_size=10_000)  # will shuffle the shards order and use a shuffle buffer when you start iterating
>>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4)  # will assign 64 / 4 = 16 shards from the shuffled list of shards to each worker when you start iterating
>>> for example in ids:
...     pass

在 PyTorch DDP 等分散式設定中使用 PyTorch DataLoader 和洗牌

>>> from datasets.distributed import split_dataset_by_node
>>> ids = ds.to_iterable_dataset(num_shards=512)
>>> ids = ids.shuffle(buffer_size=10_000, seed=42)  # will shuffle the shards order and use a shuffle buffer when you start iterating
>>> ids = split_dataset_by_node(ds, world_size=8, rank=0)  # will keep only 512 / 8 = 64 shards from the shuffled lists of shards when you start iterating
>>> dataloader = torch.utils.data.DataLoader(ids, num_workers=4)  # will assign 64 / 4 = 16 shards from this node's list of shards to each worker when you start iterating
>>> for example in ids:
...     pass

使用洗牌和多個 epoch

>>> ids = ds.to_iterable_dataset(num_shards=64)
>>> ids = ids.shuffle(buffer_size=10_000, seed=42)  # will shuffle the shards order and use a shuffle buffer when you start iterating
>>> for epoch in range(n_epochs):
...     ids.set_epoch(epoch)  # will use effective_seed = seed + epoch to shuffle the shards and for the shuffle buffer when you start iterating
...     for example in ids:
...         pass
在使用 PyTorch DataLoader 或在分散式設定中時,也隨時使用 `IterableDataset.set_epoch()`。

add_faiss_index

< >

( column: str index_name: typing.Optional[str] = None device: typing.Optional[int] = None string_factory: typing.Optional[str] = None metric_type: typing.Optional[int] = None custom_index: typing.Optional[ForwardRef('faiss.Index')] = None batch_size: int = 1000 train_size: typing.Optional[int] = None faiss_verbose: bool = False dtype = <class 'numpy.float32'> )

引數

  • column (str) — 要新增到索引的向量所在的列。
  • index_name (str, 可選) — 索引的 index_name/識別符號。這是用於呼叫 get_nearest_examples()search()index_name。預設情況下,它對應於 column
  • device (Union[int, List[int]], 可選) — 如果是正整數,則為要使用的 GPU 的索引。如果是負整數,則使用所有 GPU。如果傳入一個正整數列表,則僅在這些 GPU 上執行。預設情況下使用 CPU。
  • string_factory (str, 可選) — 此引數傳遞給 Faiss 的索引工廠以建立索引。預設索引類是 IndexFlat
  • metric_type (int, 可選) — 度量型別。例如:faiss.METRIC_INNER_PRODUCTfaiss.METRIC_L2
  • custom_index (faiss.Index, 可選) — 您已經根據需要例項化和配置的自定義 Faiss 索引。
  • batch_size (int) — 向 FaissIndex 新增向量時使用的批次大小。預設值為 1000

    2.4.0 版本中新增

  • train_size (int, 可選) — 如果索引需要訓練步驟,則指定將用於訓練索引的向量數量。
  • faiss_verbose (bool, 預設為 False) — 啟用 Faiss 索引的詳細資訊輸出。
  • dtype (data-type) — 被索引的 numpy 陣列的資料型別。預設為 np.float32

使用 Faiss 新增密集索引以實現快速檢索。預設情況下,索引是在指定列的向量上完成的。如果您想在 GPU 上執行,可以指定 device (device 必須是 GPU 索引)。您可以在此處找到有關 Faiss 的更多資訊

示例

>>> ds = datasets.load_dataset('crime_and_punish', split='train')
>>> ds_with_embeddings = ds.map(lambda example: {'embeddings': embed(example['line']}))
>>> ds_with_embeddings.add_faiss_index(column='embeddings')
>>> # query
>>> scores, retrieved_examples = ds_with_embeddings.get_nearest_examples('embeddings', embed('my new query'), k=10)
>>> # save index
>>> ds_with_embeddings.save_faiss_index('embeddings', 'my_index.faiss')

>>> ds = datasets.load_dataset('crime_and_punish', split='train')
>>> # load index
>>> ds.load_faiss_index('embeddings', 'my_index.faiss')
>>> # query
>>> scores, retrieved_examples = ds.get_nearest_examples('embeddings', embed('my new query'), k=10)

add_faiss_index_from_external_arrays

< >

( external_arrays: <built-in function array> index_name: str device: typing.Optional[int] = None string_factory: typing.Optional[str] = None metric_type: typing.Optional[int] = None custom_index: typing.Optional[ForwardRef('faiss.Index')] = None batch_size: int = 1000 train_size: typing.Optional[int] = None faiss_verbose: bool = False dtype = <class 'numpy.float32'> )

引數

  • external_arrays (np.array) — 如果您想使用庫外部的陣列建立索引,可以設定 external_arrays。它將使用 external_arrays 來建立 Faiss 索引,而不是使用給定 column 中的陣列。
  • index_name (str) — 索引的 index_name/識別符號。這是用於呼叫 get_nearest_examples()search()index_name
  • device (可選 Union[int, List[int]], 可選) — 如果是正整數,表示要使用的 GPU 索引。如果是負整數,表示使用所有 GPU。如果傳入一個正整數列表,則只在這些 GPU 上執行。預設情況下使用 CPU。
  • string_factory (str, 可選) — 傳遞給 Faiss 索引工廠以建立索引。預設的索引類是 IndexFlat
  • metric_type (int, 可選) — 度量型別。例如:faiss.faiss.METRIC_INNER_PRODUCTfaiss.METRIC_L2
  • custom_index (faiss.Index, 可選) — 您已經例項化並根據需要配置的自定義 Faiss 索引。
  • batch_size (int, 可選) — 向 FaissIndex 新增向量時使用的批次大小。預設值為 1000。

    2.4.0 版本新增

  • train_size (int, 可選) — 如果索引需要訓練步驟,指定用於訓練索引的向量數量。
  • faiss_verbose (bool, 預設為 False) — 啟用 Faiss 索引的詳細日誌輸出。
  • dtype (numpy.dtype) — 被索引的 numpy 陣列的資料型別。預設為 np.float32。

使用 Faiss 新增一個密集索引以實現快速檢索。索引是使用 external_arrays 中的向量建立的。如果您想在 GPU 上執行,可以指定 devicedevice 必須是 GPU 索引)。您可以在此處找到有關 Faiss 的更多資訊。

save_faiss_index

< >

( index_name: str file: typing.Union[str, pathlib.PurePath] storage_options: typing.Optional[dict] = None )

引數

  • index_name (str) — 索引的 index_name/識別符號。這是用於呼叫 .get_nearest.search 的 index_name。
  • file (str) — 序列化後的 faiss 索引在磁碟上的路徑或遠端 URI(例如 "s3://my-bucket/index.faiss")。
  • storage_options (dict, 可選) — 傳遞給檔案系統後端的鍵/值對(如果有)。

    2.11.0 版本新增

將 FaissIndex 儲存到磁碟。

load_faiss_index

< >

( index_name: str file: typing.Union[str, pathlib.PurePath] device: typing.Union[int, list[int], NoneType] = None storage_options: typing.Optional[dict] = None )

引數

  • index_name (str) — 索引的 index_name/識別符號。這是用於呼叫 .get_nearest.search 的 index_name。
  • file (str) — 序列化後的 faiss 索引在磁碟上的路徑或遠端 URI(例如 "s3://my-bucket/index.faiss")。
  • device (可選 Union[int, List[int]]) — 如果是正整數,表示要使用的 GPU 索引。如果是負整數,表示使用所有 GPU。如果傳入一個正整數列表,則只在這些 GPU 上執行。預設情況下使用 CPU。
  • storage_options (dict, 可選) — 傳遞給檔案系統後端的鍵/值對(如果有)。

    2.11.0 版本新增

從磁碟載入 FaissIndex。

如果您想進行額外配置,可以透過 .get_index(index_name).faiss_index 訪問 faiss 索引物件,以滿足您的需求。

add_elasticsearch_index

< >

( column: str index_name: typing.Optional[str] = None host: typing.Optional[str] = None port: typing.Optional[int] = None es_client: typing.Optional[ForwardRef('elasticsearch.Elasticsearch')] = None es_index_name: typing.Optional[str] = None es_index_config: typing.Optional[dict] = None )

引數

  • column (str) — 要新增到索引的文件所在的列。
  • index_name (str, 可選) — 索引的 index_name/識別符號。這是用於呼叫 get_nearest_examples()search() 的索引名稱。預設情況下,它對應於 column
  • host (str, 可選, 預設為 localhost) — ElasticSearch 執行的主機。
  • port (str, 可選, 預設為 9200) — ElasticSearch 執行的埠。
  • es_client (elasticsearch.Elasticsearch, 可選) — 當 host 和 port 為 None 時,用於建立索引的 elasticsearch 客戶端。
  • es_index_name (str, 可選) — 用於建立索引的 elasticsearch 索引名稱。
  • es_index_config (dict, 可選) — elasticsearch 索引的配置。預設配置是:

使用 ElasticSearch 新增一個文字索引以實現快速檢索。此操作是原地執行的。

示例

>>> es_client = elasticsearch.Elasticsearch()
>>> ds = datasets.load_dataset('crime_and_punish', split='train')
>>> ds.add_elasticsearch_index(column='line', es_client=es_client, es_index_name="my_es_index")
>>> scores, retrieved_examples = ds.get_nearest_examples('line', 'my new query', k=10)

load_elasticsearch_index

< >

( index_name: str es_index_name: str host: typing.Optional[str] = None port: typing.Optional[int] = None es_client: typing.Optional[ForwardRef('Elasticsearch')] = None es_index_config: typing.Optional[dict] = None )

引數

  • index_name (str) — 索引的 index_name/識別符號。這是用於呼叫 get_nearestsearch 的索引名稱。
  • es_index_name (str) — 要載入的 elasticsearch 索引的名稱。
  • host (str, 可選, 預設為 localhost) — ElasticSearch 執行的主機。
  • port (str, 可選, 預設為 9200) — ElasticSearch 執行的埠。
  • es_client (elasticsearch.Elasticsearch, 可選) — 當 host 和 port 為 None 時,用於建立索引的 elasticsearch 客戶端。
  • es_index_config (dict, 可選) — elasticsearch 索引的配置。預設配置是:

使用 ElasticSearch 載入現有文字索引以實現快速檢索。

list_indexes

< >

( )

列出所有附加索引的 colindex_nameumns/識別符號。

get_index

< >

( index_name: str )

引數

  • index_name (str) — 索引名稱。

列出所有附加索引的 index_name/識別符號。

drop_index

< >

( index_name: str )

引數

  • index_name (str) — 索引的 index_name/識別符號。

刪除指定列的索引。

search

< >

( index_name: str query: typing.Union[str, <built-in function array>] k: int = 10 **kwargs ) (scores, indices)

引數

  • index_name (str) — 索引的名稱/識別符號。
  • query (Union[str, np.ndarray]) — 查詢。如果 index_name 是文字索引,則為字串;如果 index_name 是向量索引,則為 numpy 陣列。
  • k (int) — 要檢索的樣本數量。

返回

(scores, indices)

一個元組 (scores, indices),其中:

  • scores (List[List[float]):從 FAISS(預設為 IndexFlatL2)或 ElasticSearch 中檢索到的樣本的檢索分數
  • indices (List[List[int]]):檢索到的樣本的索引

在資料集中查詢與查詢最接近的樣本索引。

search_batch

< >

( index_name: str queries: typing.Union[list[str], <built-in function array>] k: int = 10 **kwargs ) (total_scores, total_indices)

引數

  • index_name (str) — 索引的 index_name/識別符號。
  • queries (Union[List[str], np.ndarray]) — 查詢。如果 index_name 是文字索引,則為字串列表;如果 index_name 是向量索引,則為 numpy 陣列。
  • k (int) — 每個查詢要檢索的樣本數量。

返回

(total_scores, total_indices)

一個元組 (total_scores, total_indices),其中:

  • total_scores (List[List[float]):每個查詢從 FAISS(預設為 IndexFlatL2)或 ElasticSearch 中檢索到的樣本的檢索分數
  • total_indices (List[List[int]]):每個查詢檢索到的樣本的索引

在資料集中查詢與查詢最接近的樣本索引。

get_nearest_examples

< >

( index_name: str query: typing.Union[str, <built-in function array>] k: int = 10 **kwargs ) (scores, examples)

引數

  • index_name (str) — 索引的 index_name/識別符號。
  • query (Union[str, np.ndarray]) — 查詢。如果 index_name 是文字索引,則為字串;如果 index_name 是向量索引,則為 numpy 陣列。
  • k (int) — 要檢索的樣本數量。

返回

(分數,樣本)

一個 `(scores, examples)` 元組,其中

  • scores (List[float]):檢索到的樣本的分數,來自 FAISS(預設為 `IndexFlatL2`)或 ElasticSearch
  • examples (dict):檢索到的樣本

在資料集中查詢與查詢最接近的樣本。

get_nearest_examples_batch

< >

( index_name: str queries: typing.Union[list[str], <built-in function array>] k: int = 10 **kwargs ) (total_scores, total_examples)

引數

  • index_name (str) — 索引的 `index_name`/識別符號。
  • queries (Union[List[str], np.ndarray]) — 如果 `index_name` 是文字索引,則查詢為字串列表;如果 `index_name` 是向量索引,則查詢為 numpy 陣列。
  • k (int) — 每個查詢要檢索的樣本數量。

返回

(total_scores, total_examples)

一個 `(total_scores, total_examples)` 元組,其中

  • total_scores (List[List[float]):每個查詢從 FAISS(預設為 IndexFlatL2)或 ElasticSearch 中檢索到的樣本的檢索分數
  • total_examples (List[dict]):每個查詢檢索到的樣本

在資料集中查詢與查詢最接近的樣本。

info

< >

( )

包含資料集中所有元資料的 DatasetInfo 物件。

split

< >

( )

對應於命名資料集拆分的 NamedSplit 物件。

builder_name

< >

( )

引用

< >

( )

config_name

< >

( )

dataset_size

< >

( )

description

< >

( )

download_checksums

< >

( )

download_size

< >

( )

features

< >

( )

homepage

< >

( )

許可證

< >

( )

size_in_bytes

< >

( )

supervised_keys

< >

( )

版本

< >

( )

from_csv

< >

( path_or_paths: typing.Union[str, bytes, os.PathLike, list[typing.Union[str, bytes, os.PathLike]]] split: typing.Optional[datasets.splits.NamedSplit] = None features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False num_proc: typing.Optional[int] = None **kwargs )

引數

  • path_or_paths (path-likepath-like 列表) — CSV 檔案的路徑。
  • split (NamedSplit, 可選) — 要分配給資料集的拆分名稱。
  • features (Features, 可選) — 資料集特徵。
  • cache_dir (str, 可選, 預設為 "~/.cache/huggingface/datasets") — 快取資料的目錄。
  • keep_in_memory (bool, 預設為 False) — 是否將資料複製到記憶體中。
  • num_proc (int, 可選, 預設為 None) — 在本地下載和生成資料集時使用的程序數。如果資料集由多個檔案組成,此引數會很有幫助。預設停用多程序。

    2.8.0 版本新增

  • **kwargs (附加關鍵字引數) — 傳遞給 `pandas.read_csv` 的關鍵字引數。

從 CSV 檔案建立資料集。

示例

>>> ds = Dataset.from_csv('path/to/dataset.csv')

from_json

< >

( path_or_paths: typing.Union[str, bytes, os.PathLike, list[typing.Union[str, bytes, os.PathLike]]] split: typing.Optional[datasets.splits.NamedSplit] = None features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False field: typing.Optional[str] = None num_proc: typing.Optional[int] = None **kwargs )

引數

  • path_or_paths (path-likepath-like 列表) — JSON 或 JSON Lines 檔案的路徑。
  • split (NamedSplit, 可選) — 要分配給資料集的拆分名稱。
  • features (Features, 可選) — 資料集特徵。
  • cache_dir (str, 可選, 預設為 "~/.cache/huggingface/datasets") — 快取資料的目錄。
  • keep_in_memory (bool, 預設為 False) — 是否將資料複製到記憶體中。
  • field (str, 可選) — 包含資料集的 JSON 檔案的欄位名。
  • num_proc (int, 可選, 預設為 None) — 在本地下載和生成資料集時使用的程序數。如果資料集由多個檔案組成,此引數會很有幫助。預設停用多程序。

    2.8.0 版本新增

  • **kwargs (附加關鍵字引數) — 傳遞給 `JsonConfig` 的關鍵字引數。

從 JSON 或 JSON Lines 檔案建立資料集。

示例

>>> ds = Dataset.from_json('path/to/dataset.json')

from_parquet

< >

( path_or_paths: typing.Union[str, bytes, os.PathLike, list[typing.Union[str, bytes, os.PathLike]]] split: typing.Optional[datasets.splits.NamedSplit] = None features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False columns: typing.Optional[list[str]] = None num_proc: typing.Optional[int] = None **kwargs )

引數

  • path_or_paths (path-likepath-like 列表) — Parquet 檔案的路徑。
  • split (NamedSplit, 可選) — 要分配給資料集的拆分名稱。
  • features (Features, 可選) — 資料集特徵。
  • cache_dir (str, 可選, 預設為 "~/.cache/huggingface/datasets") — 快取資料的目錄。
  • keep_in_memory (bool, 預設為 False) — 是否將資料複製到記憶體中。
  • columns (List[str], 可選) — 如果不為 `None`,則僅從檔案中讀取這些列。列名可以是巢狀欄位的字首,例如,“a”將選擇“a.b”、“a.c”和“a.d.e”。
  • num_proc (int, 可選, 預設為 None) — 在本地下載和生成資料集時使用的程序數。如果資料集由多個檔案組成,此引數會很有幫助。預設停用多程序。

    2.8.0 版本新增

  • **kwargs (附加關鍵字引數) — 傳遞給 `ParquetConfig` 的關鍵字引數。

從 Parquet 檔案建立資料集。

示例

>>> ds = Dataset.from_parquet('path/to/dataset.parquet')

from_text

< >

( path_or_paths: typing.Union[str, bytes, os.PathLike, list[typing.Union[str, bytes, os.PathLike]]] split: typing.Optional[datasets.splits.NamedSplit] = None features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False num_proc: typing.Optional[int] = None **kwargs )

引數

  • path_or_paths (path-likepath-like 列表) — 文字檔案的路徑。
  • split (NamedSplit, 可選) — 要分配給資料集的拆分名稱。
  • features (Features, 可選) — 資料集特徵。
  • cache_dir (str, 可選, 預設為 "~/.cache/huggingface/datasets") — 快取資料的目錄。
  • keep_in_memory (bool, 預設為 False) — 是否將資料複製到記憶體中。
  • num_proc (int, 可選, 預設為 None) — 在本地下載和生成資料集時使用的程序數。如果資料集由多個檔案組成,此引數會很有幫助。預設停用多程序。

    2.8.0 版本新增

  • **kwargs (附加關鍵字引數) — 傳遞給 `TextConfig` 的關鍵字引數。

從文字檔案建立資料集。

示例

>>> ds = Dataset.from_text('path/to/dataset.txt')

from_sql

< >

( sql: typing.Union[str, ForwardRef('sqlalchemy.sql.Selectable')] con: typing.Union[str, ForwardRef('sqlalchemy.engine.Connection'), ForwardRef('sqlalchemy.engine.Engine'), ForwardRef('sqlite3.Connection')] features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False **kwargs )

引數

  • sql (strsqlalchemy.sql.Selectable) — 要執行的 SQL 查詢或表名。
  • con (strsqlite3.Connectionsqlalchemy.engine.Connectionsqlalchemy.engine.Connection) — 用於例項化資料庫連線的 URI 字串,或 SQLite3/SQLAlchemy 連線物件。
  • features (Features, 可選) — 資料集特徵。
  • cache_dir (str, 可選, 預設為 "~/.cache/huggingface/datasets") — 快取資料的目錄。
  • keep_in_memory (bool, 預設為 False) — 是否將資料複製到記憶體中。
  • **kwargs (附加關鍵字引數) — 傳遞給 SqlConfig 的關鍵字引數。

從 SQL 查詢或資料庫表建立資料集。

示例

>>> # 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
>>> from sqlalchemy import select, text
>>> stmt = select([text("sentence")]).select_from(text("test_data"))
>>> ds = Dataset.from_sql(stmt, "postgres:///db_name")

只有當 con 被指定為 URI 字串時,返回的資料集才能被快取。

align_labels_with_mapping

< >

( label2id: dict label_column: str )

引數

  • label2id (dict) — 用於與資料集對齊的標籤名到 ID 的對映。
  • label_column (str) — 要對齊的標籤列的列名。

將資料集的標籤 ID 和標籤名對映與輸入的 label2id 對映對齊。當您希望確保模型的預測標籤與資料集對齊時,這非常有用。對齊是使用小寫標籤名完成的。

示例

>>> # dataset with mapping {'entailment': 0, 'neutral': 1, 'contradiction': 2}
>>> ds = load_dataset("nyu-mll/glue", "mnli", split="train")
>>> # mapping to align with
>>> label2id = {'CONTRADICTION': 0, 'NEUTRAL': 1, 'ENTAILMENT': 2}
>>> ds_aligned = ds.align_labels_with_mapping(label2id, "label")

datasets.concatenate_datasets

< >

( dsets: list info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None axis: int = 0 )

引數

  • dsets (List[datasets.Dataset]) — 要連線的資料集列表。
  • info (DatasetInfo, 可選) — 資料集資訊,如描述、引用等。
  • split (NamedSplit, 可選) — 資料集拆分的名稱。
  • axis ({0, 1}, 預設為 0) — 連線的軸,其中 0 表示按行連線(垂直),1 表示按列連線(水平)。

    在 1.6.0 版本中新增

將具有相同模式的 Dataset 列表轉換為單個 Dataset

示例

>>> ds3 = concatenate_datasets([ds1, ds2])

datasets.interleave_datasets

< >

( datasets: list probabilities: typing.Optional[list[float]] = None seed: typing.Optional[int] = None info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None stopping_strategy: typing.Literal['first_exhausted', 'all_exhausted'] = 'first_exhausted' ) DatasetIterableDataset

引數

  • datasets (List[Dataset]List[IterableDataset]) — 要交錯的資料集列表。
  • probabilities (List[float], 可選, 預設為 None) — 如果指定,新資料集將根據這些機率從一個源中取樣構建。
  • seed (int, 可選, 預設為 None) — 用於為每個示例選擇源的隨機種子。
  • info (DatasetInfo, 可選) — 資料集資訊,如描述、引用等。

    在 2.4.0 版本中新增

  • split (NamedSplit, 可選) — 資料集拆分的名稱。

    在 2.4.0 版本中新增

  • stopping_strategy (str, 預設為 first_exhausted) — 目前提供兩種策略,first_exhaustedall_exhausted。預設情況下,first_exhausted 是一種欠取樣策略,即一旦某個資料集的樣本耗盡,資料集的構建就停止。如果策略是 all_exhausted,我們使用過取樣策略,即一旦每個資料集的每個樣本都至少被新增過一次,資料集的構建就停止。請注意,如果策略是 all_exhausted,交錯後的資料集大小可能會變得非常大:
    • 沒有機率時,結果資料集將有 max_length_datasets*nb_dataset 個樣本。
    • 有給定機率時,如果某些資料集的訪問機率非常低,結果資料集的樣本會更多。

返回

DatasetIterableDataset

返回型別取決於輸入的 datasets 引數。如果輸入是 Dataset 列表,則返回 Dataset;如果輸入是 IterableDataset 列表,則返回 IterableDataset

將多個數據集(源)交錯成單個數據集。新資料集透過在源之間交替獲取示例來構建。

您可以在 Dataset 物件列表上或在 IterableDataset 物件列表上使用此函式。

  • 如果 probabilitiesNone(預設),新資料集透過在每個源之間迴圈獲取示例來構建。
  • 如果 probabilities 不為 None,新資料集透過根據提供的機率從隨機源中獲取示例來構建。

當其中一個源資料集耗盡示例時,結果資料集結束,除非 oversamplingTrue,在這種情況下,當所有資料集都至少耗盡一次示例時,結果資料集才結束。

可迭代資料集註意事項

在分散式設定或 PyTorch DataLoader 工作程序中,停止策略是按程序應用的。因此,在分片的可迭代資料集上使用“first_exhausted”策略可能會生成更少的總樣本(每個子資料集每個工作程序最多缺少 1 個樣本)。

示例

對於常規資料集(對映樣式)

>>> from datasets import Dataset, interleave_datasets
>>> d1 = Dataset.from_dict({"a": [0, 1, 2]})
>>> d2 = Dataset.from_dict({"a": [10, 11, 12]})
>>> d3 = Dataset.from_dict({"a": [20, 21, 22]})
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42, stopping_strategy="all_exhausted")
>>> dataset["a"]
[10, 0, 11, 1, 2, 20, 12, 10, 0, 1, 2, 21, 0, 11, 1, 2, 0, 1, 12, 2, 10, 0, 22]
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42)
>>> dataset["a"]
[10, 0, 11, 1, 2]
>>> dataset = interleave_datasets([d1, d2, d3])
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22]
>>> dataset = interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted")
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22]
>>> d1 = Dataset.from_dict({"a": [0, 1, 2]})
>>> d2 = Dataset.from_dict({"a": [10, 11, 12, 13]})
>>> d3 = Dataset.from_dict({"a": [20, 21, 22, 23, 24]})
>>> dataset = interleave_datasets([d1, d2, d3])
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22]
>>> dataset = interleave_datasets([d1, d2, d3], stopping_strategy="all_exhausted")
>>> dataset["a"]
[0, 10, 20, 1, 11, 21, 2, 12, 22, 0, 13, 23, 1, 10, 24]
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42)
>>> dataset["a"]
[10, 0, 11, 1, 2]
>>> dataset = interleave_datasets([d1, d2, d3], probabilities=[0.7, 0.2, 0.1], seed=42, stopping_strategy="all_exhausted")
>>> dataset["a"]
[10, 0, 11, 1, 2, 20, 12, 13, ..., 0, 1, 2, 0, 24]
For datasets in streaming mode (iterable):

>>> from datasets import interleave_datasets
>>> d1 = load_dataset('allenai/c4', 'es', split='train', streaming=True)
>>> d2 = load_dataset('allenai/c4', 'fr', split='train', streaming=True)
>>> dataset = interleave_datasets([d1, d2])
>>> iterator = iter(dataset)
>>> next(iterator)
{'text': 'Comprar Zapatillas para niña en chancla con goma por...'}
>>> next(iterator)
{'text': 'Le sacre de philippe ier, 23 mai 1059 - Compte Rendu...'

datasets.distributed.split_dataset_by_node

< >

( dataset: ~DatasetType rank: int world_size: int ) DatasetIterableDataset

引數

  • dataset (DatasetIterableDataset) — 按節點拆分的資料集。
  • rank (int) — 當前節點的排名。
  • world_size (int) — 節點總數。

返回

DatasetIterableDataset

在排名為 rank 的節點上使用的資料集。

在一個大小為 world_size 的節點池中,為排名為 rank 的節點拆分一個數據集。

對於對映樣式的資料集

每個節點被分配一個數據塊,例如,排名 0 的節點被給予資料集的第一個資料塊。為了最大化資料載入吞吐量,如果可能,資料塊由磁碟上的連續資料組成。

對於可迭代的資料集

如果資料集的分片數是 world_size 的因子(即 dataset.num_shards % world_size == 0),那麼分片將在節點之間均勻分配,這是最最佳化的。否則,每個節點從 world_size 個示例中保留 1 個示例,跳過其他示例。

datasets.enable_caching

< >

( )

在對資料集應用轉換時,資料儲存在快取檔案中。快取機制允許在已計算過的情況下重新載入現有的快取檔案。

重新載入資料集是可能的,因為快取檔案是使用資料集指紋命名的,該指紋在每次轉換後都會更新。

如果停用,該庫在對資料集應用轉換時將不再重新載入快取的資料集檔案。更確切地說,如果停用了快取:

  • 快取檔案總是被重新建立
  • 快取檔案被寫入一個臨時目錄,該目錄在會話關閉時被刪除
  • 快取檔案使用隨機雜湊命名,而不是資料集指紋
  • 使用 save_to_disk() 來儲存轉換後的資料集,否則它將在會話關閉時被刪除
  • 快取不影響 load_dataset()。如果你想從頭開始重新生成一個數據集,你應該在 load_dataset() 中使用 download_mode 引數。

datasets.disable_caching

< >

( )

在對資料集應用轉換時,資料儲存在快取檔案中。快取機制允許在已計算過的情況下重新載入現有的快取檔案。

重新載入資料集是可能的,因為快取檔案是使用資料集指紋命名的,該指紋在每次轉換後都會更新。

如果停用,該庫在對資料集應用轉換時將不再重新載入快取的資料集檔案。更確切地說,如果停用了快取:

  • 快取檔案總是被重新建立
  • 快取檔案被寫入一個臨時目錄,該目錄在會話關閉時被刪除
  • 快取檔案使用隨機雜湊命名,而不是資料集指紋
  • 使用 save_to_disk() 來儲存轉換後的資料集,否則它將在會話關閉時被刪除
  • 快取不影響 load_dataset()。如果你想從頭開始重新生成一個數據集,你應該在 load_dataset() 中使用 download_mode 引數。

datasets.is_caching_enabled

< >

( )

在對資料集應用轉換時,資料儲存在快取檔案中。快取機制允許在已計算過的情況下重新載入現有的快取檔案。

重新載入資料集是可能的,因為快取檔案是使用資料集指紋命名的,該指紋在每次轉換後都會更新。

如果停用,該庫在對資料集應用轉換時將不再重新載入快取的資料集檔案。更確切地說,如果停用了快取:

  • 快取檔案總是被重新建立
  • 快取檔案被寫入一個臨時目錄,該目錄在會話關閉時被刪除
  • 快取檔案使用隨機雜湊命名,而不是資料集指紋
  • 使用 save_to_disk() 來儲存轉換後的資料集,否則它將在會話關閉時被刪除
  • 快取不影響 load_dataset()。如果你想從頭開始重新生成一個數據集,你應該在 load_dataset() 中使用 download_mode 引數。

class datasets.Column

< >

( source: typing.Union[ForwardRef('Dataset'), ForwardRef('Column')] column_name: str )

用於 Dataset 特定列的可迭代物件。

示例

迭代資料集“text”列中的文字

for text in dataset["text"]:
    ...

它也適用於巢狀列

for source in dataset["metadata"]["source"]:
    ...

DatasetDict

以拆分名稱(例如‘train’、‘test’)為鍵,Dataset 物件為值的字典。它還具有資料集轉換方法,如 map 或 filter,可一次處理所有拆分。

class datasets.DatasetDict

< >

( )

一個具有資料集轉換方法(map、filter 等)的字典(dict of str: datasets.Dataset)。

data

< >

( )

支援每個拆分的 Apache Arrow 表。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.data

cache_files

< >

( )

包含支援每個拆分的 Apache Arrow 表的快取檔案。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.cache_files
{'test': [{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-test.arrow'}],
 'train': [{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-train.arrow'}],
 'validation': [{'filename': '/root/.cache/huggingface/datasets/rotten_tomatoes_movie_review/default/1.0.0/40d411e45a6ce3484deed7cc15b82a53dad9a72aafd9f86f8f227134bec5ca46/rotten_tomatoes_movie_review-validation.arrow'}]}

num_columns

< >

( )

資料集中每個拆分的列數。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.num_columns
{'test': 2, 'train': 2, 'validation': 2}

num_rows

< >

( )

資料集中每個拆分的行數。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.num_rows
{'test': 1066, 'train': 8530, 'validation': 1066}

column_names

< >

( )

資料集中每個拆分的列名。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.column_names
{'test': ['text', 'label'],
 'train': ['text', 'label'],
 'validation': ['text', 'label']}

shape

< >

( )

資料集中每個拆分的形狀(行數,列數)。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.shape
{'test': (1066, 2), 'train': (8530, 2), 'validation': (1066, 2)}

unique

< >

( column: str ) Dict[str, list]

引數

  • column (str) — 列名(使用 column_names 列出所有列名)

返回

Dict[str, list]

給定列中唯一元素的字典。

返回每個拆分中某列的唯一元素列表。

此功能在底層後端實現,因此速度非常快。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.unique("label")
{'test': [1, 0], 'train': [1, 0], 'validation': [1, 0]}

cleanup_cache_files

< >

( )

清理資料集快取目錄中的所有快取檔案,但當前正在使用的快取檔案(如果有的話)除外。執行此命令時要小心,確保沒有其他程序正在使用其他快取檔案。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.cleanup_cache_files()
{'test': 0, 'train': 0, 'validation': 0}

map

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False with_rank: bool = False with_split: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 drop_last_batch: bool = False remove_columns: typing.Union[str, list[str], NoneType] = None keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None cache_file_names: typing.Optional[dict[str, typing.Optional[str]]] = None writer_batch_size: typing.Optional[int] = 1000 features: typing.Optional[datasets.features.features.Features] = None disable_nullable: bool = False fn_kwargs: typing.Optional[dict] = None num_proc: typing.Optional[int] = None desc: typing.Optional[str] = None try_original_type: typing.Optional[bool] = True )

引數

  • function (callable) — 具有以下簽名之一:

    • function(example: Dict[str, Any]) -> Dict[str, Any] 如果 batched=Falsewith_indices=False
    • function(example: Dict[str, Any], indices: int) -> Dict[str, Any] 如果 batched=Falsewith_indices=True
    • function(batch: Dict[str, list]) -> Dict[str, list] 如果 batched=Truewith_indices=False
    • function(batch: Dict[str, list], indices: list[int]) -> Dict[str, list] 如果 batched=Truewith_indices=True

    對於高階用法,該函式還可以返回一個 pyarrow.Table。如果函式是非同步的,那麼 map 將並行執行您的函式。此外,如果您的函式不返回任何內容(None),那麼 map 將執行您的函式並返回未更改的資料集。如果沒有提供函式,則預設為恆等函式:lambda x: x

  • with_indices (bool, 預設為 False) — 向 function 提供示例索引。請注意,在這種情況下,function 的簽名應為 def function(example, idx): ...
  • with_rank (bool, 預設為 False) — 向 function 提供程序排名。請注意,在這種情況下,function 的簽名應為 def function(example[, idx], rank): ...
  • with_split (bool, 預設為 False) — 向 function 提供程序拆分。請注意,在這種情況下,function 的簽名應為 def function(example[, idx], split): ...
  • input_columns ([Union[str, list[str]]], 可選, 預設為 None) — 作為位置引數傳遞給 function 的列。如果為 None,則將一個對映到所有格式化列的字典作為單個引數傳遞。
  • batched (bool, 預設為 False) — 向 function 提供批處理的示例。
  • batch_size (int, 可選, 預設為 1000) — 如果 batched=True,提供給 function 的每個批處理的示例數,如果 batch_size <= 0batch_size == None,則將整個資料集作為單個批處理提供給 function
  • drop_last_batch (bool, 預設為 False) — 是否應丟棄小於 batch_size 的最後一個批次,而不是由函式處理。
  • remove_columns ([Union[str, list[str]]], 可選, 預設為 None) — 在對映過程中刪除選定的列。列將在使用 function 的輸出更新示例之前被刪除,即如果 function 新增的列名在 remove_columns 中,這些列將被保留。
  • keep_in_memory (bool, 預設為 False) — 將資料集保留在記憶體中,而不是寫入快取檔案。
  • load_from_cache_file (Optional[bool], 預設為 True,如果快取已啟用) — 如果可以識別出儲存了當前 function 計算結果的快取檔案,則直接使用它而不是重新計算。
  • cache_file_names ([Dict[str, str]], 可選, 預設為 None) — 提供快取檔案的路徑名稱。它用於儲存計算結果,而不是使用自動生成的快取檔名。您必須為資料集字典中的每個資料集提供一個 cache_file_name
  • writer_batch_size (int, 預設為 1000) — 快取檔案寫入器每次寫入操作的行數。此值是在處理過程中的記憶體使用和處理速度之間的一個良好權衡。較高的值會使處理過程中的查詢次數減少,較低的值在執行 map 時消耗較少的臨時記憶體。
  • features ([datasets.Features], 可選, 預設為 None) — 使用特定的 Features 來儲存快取檔案,而不是使用自動生成的一個。
  • disable_nullable (bool, 預設為 False) — 禁止表中的空值。
  • fn_kwargs (Dict, 可選, 預設為 None) — 要傳遞給 function 的關鍵字引數。
  • num_proc (int, 可選, 預設為 None) — 用於多程序處理的程序數。預設情況下不使用多程序。
  • desc (str, 可選, 預設為 None) — 在對映示例時,與進度條一同顯示的、有意義的描述。
  • try_original_type (Optional[bool], 預設為 True) — 嘗試保留原始列的型別(例如 int32 -> int32)。如果你希望總是推斷新型別,請設定為 False。

將一個函式應用於表中的所有示例(單個或批次),並更新表。如果你的函式返回一個已存在的列,那麼它將被覆蓋。該轉換將應用於資料集字典中的所有資料集。

您可以使用 `batched` 引數指定函式是否應批次處理。

  • 如果 `batched` 為 `False`,則函式接收 1 個示例作為輸入,並應返回 1 個示例。一個示例是一個字典,例如 `{"text": "Hello there !"}`。
  • 如果 `batched` 為 `True` 且 `batch_size` 為 1,則函式接收一個包含 1 個示例的批次作為輸入,並可以返回一個包含 1 個或多個示例的批次。一個批次是一個字典,例如,一個包含 1 個示例的批次是 `{"text": ["Hello there !"]}`。
  • 如果 `batched` 為 `True` 且 `batch_size` 為 `n > 1`,則函式接收一個包含 `n` 個示例的批次作為輸入,並可以返回一個包含 `n` 個示例或任意數量示例的批次。請注意,最後一個批次可能少於 `n` 個示例。一個批次是一個字典,例如,一個包含 `n` 個示例的批次是 `{"text": ["Hello there !"] * n}`。

如果函式是非同步的,那麼 `map` 將並行執行您的函式,最多可同時進行一千次呼叫。如果您想設定可以同時執行的最大運算元,建議在您的函式中使用 `asyncio.Semaphore`。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> ds["train"][0:3]["text"]
['Review: the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .',
 'Review: 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 .',
 'Review: effective but too-tepid biopic']

# 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)

過濾器

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False with_rank: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None cache_file_names: typing.Optional[dict[str, typing.Optional[str]]] = None writer_batch_size: typing.Optional[int] = 1000 fn_kwargs: typing.Optional[dict] = None num_proc: typing.Optional[int] = None desc: typing.Optional[str] = None )

引數

  • function (Callable) — 具有以下簽名之一的可呼叫物件:

    • batched=Falsewith_indices=Falsewith_rank=False 時:function(example: Dict[str, Any]) -> bool
    • batched=Falsewith_indices=True 和/或 with_rank=True 時(每項一個額外引數):function(example: Dict[str, Any], *extra_args) -> bool
    • batched=Truewith_indices=Falsewith_rank=False 時:function(batch: Dict[str, list]) -> list[bool]
    • batched=Truewith_indices=True 和/或 with_rank=True 時(每項一個額外引數):function(batch: Dict[str, list], *extra_args) -> list[bool]

    如果未提供函式,則預設為始終返回 True 的函式:lambda x: True

  • with_indices (bool, 預設為 False) — 向 function 提供示例索引。請注意,在這種情況下,function 的簽名應為 def function(example, idx[, rank]): ...
  • with_rank (bool, 預設為 False) — 向 function 提供程序等級。請注意,在這種情況下,function 的簽名應為 def function(example[, idx], rank): ...
  • input_columns ([Union[str, list[str]]], 可選, 預設為 None) — 要作為位置引數傳遞給 function 的列。如果為 None,則將一個對映到所有格式化列的字典作為單個引數傳遞。
  • batched (bool, 預設為 False) — 向 function 提供一批示例。
  • batch_size (int, 可選, 預設為 1000) — 如果 batched=True,提供給 function 的每批示例數。如果 batch_size <= 0batch_size == None,則將整個資料集作為單個批次提供給 function
  • keep_in_memory (bool, 預設為 False) — 將資料集保留在記憶體中,而不是寫入快取檔案。
  • load_from_cache_file (Optional[bool], 預設為 True,如果快取已啟用) — 如果可以識別出儲存了當前 function 計算結果的快取檔案,則直接使用它而不是重新計算。
  • cache_file_names ([Dict[str, str]], 可選, 預設為 None) — 提供快取檔案的路徑名稱。它用於儲存計算結果,而不是使用自動生成的快取檔名。您必須為資料集字典中的每個資料集提供一個 cache_file_name
  • writer_batch_size (int, 預設為 1000) — 快取檔案寫入器每次寫入操作的行數。此值是在處理過程中的記憶體使用和處理速度之間的一個良好權衡。較高的值會使處理過程中的查詢次數減少,較低的值在執行 map 時消耗較少的臨時記憶體。
  • fn_kwargs (Dict, 可選, 預設為 None) — 要傳遞給 function 的關鍵字引數。
  • num_proc (int, 可選, 預設為 None) — 用於多程序處理的程序數。預設情況下不使用多程序。
  • desc (str, 可選, 預設為 None) — 在過濾示例時,與進度條一同顯示的、有意義的描述。

對錶中的所有元素批次應用一個過濾函式,並更新表,使得資料集只包含符合過濾函式的示例。該轉換將應用於資料集字典中的所有資料集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.filter(lambda x: x["label"] == 1)
DatasetDict({
    train: Dataset({
        features: ['text', 'label'],
        num_rows: 4265
    })
    validation: Dataset({
        features: ['text', 'label'],
        num_rows: 533
    })
    test: Dataset({
        features: ['text', 'label'],
        num_rows: 533
    })
})

sort

< >

( column_names: typing.Union[str, collections.abc.Sequence[str]] reverse: typing.Union[bool, collections.abc.Sequence[bool]] = False null_placement: str = 'at_end' keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None indices_cache_file_names: typing.Optional[dict[str, typing.Optional[str]]] = None writer_batch_size: typing.Optional[int] = 1000 )

引數

  • column_names (Union[str, Sequence[str]]) — 用於排序的列名。
  • reverse (Union[bool, Sequence[bool]], 預設為 False) — 如果為 True,則按降序排序而不是升序。如果提供單個布林值,該值將應用於所有列名的排序。否則,必須提供一個與 column_names 長度和順序相同的布林值列表。
  • null_placement (str, 預設為 at_end) — 如果是 at_startfirst,則將 None 值放在開頭;如果是 at_endlast,則放在末尾。
  • keep_in_memory (bool, 預設為 False) — 將排序後的索引保留在記憶體中,而不是寫入快取檔案。
  • load_from_cache_file (Optional[bool], 預設為 True,如果快取已啟用) — 如果可以識別出儲存了排序索引的快取檔案,則直接使用它而不是重新計算。
  • indices_cache_file_names ([Dict[str, str]], 可選, 預設為 None) — 提供快取檔案的路徑名稱。它用於儲存索引對映,而不是使用自動生成的快取檔名。您必須為資料集字典中的每個資料集提供一個 cache_file_name
  • writer_batch_size (int, 預設為 1000) — 快取檔案寫入器每次寫入操作的行數。較高的值會產生較小的快取檔案,較低的值會消耗較少的臨時記憶體。

根據單個或多個列建立一個新的已排序的資料集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset('cornell-movie-review-data/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]
>>> another_sorted_ds = ds.sort(['label', 'text'], reverse=[True, False])
>>> another_sorted_ds['train']['label'][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

shuffle

< >

( seeds: typing.Union[int, dict[str, typing.Optional[int]], NoneType] = None seed: typing.Optional[int] = None generators: typing.Optional[dict[str, numpy.random._generator.Generator]] = None keep_in_memory: bool = False load_from_cache_file: typing.Optional[bool] = None indices_cache_file_names: typing.Optional[dict[str, typing.Optional[str]]] = None writer_batch_size: typing.Optional[int] = 1000 )

引數

  • seeds (Dict[str, int]int, 可選) — 如果 generator=None,用於初始化預設 BitGenerator 的種子。如果為 None,則會從作業系統中獲取全新的、不可預測的熵。如果傳遞一個 intarray_like[ints],它將被傳遞給 SeedSequence 以派生初始 BitGenerator 狀態。您可以在資料集字典中為每個資料集提供一個 seed
  • seed (int, 可選) — 如果 generator=None,用於初始化預設 BitGenerator 的種子。是 seeds 的別名(如果兩者都提供,將引發 ValueError)。
  • generators (Dict[str, *可選*, np.random.Generator]) — 用於計算資料集行排列的 Numpy 隨機生成器。如果 generator=None(預設),則使用 np.random.default_rng(NumPy 的預設 BitGenerator (PCG64))。您必須為資料集字典中的每個資料集提供一個 generator
  • keep_in_memory (bool, 預設為 False) — 將資料集保留在記憶體中,而不是寫入快取檔案。
  • load_from_cache_file (Optional[bool], 預設為 True,如果快取已啟用) — 如果可以識別出儲存了當前 function 計算結果的快取檔案,則直接使用它而不是重新計算。
  • indices_cache_file_names (Dict[str, str], 可選) — 提供快取檔案的路徑名稱。它用於儲存索引對映,而不是使用自動生成的快取檔名。您必須為資料集字典中的每個資料集提供一個 cache_file_name
  • writer_batch_size (int, 預設為 1000) — 快取檔案寫入器每次寫入操作的行數。此值是在處理過程中的記憶體使用和處理速度之間的一個良好權衡。較高的值會使處理過程中的查詢次數減少,較低的值在執行 map 時消耗較少的臨時記憶體。

建立一個新的資料集,其中的行被打亂。

該轉換將應用於資料集字典中的所有資料集。

目前,打亂操作使用 numpy 隨機生成器。您可以提供一個 NumPy BitGenerator 來使用,或者提供一個種子來初始化 NumPy 的預設隨機生成器(PCG64)。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds["train"]["label"][:10]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

# set a seed
>>> shuffled_ds = ds.shuffle(seed=42)
>>> shuffled_ds["train"]["label"][:10]
[0, 1, 0, 1, 0, 0, 0, 0, 0, 0]

set_format

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

引數

  • type (str, 可選) — 輸出型別,可選自 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars']None 表示 __getitem__ 返回 Python 物件(預設)。
  • columns (list[str], 可選) — 輸出中要格式化的列。None 表示 __getitem__ 返回所有列(預設)。
  • output_all_columns (bool, 預設為 False) — 在輸出中同時保留未格式化的列(作為 Python 物件),
  • **format_kwargs (附加關鍵字引數) — 傳遞給轉換函式的關鍵字引數,如 np.arraytorch.tensortensorflow.ragged.constant

設定 __getitem__ 的返回格式(型別和列)。該格式將為資料集字典中的每個資料集設定。

可以在呼叫 set_format 後呼叫 map。由於 map 可能會新增新列,格式化列的列表會隨之更新。在這種情況下,如果你對資料集應用 map 來新增一個新列,那麼這個新列將被格式化。

新的格式化列 = (所有列 - 先前未格式化的列)

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x["text"], truncation=True, padding=True), batched=True)
>>> ds.set_format(type="numpy", columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds["train"].format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'numpy'}

reset_format

< >

( )

__getitem__ 的返回格式重置為 Python 物件和所有列。該轉換將應用於資料集字典中的所有資料集。

self.set_format() 相同

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x["text"], truncation=True, padding=True), batched=True)
>>> ds.set_format(type="numpy", columns=['input_ids', 'token_type_ids', 'attention_mask', 'label'])
>>> ds["train"].format
{'columns': ['input_ids', 'token_type_ids', 'attention_mask', 'label'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'numpy'}
>>> ds.reset_format()
>>> ds["train"].format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}

formatted_as

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

引數

  • type (str, 可選) — 輸出型別,可選自 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars']None 表示 __getitem__ 返回 Python 物件(預設)。
  • columns (list[str], 可選) — 輸出中要格式化的列。None 表示 __getitem__ 返回所有列(預設)。
  • output_all_columns (bool, 預設為 False) — 在輸出中同時保留未格式化的列(作為 Python 物件)。
  • **format_kwargs (附加關鍵字引數) — 傳遞給轉換函式的關鍵字引數,如 np.arraytorch.tensortensorflow.ragged.constant

with 語句中使用。設定 __getitem__ 的返回格式(型別和列)。該轉換將應用於資料集字典中的所有資料集。

with_format

< >

( type: typing.Optional[str] = None columns: typing.Optional[list] = None output_all_columns: bool = False **format_kwargs )

引數

  • type (str, 可選) — 輸出型別,可選自 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars']None 表示 __getitem__ 返回 Python 物件(預設)。
  • columns (list[str], 可選) — 輸出中要格式化的列。None 表示 __getitem__ 返回所有列(預設)。
  • output_all_columns (bool, 預設為 False) — 在輸出中同時保留未格式化的列(作為 Python 物件)。
  • **format_kwargs (附加關鍵字引數) — 傳遞給轉換函式的關鍵字引數,如 np.arraytorch.tensortensorflow.ragged.constant

設定 __getitem__ 的返回格式(型別和列)。資料格式化是即時應用的。格式 type(例如 “numpy”)用於在使用 __getitem__ 時格式化批次。該格式將為資料集字典中的每個資料集設定。

也可以使用 with_transform() 使用自定義轉換進行格式化。

set_format() 不同,with_format 返回一個新的 DatasetDict 物件,其中包含新的 Dataset 物件。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds["train"].format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': None}
>>> ds = ds.with_format("torch")
>>> ds["train"].format
{'columns': ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
 'format_kwargs': {},
 'output_all_columns': False,
 'type': 'torch'}
>>> ds["train"][0]
{'text': 'compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .',
 '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,     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,     0,     0,
            0,     0,     0,     0]),
 '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, 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]),
 '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,
        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])}

with_transform

< >

( transform: typing.Optional[typing.Callable] columns: typing.Optional[list] = None output_all_columns: bool = False )

引數

  • transform (Callable, 可選) — 使用者定義的格式化轉換,替換由 set_format() 定義的格式。格式化函式是一個可呼叫函式,它接受一個批次(作為字典)作為輸入並返回一個批次。此函式在 __getitem__ 返回物件之前立即應用。
  • columns (list[str], 可選) — 輸出中要格式化的列。如果指定,則轉換的輸入批次僅包含這些列。
  • output_all_columns (bool, 預設為 False) — 在輸出中也保留未格式化的列(作為 python 物件)。如果設定為 True,則其他未格式化的列將與轉換的輸出一起保留。

使用此轉換設定 __getitem__ 的返回格式。當呼叫 __getitem__ 時,轉換會即時應用於批次。此轉換為資料集字典中的每個資料集設定。

set_format() 一樣,這可以使用 reset_format() 重置。

set_transform() 相反,with_transform 返回一個新的 DatasetDict 物件,其中包含新的 Dataset 物件。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> def encode(example):
...     return tokenizer(example['text'], truncation=True, padding=True, return_tensors="pt")
>>> ds = ds.with_transform(encode)
>>> ds["train"][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, 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]),
 'input_ids': tensor([  101,  1103,  2067,  1110, 17348,  1106,  1129,  1103,  6880,  1432,
        112,   188,  1207,   107, 14255,  1389,   107,  1105,  1115,  1119,
        112,   188,  1280,  1106,  1294,   170, 24194,  1256,  3407,  1190,
        170, 11791,  5253,   188,  1732,  7200, 10947, 12606,  2895,   117,
        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, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0])}

flatten

< >

( max_depth = 16 )

展平每個資料分割的 Apache Arrow 表(巢狀特徵被展平)。每個具有結構型別的列都被展平為每個結構欄位一列。其他列保持不變。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("rajpurkar/squad")
>>> ds["train"].features
{'id': Value('string'),
 'title': Value('string'),
 'context': Value('string'),
 'question': Value('string'),
 'answers.text': List(Value('string')),
 'answers.answer_start': List(Value('int32'))}
>>> ds.flatten()
DatasetDict({
    train: Dataset({
        features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'],
        num_rows: 87599
    })
    validation: Dataset({
        features: ['id', 'title', 'context', 'question', 'answers.text', 'answers.answer_start'],
        num_rows: 10570
    })
})

cast

< >

( features: Features )

引數

  • features (Features) — 要將資料集轉換到的新特徵。特徵中欄位的名稱和順序必須與當前列名匹配。資料的型別也必須能夠從一種型別轉換為另一種型別。對於非平凡的轉換,例如 string <-> ClassLabel,您應該使用 map() 來更新資料集。

將資料集轉換為一組新的特徵。該轉換將應用於資料集字典的所有資料集。

示例

>>> from datasets import load_dataset, ClassLabel, Value
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds["train"].features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> new_features = ds["train"].features.copy()
>>> new_features['label'] = ClassLabel(names=['bad', 'good'])
>>> new_features['text'] = Value('large_string')
>>> ds = ds.cast(new_features)
>>> ds["train"].features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('large_string')}

cast_column

< >

( column: str feature )

引數

  • column (str) — 列名。
  • feature (Feature) — 目標特徵。

將列轉換為特徵以進行解碼。

示例

>>> from datasets import load_dataset, ClassLabel
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds["train"].features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds["train"].features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('string')}

remove_columns

< >

( column_names: typing.Union[str, list[str]] ) DatasetDict

引數

  • column_names (Union[str, list[str]]) — 要移除的列名。

返回

DatasetDict

移除了指定列的資料集物件副本。

從資料集的每個分割中移除一個或多個列以及與這些列相關的特徵。

該轉換將應用於資料集字典的所有分割。

您也可以使用帶有 remove_columnsmap() 來移除列,但本方法不會複製剩餘列的資料,因此速度更快。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds = ds.remove_columns("label")
DatasetDict({
    train: Dataset({
        features: ['text'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text'],
        num_rows: 1066
    })
})

rename_column

< >

( original_column_name: str new_column_name: str )

引數

  • original_column_name (str) — 要重新命名的列名。
  • new_column_name (str) — 列的新名稱。

重新命名資料集中的列,並將與原始列關聯的特徵移動到新列名下。該轉換將應用於資料集字典的所有資料集。

您也可以使用帶有 remove_columnsmap() 來重新命名列,但本方法

  • 負責將原始特徵移動到新列名下。
  • 不會將資料複製到新資料集中,因此速度更快。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds = ds.rename_column("label", "label_new")
DatasetDict({
    train: Dataset({
        features: ['text', 'label_new'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text', 'label_new'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text', 'label_new'],
        num_rows: 1066
    })
})

rename_columns

< >

( column_mapping: dict ) DatasetDict

引數

  • column_mapping (Dict[str, str]) — 一個將要重新命名的列對映到其新名稱的字典。

返回

DatasetDict

重新命名列後資料集的副本。

重新命名資料集中的多個列,並將與原始列關聯的特徵移動到新列名下。該轉換將應用於資料集字典的所有資料集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.rename_columns({'text': 'text_new', 'label': 'label_new'})
DatasetDict({
    train: Dataset({
        features: ['text_new', 'label_new'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text_new', 'label_new'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text_new', 'label_new'],
        num_rows: 1066
    })
})

select_columns

< >

( column_names: typing.Union[str, list[str]] )

引數

  • column_names (Union[str, list[str]]) — 要保留的列名。

從資料集的每個分割中選擇一個或多個列以及與這些列相關的特徵。

該轉換將應用於資料集字典的所有分割。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
>>> ds.select_columns("text")
DatasetDict({
    train: Dataset({
        features: ['text'],
        num_rows: 8530
    })
    validation: Dataset({
        features: ['text'],
        num_rows: 1066
    })
    test: Dataset({
        features: ['text'],
        num_rows: 1066
    })
})

class_encode_column

< >

( column: str include_nulls: bool = False )

引數

  • column (str) — 要轉換的列名。
  • include_nulls (bool, 預設為 False) — 是否在類別標籤中包含空值。如果為 True,空值將被編碼為 "None" 類別標籤。

    1.14.2 版本新增

將給定列轉換為 ClassLabel 並更新表。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("boolq")
>>> ds["train"].features
{'answer': Value('bool'),
 'passage': Value('string'),
 'question': Value('string')}
>>> ds = ds.class_encode_column("answer")
>>> ds["train"].features
{'answer': ClassLabel(num_classes=2, names=['False', 'True']),
 'passage': Value('string'),
 'question': Value('string')}

push_to_hub

< >

( repo_id config_name: str = 'default' set_default: typing.Optional[bool] = None data_dir: typing.Optional[str] = None commit_message: typing.Optional[str] = None commit_description: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Optional[str] = None revision: typing.Optional[str] = None create_pr: typing.Optional[bool] = False max_shard_size: typing.Union[str, int, NoneType] = None num_shards: typing.Optional[dict[str, int]] = None embed_external_files: bool = True num_proc: typing.Optional[int] = None )

引數

  • repo_id (str) — 要推送到的倉庫 ID,格式為 <user>/<dataset_name><org>/<dataset_name>。也接受 <dataset_name>,此時將預設為已登入使用者的名稱空間。
  • config_name (str) — 資料集的配置名稱。預設為 "default"。
  • set_default (bool, 可選) — 是否將此配置設定為預設配置。否則,預設配置是名為 "default" 的配置。
  • data_dir (str, 可選) — 將包含上傳資料檔案的目錄名稱。如果 config_name 不同於 "default",則預設為 config_name,否則為 "data"。

    2.17.0 版本新增

  • commit_message (str, 可選) — 推送時要提交的訊息。將預設為 "Upload dataset"
  • commit_description (str, 可選) — 將建立的提交的描述。此外,如果建立了 PR(create_pr 為 True),則為 PR 的描述。

    2.16.0 版本新增

  • private (bool, 可選) — 是否將倉庫設為私有。如果為 None(預設),倉庫將為公開,除非組織的預設設定是私有。如果倉庫已存在,則此值將被忽略。
  • token (str, 可選) — Hugging Face Hub 的可選身份驗證令牌。如果未傳遞令牌,將預設使用透過 huggingface-cli login 登入時本地儲存的令牌。如果未傳遞令牌且使用者未登入,將引發錯誤。
  • revision (str, 可選) — 要將上傳的檔案推送到的分支。預設為 "main" 分支。

    2.15.0 版本新增

  • create_pr (bool, 可選, 預設為 False) — 是為上傳的檔案建立一個 PR 還是直接提交。

    2.15.0 版本新增

  • max_shard_size (intstr, 可選, 預設為 "500MB") — 要上傳到 Hub 的資料集分片的最大大小。如果表示為字串,需要是數字後跟一個單位(如 "500MB""1GB")。
  • num_shards (Dict[str, int], 可選) — 要寫入的分片數量。預設情況下,分片數量取決於 max_shard_size。使用字典為每個分割定義不同的 num_shards。

    2.8.0 版本新增

  • embed_external_files (bool, 預設為 True) — 是否在分片中嵌入檔案位元組。特別是,在推送之前,這將對以下型別的欄位執行以下操作:

    • AudioImage 會移除本地路徑資訊並在 Parquet 檔案中嵌入檔案內容。
  • num_proc (int, 可選, 預設為 None) — 準備和上傳資料集時的程序數。如果資料集由許多樣本或要嵌入的媒體檔案組成,這會很有幫助。多程序預設停用。

    4.0.0 版本新增

DatasetDict 作為 Parquet 資料集推送到 Hub。DatasetDict 使用 HTTP 請求推送,不需要安裝 git 或 git-lfs。

每個資料集分割將獨立推送。推送的資料集將保留原始的分割名稱。

預設情況下,生成的 Parquet 檔案是自包含的:如果您的資料集包含 ImageAudio 資料,Parquet 檔案將儲存您的影像或音訊檔案的位元組。您可以透過將 embed_external_files 設定為 False 來停用此功能。

示例

>>> 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>", num_shards={"train": 1024, "test": 8})

如果您想向資料集新增新的配置(或子集)(例如,如果資料集有多個任務/版本/語言)

>>> 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>/<dataset_id>", "fr")

save_to_disk

< >

( dataset_dict_path: typing.Union[str, bytes, os.PathLike] max_shard_size: typing.Union[str, int, NoneType] = None num_shards: typing.Optional[dict[str, int]] = None num_proc: typing.Optional[int] = None storage_options: typing.Optional[dict] = None )

引數

  • dataset_dict_path (path-like) — 資料集字典目錄的路徑(例如 dataset/train)或遠端 URI(例如 s3://my-bucket/dataset/train),資料集字典將被儲存到該位置。
  • max_shard_size (intstr, 可選, 預設為 "500MB") — 要儲存到檔案系統的資料集分片的最大大小。如果表示為字串,需要是數字後跟一個單位(如 "50MB")。
  • num_shards (Dict[str, int], 可選) — 要寫入的分片數量。預設情況下,分片數量取決於 max_shard_sizenum_proc。您需要為資料集字典中的每個資料集提供分片數量。使用字典為每個分割定義不同的 num_shards。

    2.8.0 版本新增

  • num_proc (int, 可選, 預設 None) — 在本地下載和生成資料集時的程序數。多程序預設停用。

    2.8.0 版本新增

  • storage_options (dict, 可選) — 要傳遞給檔案系統後端的鍵/值對(如果有)。

    2.8.0 版本新增

使用 fsspec.spec.AbstractFileSystem 將資料集字典儲存到檔案系統。

對於 ImageAudioVideo 資料

所有的 Image()、Audio() 和 Video() 資料都儲存在 arrow 檔案中。如果您想儲存路徑或 url,請使用 Value(“string”) 型別。

示例

>>> dataset_dict.save_to_disk("path/to/dataset/directory")
>>> dataset_dict.save_to_disk("path/to/dataset/directory", max_shard_size="1GB")
>>> dataset_dict.save_to_disk("path/to/dataset/directory", num_shards={"train": 1024, "test": 8})

load_from_disk

< >

( dataset_dict_path: typing.Union[str, bytes, os.PathLike] keep_in_memory: typing.Optional[bool] = None storage_options: typing.Optional[dict] = None )

引數

  • dataset_dict_path (path-like) — 資料集字典目錄的路徑(例如 "dataset/train")或遠端 URI(例如 "s3//my-bucket/dataset/train"),將從該位置載入資料集字典。
  • keep_in_memory (bool, 預設為 None) — 是否將資料集複製到記憶體中。如果為 None,除非透過將 datasets.config.IN_MEMORY_MAX_SIZE 設定為非零值來明確啟用,否則資料集將不會被複制到記憶體中。更多詳細資訊請參見提高效能部分。
  • storage_options (dict, 可選) — 要傳遞給檔案系統後端的鍵/值對(如果有)。

    2.8.0 版本新增

使用 fsspec.spec.AbstractFileSystem 從檔案系統載入先前使用 save_to_disk 儲存的資料集。

示例

>>> ds = load_from_disk('path/to/dataset/directory')

from_csv

< >

( path_or_paths: dict features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False **kwargs )

引數

  • path_or_paths (dict of path-like) — CSV 檔案的路徑。
  • features (Features, optional) — 資料集特徵。
  • cache_dir (str, optional, 預設為 "~/.cache/huggingface/datasets") — 快取資料的目錄。
  • keep_in_memory (bool, 預設為 False) — 是否將資料複製到記憶體中。
  • **kwargs (附加關鍵字引數) — 傳遞給 pandas.read_csv 的關鍵字引數。

從 CSV 檔案建立 DatasetDict

示例

>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_csv({'train': 'path/to/dataset.csv'})

from_json

< >

( path_or_paths: dict features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False **kwargs )

引數

  • path_or_paths (path-likepath-like 列表) — JSON Lines 檔案的路徑。
  • features (Features, optional) — 資料集特徵。
  • cache_dir (str, optional, 預設為 "~/.cache/huggingface/datasets") — 快取資料的目錄。
  • keep_in_memory (bool, 預設為 False) — 是否將資料複製到記憶體中。
  • **kwargs (附加關鍵字引數) — 傳遞給 JsonConfig 的關鍵字引數。

從 JSON Lines 檔案建立 DatasetDict

示例

>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_json({'train': 'path/to/dataset.json'})

from_parquet

< >

( path_or_paths: dict features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False columns: typing.Optional[list[str]] = None **kwargs )

引數

  • path_or_paths (dict of path-like) — CSV 檔案的路徑。
  • features (Features, optional) — 資料集特徵。
  • cache_dir (str, optional, 預設為 "~/.cache/huggingface/datasets") — 快取資料的目錄。
  • keep_in_memory (bool, 預設為 False) — 是否將資料複製到記憶體中。
  • columns (list[str], optional) — 如果不為 None,則只從檔案中讀取這些列。列名可以是巢狀欄位的字首,例如,“a”將選擇“a.b”、“a.c”和“a.d.e”。
  • **kwargs (附加關鍵字引數) — 傳遞給 ParquetConfig 的關鍵字引數。

從 Parquet 檔案建立 DatasetDict

示例

>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_parquet({'train': 'path/to/dataset/parquet'})

from_text

< >

( path_or_paths: dict features: typing.Optional[datasets.features.features.Features] = None cache_dir: str = None keep_in_memory: bool = False **kwargs )

引數

  • path_or_paths (dict of path-like) — 文字檔案的路徑。
  • features (Features, optional) — 資料集特徵。
  • cache_dir (str, optional, 預設為 "~/.cache/huggingface/datasets") — 快取資料的目錄。
  • keep_in_memory (bool, 預設為 False) — 是否將資料複製到記憶體中。
  • **kwargs (附加關鍵字引數) — 傳遞給 TextConfig 的關鍵字引數。

從文字檔案建立 DatasetDict

示例

>>> from datasets import DatasetDict
>>> ds = DatasetDict.from_text({'train': 'path/to/dataset.txt'})

IterableDataset

基類 IterableDataset 實現了一個由 Python 生成器支援的可迭代資料集。

class datasets.IterableDataset

< >

( ex_iterable: _BaseExamplesIterable info: typing.Optional[datasets.info.DatasetInfo] = None split: typing.Optional[datasets.splits.NamedSplit] = None formatting: typing.Optional[datasets.iterable_dataset.FormattingConfig] = None shuffling: typing.Optional[datasets.iterable_dataset.ShufflingConfig] = None distributed: typing.Optional[datasets.iterable_dataset.DistributedConfig] = None token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )

由一個可迭代物件支援的資料集。

from_generator

< >

( generator: typing.Callable features: typing.Optional[datasets.features.features.Features] = None gen_kwargs: typing.Optional[dict] = None split: NamedSplit = NamedSplit('train') ) IterableDataset

引數

  • generator (Callable) — 一個 `yields` 樣本的生成器函式。
  • features (Features, optional) — 資料集特徵。
  • gen_kwargs(dict, optional) — 傳遞給 generator 可呼叫物件的關鍵字引數。你可以透過在 gen_kwargs 中傳遞分片列表來定義一個分片可迭代資料集。這可以用於改善洗牌效果,以及在使用多個工作程序迭代資料集時。
  • split (NamedSplit, 預設為 Split.TRAIN) — 分配給資料集的分割名稱。

    2.21.0 版本新增

返回

IterableDataset

從生成器建立一個可迭代資料集。

示例

>>> def gen():
...     yield {"text": "Good", "label": 0}
...     yield {"text": "Bad", "label": 1}
...
>>> ds = IterableDataset.from_generator(gen)
>>> def gen(shards):
...     for shard in shards:
...         with open(shard) as f:
...             for line in f:
...                 yield {"line": line}
...
>>> shards = [f"data{i}.txt" for i in range(32)]
>>> ds = IterableDataset.from_generator(gen, gen_kwargs={"shards": shards})
>>> ds = ds.shuffle(seed=42, buffer_size=10_000)  # shuffles the shards order + uses a shuffle buffer
>>> from torch.utils.data import DataLoader
>>> dataloader = DataLoader(ds.with_format("torch"), num_workers=4)  # give each worker a subset of 32/4=8 shards

remove_columns

< >

( column_names: typing.Union[str, list[str]] ) IterableDataset

引數

  • column_names (Union[str, List[str]]) — 要移除的列的名稱。

返回

IterableDataset

移除了指定列的資料集物件副本。

移除資料集中的一個或多個列以及與之相關的特徵。在迭代資料集時,移除操作是在樣本上動態執行的。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 'label': 1}
>>> ds = ds.remove_columns("label")
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

select_columns

< >

( column_names: typing.Union[str, list[str]] ) IterableDataset

引數

  • column_names (Union[str, List[str]]) — 要選擇的列的名稱。

返回

IterableDataset

帶有選定列的資料集物件的副本。

選擇資料集中的一個或多個列以及與之相關的特徵。在迭代資料集時,選擇操作是在樣本上動態執行的。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .', 'label': 1}
>>> ds = ds.select_columns("text")
>>> next(iter(ds))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

cast_column

< >

( column: str feature: typing.Union[dict, list, tuple, datasets.features.features.Value, datasets.features.features.ClassLabel, datasets.features.translation.Translation, datasets.features.translation.TranslationVariableLanguages, datasets.features.features.LargeList, datasets.features.features.List, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image, datasets.features.video.Video, datasets.features.pdf.Pdf] ) IterableDataset

引數

  • column (str) — 列名。
  • feature (Feature) — 目標特徵。

返回

IterableDataset

將列轉換為特徵以進行解碼。

示例

>>> from datasets import load_dataset, Audio
>>> ds = load_dataset("PolyAI/minds14", name="en-US", split="train", streaming=True)
>>> ds.features
{'audio': Audio(sampling_rate=8000, mono=True, decode=True, id=None),
 'english_transcription': Value('string'),
 'intent_class': ClassLabel(num_classes=14, names=['abroad', 'address', 'app_error', 'atm_limit', 'balance', 'business_loan',  'card_issues', 'cash_deposit', 'direct_debit', 'freeze', 'high_value_payment', 'joint_account', 'latest_transactions', 'pay_bill']),
 'lang_id': ClassLabel(num_classes=14, names=['cs-CZ', 'de-DE', 'en-AU', 'en-GB', 'en-US', 'es-ES', 'fr-FR', 'it-IT', 'ko-KR',  'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'zh-CN']),
 'path': Value('string'),
 'transcription': Value('string')}
>>> ds = ds.cast_column("audio", Audio(sampling_rate=16000))
>>> ds.features
{'audio': Audio(sampling_rate=16000, mono=True, decode=True, id=None),
 'english_transcription': Value('string'),
 'intent_class': ClassLabel(num_classes=14, names=['abroad', 'address', 'app_error', 'atm_limit', 'balance', 'business_loan',  'card_issues', 'cash_deposit', 'direct_debit', 'freeze', 'high_value_payment', 'joint_account', 'latest_transactions', 'pay_bill']),
 'lang_id': ClassLabel(num_classes=14, names=['cs-CZ', 'de-DE', 'en-AU', 'en-GB', 'en-US', 'es-ES', 'fr-FR', 'it-IT', 'ko-KR',  'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'zh-CN']),
 'path': Value('string'),
 'transcription': Value('string')}

cast

< >

( features: Features ) IterableDataset

引數

  • features (Features) — 用於轉換資料集的新特徵。特徵中欄位的名稱必須與當前列名匹配。資料型別也必須能夠從一種型別轉換為另一種。對於非平凡的轉換,例如 `string` <-> `ClassLabel`,你應該使用 map() 來更新資料集。

返回

IterableDataset

一份具有轉換後特徵的資料集副本。

將資料集轉換為一組新的特徵。

示例

>>> from datasets import load_dataset, ClassLabel, Value
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> ds.features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> new_features = ds.features.copy()
>>> new_features["label"] = ClassLabel(names=["bad", "good"])
>>> new_features["text"] = Value("large_string")
>>> ds = ds.cast(new_features)
>>> ds.features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('large_string')}

decode

< >

( enable: bool = True num_threads: int = 0 ) IterableDataset

引數

  • enable (bool, 預設為 True) — 啟用或停用特徵解碼。
  • num_threads (int, 預設為 0) — 啟用多執行緒進行特徵解碼。

返回

IterableDataset

一份具有轉換後特徵的資料集副本。

啟用或停用對音訊、影像、影片的資料集特徵解碼。

啟用時(預設),媒體型別會被解碼

  • 音訊 -> 包含 "array"、"sampling_rate" 和 "path" 的字典
  • 影像 -> PIL.Image
  • 影片 -> torchvision.io.VideoReader

您可以使用 num_threads 啟用多執行緒。這對於加快遠端資料流傳輸特別有用。但是,對於快速磁碟上的本地資料,它可能比 num_threads=0 慢。

如果您想迭代媒體檔案的路徑或位元組,而不實際解碼其內容,停用解碼會很有用。要停用解碼,您可以使用 .decode(False),這相當於呼叫 .cast().cast_column() 並將所有音訊、影像和影片型別的 decode=False 設定為 False

示例

停用解碼

>>> from datasets import load_dataset
>>> ds = load_dataset("sshh12/planet-textures", split="train", streaming=True)
>>> next(iter(ds))
{'image': <PIL.PngImagePlugin.PngImageFile image mode=RGB size=2048x1024>,
'text': 'A distant celestial object with an icy crust, displaying a light blue shade, covered with round pits and rugged terrains.'}
>>> ds = ds.decode(False)
>>> ds.features
{'image': Image(mode=None, decode=False, id=None),
'text': Value('string')}
>>> next(iter(ds))
{
  'image': {
    'path': 'hf://datasets/sshh12/planet-textures@69dc4cef7a5c4b2cfe387727ec8ea73d4bff7302/train/textures/0000.png',
    'bytes': None
  },
  'text': 'A distant celestial object with an icy crust, displaying a light blue shade, covered with round pits and rugged terrains.'
}

透過多執行緒加速流式處理

>>> import os
>>> from datasets import load_dataset
>>> from tqdm import tqdm
>>> ds = load_dataset("sshh12/planet-textures", split="train", streaming=True)
>>> num_threads = min(32, (os.cpu_count() or 1) + 4)
>>> ds = ds.decode(num_threads=num_threads)
>>> for _ in tqdm(ds):  # 20 times faster !
...     ...

__iter__

< >

( )

iter

< >

( batch_size: int drop_last_batch: bool = False )

引數

  • batch_size (int) — 每個要生成的批次的大小。
  • drop_last_batch (bool, 預設為 False) — 是否應丟棄小於 batch_size 的最後一個批次。

按批次大小 batch_size 遍歷。

map

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 drop_last_batch: bool = False remove_columns: typing.Union[str, list[str], NoneType] = None features: typing.Optional[datasets.features.features.Features] = None fn_kwargs: typing.Optional[dict] = None )

引數

  • function (Callable, 可選, 預設為 None) — 在你迭代資料集時,即時應用於樣本的函式。它必須具有以下簽名之一:

    • function(example: Dict[str, Any]) -> Dict[str, Any] 如果 batched=Falsewith_indices=False
    • function(example: Dict[str, Any], idx: int) -> Dict[str, Any] 如果 batched=Falsewith_indices=True
    • function(batch: Dict[str, List]) -> Dict[str, List] 如果 batched=Truewith_indices=False
    • function(batch: Dict[str, List], indices: List[int]) -> Dict[str, List] 如果 batched=Truewith_indices=True

    對於高階用法,該函式也可以返回一個 `pyarrow.Table`。如果函式是非同步的,那麼 `map` 將並行執行你的函式。此外,如果你的函式不返回任何內容 (None),那麼 `map` 將執行你的函式並返回未經更改的資料集。如果沒有提供函式,則預設為恆等函式:`lambda x: x`。

  • with_indices (bool, 預設為 False) — 向 `function` 提供樣本索引。請注意,在這種情況下,`function` 的簽名應為 `def function(example, idx[, rank]): ...`。
  • input_columns (Optional[Union[str, List[str]]], 預設為 None) — 作為位置引數傳遞給 `function` 的列。如果為 `None`,則將一個對映到所有格式化列的字典作為單個引數傳遞。
  • batched (bool, 預設為 False) — 向 `function` 提供批次樣本。
  • batch_size (int, 可選, 預設為 1000) — 如果 `batched=True`,提供給 `function` 的每批樣本數。如果 `batch_size <= 0` 或 `batch_size == None`,則將整個資料集作為一個批次提供給 `function`。
  • drop_last_batch (bool, 預設為 False) — 是否應丟棄小於 batch_size 的最後一個批次,而不是由函式處理。
  • remove_columns ([List[str]], 可選, 預設為 None) — 在對映過程中移除選定的列。列將在用 `function` 的輸出更新樣本之前被移除,即如果 `function` 添加了名稱在 `remove_columns` 中的列,這些列將被保留。
  • features ([Features], 可選, 預設為 None) — 結果資料集的特徵型別。
  • fn_kwargs (Dict, 可選, 預設為 None) — 要傳遞給 `function` 的關鍵字引數。

對可迭代資料集中的所有樣本(單個或批次)應用一個函式並更新它們。如果你的函式返回一個已存在的列,那麼它將覆蓋該列。該函式在迭代資料集時即時應用於樣本。

您可以使用 `batched` 引數指定函式是否應批次處理。

  • 如果 `batched` 為 `False`,則函式接收 1 個示例作為輸入,並應返回 1 個示例。一個示例是一個字典,例如 `{"text": "Hello there !"}`。
  • 如果 batched 為 Truebatch_size 為 1,則函式將一個包含 1 個樣本的批次作為輸入,並可以返回一個包含 1 個或多個樣本的批次。一個批次是一個字典,例如一個包含 1 個樣本的批次是 {“text”: [“Hello there !”]}。
  • 如果 batched 為 Truebatch_sizen > 1,則函式將一個包含 n 個樣本的批次作為輸入,並可以返回一個包含 n 個樣本或任意數量樣本的批次。請注意,最後一個批次可能少於 n 個樣本。一個批次是一個字典,例如一個包含 n 個樣本的批次是 {"text": ["Hello there !"] * n}

如果函式是非同步的,那麼 map 將並行執行你的函式,最多可以同時進行一千次呼叫。如果你想設定可以同時執行的最大運算元,建議在你的函式中使用 asyncio.Semaphore

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'Review: the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 'text': 'Review: 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': 'Review: effective but too-tepid biopic'}]

rename_column

< >

( original_column_name: str new_column_name: str ) IterableDataset

引數

  • original_column_name (str) — 要重新命名的列的名稱。
  • new_column_name (str) — 列的新名稱。

返回

IterableDataset

一列已重新命名的資料集副本。

重新命名資料集中的一列,並將與原始列關聯的特徵移動到新的列名下。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> next(iter(ds))
{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}
>>> ds = ds.rename_column("text", "movie_review")
>>> next(iter(ds))
{'label': 1,
 'movie_review': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

過濾器

< >

( function: typing.Optional[typing.Callable] = None with_indices = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 fn_kwargs: typing.Optional[dict] = None )

引數

  • function (Callable) — 具有以下簽名之一的可呼叫物件:

    • function(example: Dict[str, Any]) -> bool 如果 with_indices=False, batched=False
    • function(example: Dict[str, Any], indices: int) -> bool 如果 with_indices=True, batched=False
    • function(example: Dict[str, List]) -> List[bool] 如果 with_indices=False, batched=True
    • function(example: Dict[str, List], indices: List[int]) -> List[bool] 如果 with_indices=True, batched=True

    如果函式是非同步的,那麼 `filter` 將並行執行你的函式。如果沒有提供函式,則預設為一個始終返回 True 的函式:`lambda x: True`。

  • with_indices (bool, 預設為 False) — 向 `function` 提供樣本索引。請注意,在這種情況下,`function` 的簽名應為 `def function(example, idx): ...`。
  • input_columns (strList[str], 可選) — 作為位置引數傳遞給 `function` 的列。如果為 `None`,則將一個對映到所有格式化列的字典作為單個引數傳遞。
  • batched (bool, 預設為 False) — 向 `function` 提供批次樣本。
  • batch_size (int, 可選, 預設為 1000) — 如果 `batched=True`,提供給 `function` 的每批樣本數。
  • fn_kwargs (Dict, 可選, 預設為 None) — 要傳遞給 `function` 的關鍵字引數。

對所有元素應用一個過濾函式,使資料集只包含符合過濾函式條件的樣本。過濾在迭代資料集時即時進行。

如果函式是非同步的,那麼 `filter` 將並行執行你的函式,最多可以同時進行一千次呼叫(可配置)。如果你想設定可以同時執行的最大運算元,建議在你的函式中使用 `asyncio.Semaphore`。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> ds = ds.filter(lambda x: x["label"] == 0)
>>> list(ds.take(3))
[{'label': 0, 'movie_review': 'simplistic , silly and tedious .'},
 {'label': 0,
 'movie_review': "it's so laddish and juvenile , only teenage boys could possibly find it funny ."},
 {'label': 0,
 'movie_review': 'exploitative and largely devoid of the depth or sophistication that would make watching such a graphic treatment of the crimes bearable .'}]

shuffle

< >

( seed = None generator: typing.Optional[numpy.random._generator.Generator] = None buffer_size: int = 1000 )

引數

  • seed (int, 可選, 預設為 None) — 用於打亂資料集的隨機種子。它用於從打亂緩衝區中取樣,也用於打亂資料分片。
  • generator (numpy.random.Generator, 可選) — 用於計算資料集行排列的 Numpy 隨機生成器。如果 `generator=None` (預設),則使用 `np.random.default_rng` (NumPy 的預設 BitGenerator (PCG64))。
  • buffer_size (int, 預設為 1000) — 緩衝區的大小。

隨機打亂此資料集的元素。

此資料集用 `buffer_size` 個元素填充一個緩衝區,然後從該緩衝區中隨機取樣元素,用新元素替換選定的元素。為了實現完美的打亂,需要一個大於或等於資料集完整大小的緩衝區大小。

例如,如果你的資料集包含 10,000 個元素,但 `buffer_size` 設定為 1000,那麼 `shuffle` 最初將僅從緩衝區中的前 1000 個元素中隨機選擇一個元素。一旦一個元素被選中,它在緩衝區中的空間將被下一個(即第 1001 個)元素替換,從而維持 1000 個元素的緩衝區。

如果資料集由多個分片組成,它也會打亂分片的順序。但是,如果順序已透過使用 skip()take() 固定,則分片的順序保持不變。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 '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'}]
>>> shuffled_ds = ds.shuffle(seed=42)
>>> list(shuffled_ds.take(3))
[{'label': 1,
 'text': "a sports movie with action that's exciting on the field and a story you care about off it ."},
 {'label': 1,
 '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 ."}]

batch

< >

( batch_size: int drop_last_batch: bool = False )

引數

  • batch_size (int) — 每個批次中的樣本數。
  • drop_last_batch (bool, 預設為 False) — 是否丟棄最後一個不完整的批次。

將資料集中的樣本分組為批次。

示例

>>> ds = load_dataset("some_dataset", streaming=True)
>>> batched_ds = ds.batch(batch_size=32)

skip

< >

( n: int )

引數

  • n (int) — 要跳過的元素數量。

建立一個新的 IterableDataset,它跳過前 `n` 個元素。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> list(ds.take(3))
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 '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'}]
>>> ds = ds.skip(1)
>>> list(ds.take(3))
[{'label': 1,
 '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'},
 {'label': 1,
 'text': 'if you sometimes like to go to the movies to have fun , wasabi is a good place to start .'}]

take

< >

( n: int )

引數

  • n (int) — 要獲取的元素數量。

建立一個新的 IterableDataset,它只包含前 `n` 個元素。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train", streaming=True)
>>> small_ds = ds.take(2)
>>> list(small_ds)
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 '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 .'}]

shard

< >

( num_shards: int index: int contiguous: bool = True )

引數

  • num_shards (int) — 要將資料集分割成的分片數量。
  • index (int) — 要選擇和返回的分片。
  • contiguous — (bool, 預設為 True): 是否為分片選擇連續的索引塊。

返回將資料集拆分成 num_shards 份後的第 index 個分片。

這將確定性地進行分片。`dataset.shard(n, i)` 將資料集分割成連續的塊,以便在處理後可以輕鬆地將其連接回來。如果 `dataset.num_shards % n == l`,那麼前 `l` 個數據集每個都有 `(dataset.num_shards // n) + 1` 個分片,其餘的資料集有 `(dataset.num_shards // n)` 個分片。`datasets.concatenate_datasets([dset.shard(n, i) for i in range(n)])` 返回一個與原始資料集順序相同的的資料集。特別是,`dataset.shard(dataset.num_shards, i)` 返回一個包含 1 個分片的資料集。

注意:n 應該小於或等於資料集中的分片數 `dataset.num_shards`。

另一方面,`dataset.shard(n, i, contiguous=False)` 包含資料集中所有索引模 `n = i` 的分片。

在使用任何隨機化運算子(如 `shuffle`)之前,請務必進行分片。最好在資料集管道的早期使用分片運算子。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("amazon_polarity", split="train", streaming=True)
>>> ds
Dataset({
    features: ['label', 'title', 'content'],
    num_shards: 4
})
>>> ds.shard(num_shards=2, index=0)
Dataset({
    features: ['label', 'title', 'content'],
    num_shards: 2
})

repeat

< >

( num_times: typing.Optional[int] )

引數

  • num_times (int) or (None) — 重複資料集的次數。如果為 `None`,資料集將無限期重複。

建立一個新的 IterableDataset,它將底層資料集重複 `num_times` 次。

注意:在 repeat 之後呼叫 shuffle 的效果很大程度上取決於緩衝區大小。當 buffer_size 為 1 時,即使在 shuffle 之後,重複資料也永遠不會在同一次迭代中出現:ds.repeat(n).shuffle(seed=42, buffer_size=1) 等同於 ds.shuffle(seed=42, buffer_size=1).repeat(n),並且僅在每次迭代內打亂分片順序。當 buffer size >= (資料集中樣本數 * num_times) 時,我們可以對重複資料進行完全打亂,即我們可以在同一次迭代中觀察到重複資料。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> ds = ds.take(2).repeat(2)
>>> list(ds)
[{'label': 1,
 'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 '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'},
 {'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 schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 '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'}]

to_csv

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **to_csv_kwargs ) int

引數

  • path_or_buf (PathLike or FileOrBuffer) — 檔案路徑(例如 `file.csv`)、遠端 URI(例如 `hf://datasets/username/my_dataset_name/data.csv`)或 BinaryIO,資料集將以指定格式儲存到其中。
  • batch_size (int, 可選) — 一次載入到記憶體並寫入的批次大小。預設為 `datasets.config.DEFAULT_MAX_BATCH_SIZE`。
  • storage_options (dict, 可選) — 要傳遞給檔案系統後端的鍵/值對(如果有)。
  • **to_csv_kwargs (附加關鍵字引數) — 傳遞給 pandas 的 pandas.DataFrame.to_csv 的引數。如果未指定,引數 `index` 預設為 `False`。如果你想寫入索引,請傳遞 `index=True` 並透過傳遞 `index_label` 為索引列設定名稱。

返回

int

寫入的字元或位元組數。

將資料集匯出為 csv。

這會迭代資料集並在寫入之前將其完全載入到記憶體中。

示例

>>> ds.to_csv("path/to/dataset/directory")

to_pandas

< >

( batch_size: typing.Optional[int] = None batched: bool = False )

引數

  • batch_size (int, 可選) — 如果 `batched` 為 `True`,則為批次的大小(行數)。預設為 `datasets.config.DEFAULT_MAX_BATCH_SIZE`。
  • batched (bool) — 設定為 `True` 以返回一個生成器,該生成器以 `batch_size` 行的批次形式產生資料集。預設為 `False`(一次返回整個資料集)。

將資料集作為 pandas.DataFrame 返回。對於大型資料集,也可以返回一個生成器。

示例

>>> ds.to_pandas()

to_dict

< >

( batch_size: typing.Optional[int] = None batched: bool = False )

引數

  • batch_size (int, 可選) — 如果 `batched` 為 `True`,則為批次的大小(行數)。預設為 `datasets.config.DEFAULT_MAX_BATCH_SIZE`。

將資料集作為 Python 字典返回。對於大型資料集,也可以返回一個生成器。

示例

>>> ds.to_dict()

to_json

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **to_json_kwargs ) int

引數

  • path_or_buf (PathLike or FileOrBuffer) — 檔案路徑(例如 file.json)、遠端 URI(例如 hf://datasets/username/my_dataset_name/data.json)或 BinaryIO,資料集將以指定格式儲存到此處。
  • batch_size (int, optional) — 一次性載入到記憶體並寫入的批次大小。預設為 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • storage_options (dict, optional) — 要傳遞給檔案系統後端的鍵值對(如果有)。
  • **to_json_kwargs (附加關鍵字引數) — 傳遞給 pandas 的 pandas.DataFrame.to_json 的引數。預設引數是 lines=Trueorient="records"。如果 orient"split""table",引數 index 預設為 False。如果你想寫入索引,請傳遞 index=True

返回

int

寫入的字元或位元組數。

將資料集匯出為 JSON Lines 或 JSON。

這會迭代資料集並在寫入之前將其完全載入到記憶體中。

預設輸出格式是 JSON Lines。要匯出為 JSON,請傳遞 lines=False 引數和所需的 orient

示例

>>> ds.to_json("path/to/dataset/directory/filename.jsonl")
>>> num_shards = dataset.num_shards
>>> for index in range(num_shards):
...     shard = dataset.shard(index, num_shards)
...     shard.to_json(f"path/of/my/dataset/data-{index:05d}.jsonl")

to_parquet

< >

( path_or_buf: typing.Union[str, bytes, os.PathLike, typing.BinaryIO] batch_size: typing.Optional[int] = None storage_options: typing.Optional[dict] = None **parquet_writer_kwargs ) int

引數

  • path_or_buf (PathLike or FileOrBuffer) — 檔案路徑(例如 file.parquet)、遠端 URI(例如 hf://datasets/username/my_dataset_name/data.parquet)或 BinaryIO,資料集將以指定格式儲存到此處。
  • batch_size (int, optional) — 一次性載入到記憶體並寫入的批次大小。預設為 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • storage_options (dict, optional) — 要傳遞給檔案系統後端的鍵值對(如果有)。

    2.19.0 版本新增

  • **parquet_writer_kwargs (附加關鍵字引數) — 傳遞給 PyArrow 的 pyarrow.parquet.ParquetWriter 的引數。

返回

int

寫入的字元或位元組數。

將資料集匯出為 parquet 檔案。

示例

>>> ds.to_parquet("path/to/dataset/directory")
>>> num_shards = dataset.num_shards
>>> for index in range(num_shards):
...     shard = dataset.shard(index, num_shards)
...     shard.to_parquet(f"path/of/my/dataset/data-{index:05d}.parquet")

to_sql

< >

( name: str con: typing.Union[str, ForwardRef('sqlalchemy.engine.Connection'), ForwardRef('sqlalchemy.engine.Engine'), ForwardRef('sqlite3.Connection')] batch_size: typing.Optional[int] = None **sql_writer_kwargs ) int

引數

  • name (str) — SQL 表的名稱。
  • con (str or sqlite3.Connection or sqlalchemy.engine.Connection or sqlalchemy.engine.Connection) — 用於寫入資料庫的 URI 字串 或 SQLite3/SQLAlchemy 連線物件。
  • batch_size (int, optional) — 一次性載入到記憶體並寫入的批次大小。預設為 datasets.config.DEFAULT_MAX_BATCH_SIZE
  • **sql_writer_kwargs (附加關鍵字引數) — 傳遞給 pandas 的 pandas.DataFrame.to_sql 的引數。如果未指定,引數 index 預設為 False。如果你想寫入索引,請傳遞 index=True,並透過傳遞 index_label 為索引列設定名稱。

返回

int

寫入的記錄數。

將資料集匯出到 SQL 資料庫。

示例

>>> # con provided as a connection URI string
>>> ds.to_sql("data", "sqlite:///my_own_db.sql")
>>> # con provided as a sqlite3 connection object
>>> import sqlite3
>>> con = sqlite3.connect("my_own_db.sql")
>>> with con:
...     ds.to_sql("data", con)

push_to_hub

< >

( repo_id: str config_name: str = 'default' set_default: typing.Optional[bool] = None split: typing.Optional[str] = None data_dir: typing.Optional[str] = None commit_message: typing.Optional[str] = None commit_description: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Optional[str] = None revision: typing.Optional[str] = None create_pr: typing.Optional[bool] = False num_shards: typing.Optional[int] = None embed_external_files: bool = True num_proc: typing.Optional[int] = None )

引數

  • repo_id (str) — 要推送到的倉庫 ID,格式如下:<user>/<dataset_name><org>/<dataset_name>。也接受 <dataset_name>,它將預設為已登入使用者的名稱空間。
  • config_name (str, 預設為 “default”) — 資料集的配置名稱(或子集)。預設為 “default”。
  • set_default (bool, optional) — 是否將此配置設定為預設配置。否則,預設配置是名為 “default” 的配置。
  • split (str, optional) — 將賦予該資料集的拆分名稱。預設為 self.split
  • data_dir (str, optional) — 包含上傳的資料檔案的目錄名稱。如果 config_name 不同於 “default”,則預設為 config_name,否則為 “data”。
  • commit_message (str, optional) — 推送時要提交的訊息。將預設為 "Upload dataset"
  • commit_description (str, optional) — 將要建立的提交的描述。如果建立了 PR(create_pr 為 True),則也是 PR 的描述。
  • private (bool, optional) — 是否將倉庫設為私有。如果為 None (預設),除非組織的預設設定是私有,否則倉庫將是公開的。如果倉庫已存在,則忽略此值。
  • token (str, optional) — Hugging Face Hub 的可選身份驗證令牌。如果未傳遞令牌,將預設為使用 huggingface-cli login 登入時本地儲存的令牌。如果未傳遞令牌且使用者未登入,則會引發錯誤。
  • revision (str, optional) — 要將上傳的檔案推送到的分支。預設為 "main" 分支。
  • create_pr (bool, optional, 預設為 False) — 是為上傳的檔案建立 PR 還是直接提交。
  • num_shards (int, optional) — 要寫入的分片數量。預設等於該資料集的 .num_shards
  • embed_external_files (bool, 預設為 True) — 是否在分片中嵌入檔案位元組。特別是,在推送之前,對於以下型別的欄位,它將執行以下操作:

    • AudioImage:移除本地路徑資訊並在 Parquet 檔案中嵌入檔案內容。
  • num_proc (int, optional, 預設為 None) — 準備和上傳資料集時的程序數。如果資料集包含許多樣本和轉換,這將很有幫助。預設停用多程序。

將資料集作為 Parquet 資料集推送到 Hub。資料集使用 HTTP 請求推送,不需要安裝 git 或 git-lfs。

預設情況下,生成的 Parquet 檔案是自包含的。如果您的資料集包含 ImageAudioVideo 資料,Parquet 檔案將儲存您的影像或音訊檔案的位元組。您可以透過將 `embed_external_files` 設定為 `False` 來停用此功能。

示例

>>> dataset.push_to_hub("<organization>/<dataset_id>")
>>> dataset_dict.push_to_hub("<organization>/<dataset_id>", private=True)
>>> dataset.push_to_hub("<organization>/<dataset_id>", num_shards=1024)

如果您的資料集有多個拆分(例如 train/validation/test)

>>> train_dataset.push_to_hub("<organization>/<dataset_id>", split="train")
>>> val_dataset.push_to_hub("<organization>/<dataset_id>", split="validation")
>>> # later
>>> dataset = load_dataset("<organization>/<dataset_id>")
>>> train_dataset = dataset["train"]
>>> val_dataset = dataset["validation"]

如果您想向資料集新增新的配置(或子集)(例如,如果資料集有多個任務/版本/語言)

>>> 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>/<dataset_id>", "fr")

load_state_dict

< >

( state_dict: dict )

載入資料集的 state_dict。迭代將從狀態儲存時的下一個示例重新開始。

恢復時會準確地返回到檢查點儲存的位置,但有兩種情況例外

  1. 恢復時,隨機緩衝區中的示例會丟失,緩衝區會用新資料重新填充
  2. .with_format(arrow) 和批處理 .map() 的組合可能會跳過一個批次。

示例

>>> from datasets import Dataset, concatenate_datasets
>>> ds = Dataset.from_dict({"a": range(6)}).to_iterable_dataset(num_shards=3)
>>> for idx, example in enumerate(ds):
...     print(example)
...     if idx == 2:
...         state_dict = ds.state_dict()
...         print("checkpoint")
...         break
>>> ds.load_state_dict(state_dict)
>>> print(f"restart from checkpoint")
>>> for example in ds:
...     print(example)

它返回

{'a': 0}
{'a': 1}
{'a': 2}
checkpoint
restart from checkpoint
{'a': 3}
{'a': 4}
{'a': 5}
>>> from torchdata.stateful_dataloader import StatefulDataLoader
>>> ds = load_dataset("deepmind/code_contests", streaming=True, split="train")
>>> dataloader = StatefulDataLoader(ds, batch_size=32, num_workers=4)
>>> # checkpoint
>>> state_dict = dataloader.state_dict()  # uses ds.state_dict() under the hood
>>> # resume from checkpoint
>>> dataloader.load_state_dict(state_dict)  # uses ds.load_state_dict() under the hood

state_dict

< >

( ) dict

返回

字典

獲取資料集的當前 state_dict。它對應於它產出的最後一個示例的狀態。

恢復時會準確地返回到檢查點儲存的位置,但有兩種情況例外

  1. 恢復時,隨機緩衝區中的示例會丟失,緩衝區會用新資料重新填充
  2. .with_format(arrow) 和批處理 .map() 的組合可能會跳過一個批次。

示例

>>> from datasets import Dataset, concatenate_datasets
>>> ds = Dataset.from_dict({"a": range(6)}).to_iterable_dataset(num_shards=3)
>>> for idx, example in enumerate(ds):
...     print(example)
...     if idx == 2:
...         state_dict = ds.state_dict()
...         print("checkpoint")
...         break
>>> ds.load_state_dict(state_dict)
>>> print(f"restart from checkpoint")
>>> for example in ds:
...     print(example)

它返回

{'a': 0}
{'a': 1}
{'a': 2}
checkpoint
restart from checkpoint
{'a': 3}
{'a': 4}
{'a': 5}
>>> from torchdata.stateful_dataloader import StatefulDataLoader
>>> ds = load_dataset("deepmind/code_contests", streaming=True, split="train")
>>> dataloader = StatefulDataLoader(ds, batch_size=32, num_workers=4)
>>> # checkpoint
>>> state_dict = dataloader.state_dict()  # uses ds.state_dict() under the hood
>>> # resume from checkpoint
>>> dataloader.load_state_dict(state_dict)  # uses ds.load_state_dict() under the hood

info

< >

( )

包含資料集中所有元資料的 DatasetInfo 物件。

split

< >

( )

對應於命名資料集拆分的 NamedSplit 物件。

builder_name

< >

( )

引用

< >

( )

config_name

< >

( )

dataset_size

< >

( )

description

< >

( )

download_checksums

< >

( )

download_size

< >

( )

features

< >

( )

homepage

< >

( )

許可證

< >

( )

size_in_bytes

< >

( )

supervised_keys

< >

( )

版本

< >

( )

class datasets.IterableColumn

< >

( source: typing.Union[ForwardRef('IterableDataset'), ForwardRef('IterableColumn')] column_name: str )

IterableDataset 特定列的可迭代物件。

示例

迭代資料集“text”列中的文字

for text in dataset["text"]:
    ...

它也適用於巢狀列

for source in dataset["metadata"]["source"]:
    ...

IterableDatasetDict

以拆分名稱(例如 'train'、'test')為鍵,以 IterableDataset 物件為值的字典。

class datasets.IterableDatasetDict

< >

( )

map

< >

( function: typing.Optional[typing.Callable] = None with_indices: bool = False with_split: bool = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: int = 1000 drop_last_batch: bool = False remove_columns: typing.Union[str, list[str], NoneType] = None fn_kwargs: typing.Optional[dict] = None )

引數

  • function (Callable, optional, 預設為 None) — 在迭代資料集時即時應用於示例的函式。它必須具有以下簽名之一:

    • function(example: Dict[str, Any]) -> Dict[str, Any] 如果 batched=Falsewith_indices=False
    • function(example: Dict[str, Any], idx: int) -> Dict[str, Any] 如果 batched=Falsewith_indices=True
    • function(batch: Dict[str, list]) -> Dict[str, list] 如果 batched=Truewith_indices=False
    • function(batch: Dict[str, list], indices: list[int]) -> Dict[str, list] 如果 batched=Truewith_indices=True

    對於高階用法,該函式也可以返回一個 pyarrow.Table。如果函式是非同步的,那麼 map 將並行執行您的函式。此外,如果您的函式不返回任何內容(None),那麼 map 將執行您的函式並返回未更改的資料集。如果沒有提供函式,則預設為恆等函式:lambda x: x

  • with_indices (bool, 預設為 False) — 向 function 提供示例索引。請注意,在這種情況下,function 的簽名應為 def function(example, idx[, rank]): ...
  • input_columns ([Union[str, list[str]]], optional, 預設為 None) — 作為位置引數傳遞給 function 的列。如果為 None,則將一個對映到所有格式化列的字典作為單個引數傳遞。
  • batched (bool, 預設為 False) — 向 function 提供批處理的示例。
  • batch_size (int, optional, 預設為 1000) — 如果 batched=True,提供給 function 的每個批次的示例數。
  • drop_last_batch (bool, 預設為 False) — 是否應丟棄小於 batch_size 的最後一個批次,而不是由函式處理。
  • remove_columns ([list[str]], optional, 預設為 None) — 在進行對映時刪除選定的列。列將在用 function 的輸出更新示例之前被刪除,即如果 function 新增的列名在 remove_columns 中,這些列將被保留。
  • fn_kwargs (Dict, 可選, 預設為 None) — 傳遞給 function 的關鍵字引數

對可迭代資料集中的所有樣本(單獨或批次)應用一個函式並進行更新。如果你的函式返回一個已存在的列,那麼它將被覆蓋。該函式在迭代資料集時動態地應用於樣本。該轉換會應用於資料集字典中的所有資料集。

您可以使用 `batched` 引數指定函式是否應批次處理。

  • 如果 `batched` 為 `False`,則函式接收 1 個示例作為輸入,並應返回 1 個示例。一個示例是一個字典,例如 `{"text": "Hello there !"}`。
  • 如果 `batched` 為 `True` 且 `batch_size` 為 1,則函式接收一個包含 1 個示例的批次作為輸入,並可以返回一個包含 1 個或多個示例的批次。一個批次是一個字典,例如,一個包含 1 個示例的批次是 `{"text": ["Hello there !"]}`。
  • 如果 batched 為 Truebatch_sizen > 1,則函式將一個包含 n 個樣本的批次作為輸入,並可以返回一個包含 n 個樣本或任意數量樣本的批次。請注意,最後一個批次可能少於 n 個樣本。一個批次是一個字典,例如一個包含 n 個樣本的批次是 {"text": ["Hello there !"] * n}

如果函式是非同步的,那麼 `map` 將並行執行您的函式,最多可同時進行一千次呼叫。如果您想設定可以同時執行的最大運算元,建議在您的函式中使用 `asyncio.Semaphore`。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> def add_prefix(example):
...     example["text"] = "Review: " + example["text"]
...     return example
>>> ds = ds.map(add_prefix)
>>> next(iter(ds["train"]))
{'label': 1,
 'text': 'Review: the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

過濾器

< >

( function: typing.Optional[typing.Callable] = None with_indices = False input_columns: typing.Union[str, list[str], NoneType] = None batched: bool = False batch_size: typing.Optional[int] = 1000 fn_kwargs: typing.Optional[dict] = None )

引數

  • function (Callable) — 具有以下簽名之一的可呼叫物件:

    • with_indices=False, batched=False 時為 function(example: Dict[str, Any]) -> bool
    • with_indices=True, batched=False 時為 function(example: Dict[str, Any], indices: int) -> bool
    • with_indices=False, batched=True 時為 function(example: Dict[str, list]) -> list[bool]
    • with_indices=True, batched=True 時為 function(example: Dict[str, list], indices: list[int]) -> list[bool]

    如果未提供函式,則預設為始終返回 True 的函式:lambda x: True

  • with_indices (bool, 預設為 False) — 向 function 提供樣本索引。注意,在這種情況下,function 的簽名應為 def function(example, idx): ...
  • input_columns (strlist[str], 可選) — 作為位置引數傳遞給 function 的列。如果為 None,則將一個對映到所有格式化列的字典作為單個引數傳遞。
  • batched (bool, 預設為 False) — 向 function 提供一批樣本。
  • batch_size (int, 可選, 預設為 1000) — 如果 batched=True,提供給 function 的每批樣本數量。
  • fn_kwargs (Dict, 可選, 預設為 None) — 傳遞給 function 的關鍵字引數。

對所有元素應用一個篩選函式,使得資料集只包含符合該篩選函式的樣本。篩選在迭代資料集時動態進行。該篩選會應用於資料集字典中的所有資料集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/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': "Review: it's so laddish and juvenile , only teenage boys could possibly find it funny ."},
 {'label': 0,
 'text': 'Review: exploitative and largely devoid of the depth or sophistication that would make watching such a graphic treatment of the crimes bearable .'}]

shuffle

< >

( seed = None generator: typing.Optional[numpy.random._generator.Generator] = None buffer_size: int = 1000 )

引數

  • seed (int, 可選, 預設為 None) — 用於打亂資料集的隨機種子。它用於從打亂緩衝區中取樣,也用於打亂資料分片。
  • generator (numpy.random.Generator, 可選) — 用於計算資料集行排列的 Numpy 隨機生成器。如果 generator=None (預設),則使用 np.random.default_rng (NumPy 的預設 BitGenerator (PCG64))。
  • buffer_size (int, 預設為 1000) — 緩衝區的大小。

隨機打亂此資料集的元素。該打亂操作會應用於資料集字典中的所有資料集。

此資料集首先用 buffer_size 個元素填充一個緩衝區,然後從該緩衝區中隨機抽樣元素,並用新元素替換被選中的元素。為了實現完美的打亂效果,緩衝區大小需要大於或等於資料集的完整大小。

例如,如果你的資料集包含 10,000 個元素,但 `buffer_size` 設定為 1000,那麼 `shuffle` 最初將僅從緩衝區中的前 1000 個元素中隨機選擇一個元素。一旦一個元素被選中,它在緩衝區中的空間將被下一個(即第 1001 個)元素替換,從而維持 1000 個元素的緩衝區。

如果資料集由多個分片組成,它也會 shuffle 分片的順序。但是,如果已使用 skip()take() 固定了順序,則分片的順序保持不變。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/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 schwarzenegger , jean-claud van damme or steven segal .'},
 {'label': 1,
 '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'}]
>>> ds = ds.shuffle(seed=42)
>>> list(ds["train"].take(3))
[{'label': 1,
 'text': "a sports movie with action that's exciting on the field and a story you care about off it ."},
 {'label': 1,
 '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 ."}]

with_format

< >

( type: typing.Optional[str] = None )

引數

  • type (str, 可選) — 在 [None, 'numpy', 'torch', 'tensorflow', 'jax', 'arrow', 'pandas', 'polars'] 中選擇的輸出型別。None 表示返回 Python 物件 (預設)。

返回一個具有指定格式的資料集。

示例

>>> from datasets import load_dataset
>>> from transformers import AutoTokenizer
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="validation", streaming=True)
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
>>> ds = ds.map(lambda x: tokenizer(x['text'], truncation=True, padding=True), batched=True)
>>> ds = ds.with_format("torch")
>>> next(iter(ds))
{'text': 'compassionately explores the seemingly irreconcilable situation between conservative christian parents and their estranged gay and lesbian children .',
 '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,     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,     0,     0,
            0,     0,     0,     0]),
 '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, 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]),
 '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,
        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])}

cast

< >

( features: Features ) IterableDatasetDict

引數

  • features (Features) — 用於轉換資料集的新特徵。特徵中欄位的名稱必須與當前的列名匹配。資料型別也必須能夠從一種型別轉換為另一種型別。對於非平凡的轉換,例如 string <-> ClassLabel,你應該使用 map 來更新資料集。

返回

IterableDatasetDict

一份具有轉換後特徵的資料集副本。

將資料集轉換為一組新的特徵。型別轉換會應用於資料集字典中的所有資料集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds["train"].features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> new_features = ds["train"].features.copy()
>>> new_features['label'] = ClassLabel(names=['bad', 'good'])
>>> new_features['text'] = Value('large_string')
>>> ds = ds.cast(new_features)
>>> ds["train"].features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('large_string')}

cast_column

< >

( column: str feature: typing.Union[dict, list, tuple, datasets.features.features.Value, datasets.features.features.ClassLabel, datasets.features.translation.Translation, datasets.features.translation.TranslationVariableLanguages, datasets.features.features.LargeList, datasets.features.features.List, datasets.features.features.Array2D, datasets.features.features.Array3D, datasets.features.features.Array4D, datasets.features.features.Array5D, datasets.features.audio.Audio, datasets.features.image.Image, datasets.features.video.Video, datasets.features.pdf.Pdf] )

引數

  • column (str) — 列名。
  • feature (Feature) — 目標特徵。

將列轉換為特徵以進行解碼。型別轉換會應用於資料集字典中的所有資料集。

示例

>>> from datasets import load_dataset, ClassLabel
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds["train"].features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}
>>> ds = ds.cast_column('label', ClassLabel(names=['bad', 'good']))
>>> ds["train"].features
{'label': ClassLabel(names=['bad', 'good']),
 'text': Value('string')}

remove_columns

< >

( column_names: typing.Union[str, list[str]] ) IterableDatasetDict

引數

  • column_names (Union[str, list[str]]) — 要移除的列的名稱。

返回

IterableDatasetDict

移除了指定列的資料集物件副本。

移除資料集中的一列或多列以及與之相關的特徵。移除操作在迭代資料集時動態地對樣本進行。該移除會應用於資料集字典中的所有資料集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds = ds.remove_columns("label")
>>> next(iter(ds["train"]))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

rename_column

< >

( original_column_name: str new_column_name: str ) IterableDatasetDict

引數

  • original_column_name (str) — 要重新命名的列的名稱。
  • new_column_name (str) — 列的新名稱。

返回

IterableDatasetDict

一列已重新命名的資料集副本。

重新命名資料集中的一列,並將與原始列關聯的特徵移到新列名下。重新命名操作會應用於資料集字典中的所有資料集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds = ds.rename_column("text", "movie_review")
>>> next(iter(ds["train"]))
{'label': 1,
 'movie_review': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

rename_columns

< >

( column_mapping: dict ) IterableDatasetDict

引數

  • column_mapping (Dict[str, str]) — 一個將要重新命名的列對映到其新名稱的字典。

返回

IterableDatasetDict

列已重新命名的資料集副本

重新命名資料集中的多列,並將與原始列關聯的特徵移到新列名下。重新命名操作會應用於資料集字典中的所有資料集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds = ds.rename_columns({"text": "movie_review", "label": "rating"})
>>> next(iter(ds["train"]))
{'movie_review': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .',
 'rating': 1}

select_columns

< >

( column_names: typing.Union[str, list[str]] ) IterableDatasetDict

引數

  • column_names (Union[str, list[str]]) — 要保留的列的名稱。

返回

IterableDatasetDict

一個只包含所選列的資料集物件的副本。

選擇資料集中的一列或多列以及與之相關的特徵。選擇操作在迭代資料集時動態地對樣本進行。該選擇會應用於資料集字典中的所有資料集。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", streaming=True)
>>> ds = ds.select("text")
>>> next(iter(ds["train"]))
{'text': 'the rock is destined to be the 21st century's new " conan " and that he's going to make a splash even greater than arnold schwarzenegger , jean-claud van damme or steven segal .'}

push_to_hub

< >

( repo_id config_name: str = 'default' set_default: typing.Optional[bool] = None data_dir: typing.Optional[str] = None commit_message: typing.Optional[str] = None commit_description: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Optional[str] = None revision: typing.Optional[str] = None create_pr: typing.Optional[bool] = False num_shards: typing.Optional[dict[str, int]] = None embed_external_files: bool = True num_proc: typing.Optional[int] = None )

引數

  • repo_id (str) — 要推送到的儲存庫的 ID,格式如下:<user>/<dataset_name><org>/<dataset_name>。也接受 <dataset_name>,它將預設為已登入使用者的名稱空間。
  • config_name (str) — 資料集的配置名稱。預設為“default”。
  • set_default (bool, 可選) — 是否將此配置設定為預設配置。否則,預設配置是名為“default”的配置。
  • data_dir (str, 可選) — 將包含上傳資料檔案的目錄名稱。如果 `config_name` 與 “default” 不同,則預設為 `config_name`,否則為 “data”。

    2.17.0 版本中新增

  • commit_message (str, 可選) — 推送時要提交的訊息。將預設為 "Upload dataset"
  • commit_description (str, 可選) — 將要建立的提交的描述。此外,如果建立了 PR (create_pr 為 True),則為 PR 的描述。

    2.16.0 版本中新增

  • private (bool, 可選) — 是否將儲存庫設為私有。如果為 None (預設),除非組織的預設設定為私有,否則儲存庫將是公開的。如果儲存庫已存在,則忽略此值。
  • token (str, 可選) — Hugging Face Hub 的可選身份驗證令牌。如果未傳遞令牌,將預設為使用 huggingface-cli login 登入時本地儲存的令牌。如果未傳遞令牌且使用者未登入,將引發錯誤。
  • revision (str, 可選) — 將上傳檔案推送到的分支。預設為 "main" 分支。
  • create_pr (bool, 可選, 預設為 False) — 是建立帶有上傳檔案的 PR 還是直接提交。
  • num_shards (Dict[str, int], 可選) — 要寫入的分片數量。預設等於此資料集的 .num_shards。使用字典為每個拆分定義不同的 num_shards。
  • embed_external_files (bool, 預設為 True) — 是否在分片中嵌入檔案位元組。特別是,這將在推送前對以下型別的欄位執行以下操作:

    • AudioImage 會移除本地路徑資訊並在 Parquet 檔案中嵌入檔案內容。
  • num_proc (int, 可選, 預設為 None) — 準備和上傳資料集時的程序數。如果資料集由許多樣本或要嵌入的媒體檔案組成,這將很有幫助。預設情況下停用多程序。

    4.0.0 版本中新增

DatasetDict 作為 Parquet 資料集推送到 Hub。DatasetDict 使用 HTTP 請求推送,不需要安裝 git 或 git-lfs。

每個資料集分割將獨立推送。推送的資料集將保留原始的分割名稱。

預設情況下,生成的 Parquet 檔案是自包含的:如果您的資料集包含 ImageAudio 資料,Parquet 檔案將儲存您的影像或音訊檔案的位元組。您可以透過將 embed_external_files 設定為 False 來停用此功能。

示例

>>> 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>", num_shards={"train": 1024, "test": 8})

如果您想向資料集新增新的配置(或子集)(例如,如果資料集有多個任務/版本/語言)

>>> 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>/<dataset_id>", "fr")

特徵

class datasets.Features

< >

( *args **kwargs )

一種特殊的字典,用於定義資料集的內部結構。

使用 dict[str, FieldType] 型別的字典進行例項化,其中鍵是所需的列名,值是該列的型別。

FieldType 可以是以下之一:

  • Value 特徵指定單個數據型別值,例如 int64string
  • ClassLabel 特徵指定一組預定義的類別,這些類別可以有關聯的標籤,並在資料集中作為整數儲存。
  • Python dict 指定一個複合特徵,其中包含子欄位到子特徵的對映。可以以任意方式巢狀欄位。
  • ListLargeList 指定一個複合特徵,其中包含一系列相同特徵型別的子特徵。
  • Array2DArray3DArray4DArray5D 特徵用於多維陣列。
  • Audio 特徵用於儲存音訊檔案的絕對路徑或一個包含音訊檔案相對路徑(“path”鍵)及其位元組內容(“bytes”鍵)的字典。此特徵使用解碼器延遲載入音訊。
  • Image 特徵用於儲存影像檔案的絕對路徑、一個 np.ndarray 物件、一個 PIL.Image.Image 物件或一個包含影像檔案相對路徑(“path”鍵)及其位元組內容(“bytes”鍵)的字典。此特徵會提取影像資料。
  • Video 特徵用於儲存影片檔案的絕對路徑、一個 torchcodec.decoders.VideoDecoder 物件或一個包含影片檔案相對路徑(“path”鍵)及其位元組內容(“bytes”鍵)的字典。此特徵使用解碼器延遲載入影片。
  • Pdf 特徵用於儲存 PDF 檔案的絕對路徑、一個 pdfplumber.pdf.PDF 物件或一個包含 PDF 檔案相對路徑(“path”鍵)及其位元組內容(“bytes”鍵)的字典。此特徵使用 PDF 閱讀器延遲載入 PDF。
  • TranslationTranslationVariableLanguages 特徵專用於機器翻譯。

複製

< >

( )

Features 進行深複製。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> copy_of_features = ds.features.copy()
>>> copy_of_features
{'label': ClassLabel(names=['neg', 'pos']),
 'text': Value('string')}

decode_batch

< >

( batch: dict token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )

引數

  • batch (dict[str, list[Any]]) — 資料集批次資料。
  • token_per_repo_id (dict, 可選) — 要從 Hub 上的私有倉庫訪問和解碼音訊或影像檔案,你可以傳遞一個字典 repo_id (str) -> token (bool or str)

使用自定義特徵解碼來解碼批次。

decode_column

< >

( column: list column_name: str token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )

引數

  • column (list[Any]) — 資料集列資料。
  • column_name (str) — 資料集列名。

使用自定義特徵解碼來解碼列。

decode_example

< >

( example: dict token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )

引數

  • example (dict[str, Any]) — 資料集行資料。
  • token_per_repo_id (dict, optional) — 要從 Hub 上的私有倉庫訪問和解碼音訊或影像檔案,您可以傳遞一個字典 repo_id (str) -> token (bool or str)

使用自定義特徵解碼來解碼樣本。

encode_batch

< >

( batch )

引數

  • batch (dict[str, list[Any]]) — 資料集批次中的資料。

將批次編碼為 Arrow 格式。

encode_column

< >

( column column_name: str )

引數

  • column (list[Any]) — 資料集列中的資料。
  • column_name (str) — 資料集列名。

將列編碼為 Arrow 格式。

encode_example

< >

( example )

引數

  • example (dict[str, Any]) — 資料集行中的資料。

將樣本編碼為 Arrow 格式。

flatten

< >

( max_depth = 16 ) Features

返回

功能

展平後的特徵。

展平特徵。每個字典列都將被移除,並由其包含的所有子欄位替換。新欄位的命名方式是透過連線原始列名和子欄位名,格式為:<original>.<subfield>

如果一列包含巢狀字典,那麼所有更深層次的子欄位名也會被連線起來形成新列,例如:<original>.<subfield>.<subsubfield> 等。

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("rajpurkar/squad", split="train")
>>> ds.features.flatten()
{'answers.answer_start': List(Value('int32'), id=None),
 'answers.text': List(Value('string'), id=None),
 'context': Value('string'),
 'id': Value('string'),
 'question': Value('string'),
 'title': Value('string')}

from_arrow_schema

< >

( pa_schema: Schema )

引數

  • pa_schema (pyarrow.Schema) — Arrow 模式。

從 Arrow 模式構建 Features。它還會檢查模式元資料中是否包含 Hugging Face Datasets 的特徵資訊。不支援不可為空的欄位,並會將其設定為可為空。

此外,不支援 pa.dictionary,而是使用其底層型別。因此,datasets 會將 DictionaryArray 物件轉換為它們的實際值。

from_dict

< >

( dic ) Features

引數

  • dic (dict[str, Any]) — Python 字典。

返回

功能

從字典構建 [Features]。

從反序列化的字典中重新生成巢狀的特徵物件。我們使用 _type 鍵來推斷特徵 FieldType 的資料類名稱。

這允許使用一種方便的建構函式語法,從反序列化的 JSON 字典中定義特徵。該函式特別用於反序列化已轉儲為 JSON 物件的 [DatasetInfo]。它類似於 [Features.from_arrow_schema],處理遞迴的逐欄位例項化,但不需要任何與 pyarrow 的對映,除了它利用了 [Value] 自動執行的 pyarrow 原始資料型別的對映。

示例

>>> Features.from_dict({'_type': {'dtype': 'string', 'id': None, '_type': 'Value'}})
{'_type': Value('string')}

reorder_fields_as

< >

( other: Features )

引數

  • other ([Features]) — 用於對齊的另一個 [Features] 物件。

重新排序 Features 欄位以匹配另一個 [Features] 的欄位順序。

欄位的順序很重要,因為它會影響底層的 Arrow 資料。重新排序欄位可以使底層的 Arrow 資料型別匹配。

示例

>>> from datasets import Features, List, Value
>>> # let's say we have two features with a different order of nested fields (for a and b for example)
>>> f1 = Features({"root": {"a": Value("string"), "b": Value("string")}})
>>> f2 = Features({"root": {"b": Value("string"), "a": Value("string")}})
>>> assert f1.type != f2.type
>>> # re-ordering keeps the base structure (here List is defined at the root level), but makes the fields order match
>>> f1.reorder_fields_as(f2)
{'root': List({'b': Value('string'), 'a': Value('string')})}
>>> assert f1.reorder_fields_as(f2).type == f2.type

標量

class datasets.Value

< >

( dtype: str id: typing.Optional[str] = None )

引數

  • dtype (str) — 資料型別的名稱。

特定資料型別的標量特徵值。

Value 可能的資料型別如下

  • null
  • 布林值
  • int8
  • int16
  • int32
  • int64
  • uint8
  • uint16
  • uint32
  • uint64
  • float16
  • float32 (別名 float)
  • float64 (別名 double)
  • time32[(s|ms)]
  • time64[(us|ns)]
  • timestamp[(s|ms|us|ns)]
  • timestamp[(s|ms|us|ns), tz=(tzstring)]
  • date32
  • date64
  • duration[(s|ms|us|ns)]
  • decimal128(precision, scale)
  • decimal256(precision, scale)
  • binary
  • large_binary
  • 字串
  • large_string

示例

>>> from datasets import Features
>>> features = Features({'stars': Value('int32')})
>>> features
{'stars': Value('int32')}

class datasets.ClassLabel

< >

( num_classes: dataclasses.InitVar[typing.Optional[int]] = None names: list = None names_file: dataclasses.InitVar[typing.Optional[str]] = None id: typing.Optional[str] = None )

引數

  • num_classes (int, optional) — 類別數量。所有標籤必須 < num_classes
  • names (list of str, optional) — 整數類別的字串名稱。提供的名稱順序將被保留。
  • names_file (str, optional) — 包含整數類別名稱的檔案路徑,每行一個。

整數類別標籤的特徵型別。

有 3 種方式定義 ClassLabel,對應 3 個引數

  • num_classes: 建立從 0 到 (num_classes-1) 的標籤。
  • names: 標籤字串列表。
  • names_file: 包含標籤列表的檔案。

在底層,標籤以整數形式儲存。您可以使用負整數來表示未知/缺失的標籤。

示例

>>> from datasets import Features, ClassLabel
>>> features = Features({'label': ClassLabel(num_classes=3, names=['bad', 'ok', 'good'])})
>>> features
{'label': ClassLabel(names=['bad', 'ok', 'good'])}

cast_storage

< >

( storage: typing.Union[pyarrow.lib.StringArray, pyarrow.lib.IntegerArray] ) pa.Int64Array

引數

  • storage (Union[pa.StringArray, pa.IntegerArray]) — 要轉換的 PyArrow 陣列。

返回

pa.Int64Array

ClassLabel Arrow 儲存型別中的陣列。

將 Arrow 陣列轉換為 ClassLabel Arrow 儲存型別。可以轉換為 ClassLabel pyarrow 儲存型別的 Arrow 型別有

  • pa.string()
  • pa.int()

int2str

< >

( values: typing.Union[int, collections.abc.Iterable] )

轉換 integer => 類別名稱 string

關於未知/缺失標籤:傳遞負整數會引發 ValueError

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> ds.features["label"].int2str(0)
'neg'

str2int

< >

( values: typing.Union[str, collections.abc.Iterable] )

轉換類別名稱 string => integer

示例

>>> from datasets import load_dataset
>>> ds = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> ds.features["label"].str2int('neg')
0

複合型別

class datasets.LargeList

< >

( feature: typing.Any id: typing.Optional[str] = None )

引數

  • feature (FeatureType) — 大列表內每個子項的特徵資料型別。

由子特徵資料型別組成的大列表資料的特徵型別。

它由 pyarrow.LargeListType 支援,類似於 pyarrow.ListType,但使用 64 位偏移量而非 32 位。

class datasets.List

< >

( feature: typing.Any length: int = -1 id: typing.Optional[str] = None )

引數

  • feature (FeatureType) — 列表內每個子項的特徵資料型別。
  • length (optional int, default to -1) — 如果列表長度固定,則為列表的長度。預設為 -1,表示任意長度。

由子特徵資料型別組成的大列表資料的特徵型別。

它由 pyarrow.ListType 支援,使用 32 位偏移量或固定長度。

class datasets.Sequence

< >

( feature = None length = -1 **kwargs )

引數

  • feature (FeatureType) — 列表內每個子項的特徵資料型別。
  • length (optional int, default to -1) — 如果列表長度固定,則為列表的長度。預設為 -1,表示任意長度。

Sequence 是一個實用工具,可自動將內部的字典特徵轉換為列表的字典。此行為是為了與 TensorFlow Datasets 庫相容而實現的,但在某些情況下可能不需要。如果您不希望有此行為,可以使用 ListLargeList 來代替 Sequence

翻譯

class datasets.Translation

< >

( languages: list id: typing.Optional[str] = None )

引數

  • languages (dict) — 每個樣本的字典,將字串語言程式碼對映到字串翻譯。

用於每個樣本具有固定語言的翻譯的 Feature。此處是為了與 tfds 相容。

示例

>>> # At construction time:
>>> datasets.features.Translation(languages=['en', 'fr', 'de'])
>>> # During data generation:
>>> yield {
...         'en': 'the cat',
...         'fr': 'le chat',
...         'de': 'die katze'
... }

flatten

< >

( )

將 Translation 特徵展平為字典。

class datasets.TranslationVariableLanguages

< >

( languages: typing.Optional[list] = None num_languages: typing.Optional[int] = None id: typing.Optional[str] = None )

  • languagetranslation (可變長度的一維 tf.Tensor,型別為 tf.string)

引數

  • languages (dict) — 每個樣本的字典,將字串語言程式碼對映到一個或多個字串翻譯。不同樣本中的語言可能會有所不同。

返回

  • languagetranslation (可變長度的一維 tf.Tensor,型別為 tf.string)

按升序排序的語言程式碼或純文字翻譯,排序後與語言程式碼對齊。

用於每個樣本具有可變語言的翻譯的 Feature。此處是為了與 tfds 相容。

示例

>>> # At construction time:
>>> datasets.features.TranslationVariableLanguages(languages=['en', 'fr', 'de'])
>>> # During data generation:
>>> yield {
...         'en': 'the cat',
...         'fr': ['le chat', 'la chatte,']
...         'de': 'die katze'
... }
>>> # Tensor returned :
>>> {
...         'language': ['en', 'de', 'fr', 'fr'],
...         'translation': ['the cat', 'die katze', 'la chatte', 'le chat'],
... }

flatten

< >

( )

將 TranslationVariableLanguages 特徵展平為字典。

陣列

class datasets.Array2D

< >

( shape: tuple dtype: str id: typing.Optional[str] = None )

引數

  • shape (tuple) — 每個維度的大小。
  • dtype (str) — 資料型別的名稱。

建立一個二維陣列。

示例

>>> from datasets import Features
>>> features = Features({'x': Array2D(shape=(1, 3), dtype='int32')})

class datasets.Array3D

< >

( shape: tuple dtype: str id: typing.Optional[str] = None )

引數

  • shape (tuple) — 每個維度的大小。
  • dtype (str) — 資料型別的名稱。

建立一個三維陣列。

示例

>>> from datasets import Features
>>> features = Features({'x': Array3D(shape=(1, 2, 3), dtype='int32')})

class datasets.Array4D

< >

( shape: tuple dtype: str id: typing.Optional[str] = None )

引數

  • shape (tuple) — 每個維度的大小。
  • dtype (str) — 資料型別的名稱。

建立一個四維陣列。

示例

>>> from datasets import Features
>>> features = Features({'x': Array4D(shape=(1, 2, 2, 3), dtype='int32')})

class datasets.Array5D

< >

( shape: tuple dtype: str id: typing.Optional[str] = None )

引數

  • shape (tuple) — 每個維度的大小。
  • dtype (str) — 資料型別的名稱。

建立一個五維陣列。

示例

>>> from datasets import Features
>>> features = Features({'x': Array5D(shape=(1, 2, 2, 3, 3), dtype='int32')})

Audio

class datasets.Audio

< >

( sampling_rate: typing.Optional[int] = None decode: bool = True stream_index: typing.Optional[int] = None id: typing.Optional[str] = None )

引數

  • sampling_rate (int, 可選) — 目標取樣率。如果為 None,則使用原始取樣率。
  • mono (bool, 預設為 True) — 是否透過對各通道樣本求平均值將音訊訊號轉換為單聲道。
  • decode (bool, 預設為 True) — 是否解碼音訊資料。如果為 False,則返回底層字典,格式為 {"path": audio_path, "bytes": audio_bytes}
  • stream_index (int, 可選) — 要從檔案中使用的流索引。如果為 None,則預設為“最佳”索引。

Audio Feature (音訊特徵) 用於從音訊檔案中提取音訊資料。

輸入:音訊特徵接受以下輸入

  • 一個 str:音訊檔案的絕對路徑(即允許隨機訪問)。

  • 一個包含以下鍵的 dict

    • path:字串,表示音訊檔案相對於歸檔檔案的路徑。
    • bytes:音訊檔案的位元組內容。

    這對於嵌入音訊檔案的 parquet 或 webdataset 檔案很有用。

  • 一個包含以下鍵的 dict

    • array:包含音訊樣本的陣列
    • sampling_rate:對應音訊樣本取樣率的整數。
  • 一個 torchcodec.decoders.AudioDecoder:torchcodec 音訊解碼器物件。

輸出:音訊特徵以 torchcodec.decoders.AudioDecoder 物件的形式輸出資料,並附帶額外的鍵

  • array:包含音訊樣本的陣列
  • sampling_rate:對應音訊樣本取樣率的整數。

示例

>>> from datasets import load_dataset, Audio
>>> ds = load_dataset("PolyAI/minds14", name="en-US", split="train")
>>> ds = ds.cast_column("audio", Audio(sampling_rate=44100))
>>> ds[0]["audio"]
<datasets.features._torchcodec.AudioDecoder object at 0x11642b6a0>
>>> audio = ds[0]["audio"]
>>> audio.get_samples_played_in_range(0, 10)
AudioSamples:
    data (shape): torch.Size([2, 110592])
    pts_seconds: 0.0
    duration_seconds: 2.507755102040816
    sample_rate: 44100

cast_storage

< >

( storage: typing.Union[pyarrow.lib.StringArray, pyarrow.lib.StructArray] ) pa.StructArray

引數

  • storage (Union[pa.StringArray, pa.StructArray]) — 要轉換的 PyArrow 陣列。

返回

pa.StructArray

Audio Arrow 儲存型別的陣列,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

將 Arrow 陣列轉換為 Audio Arrow 儲存型別。可轉換為 Audio PyArrow 儲存型別的 Arrow 型別包括:

  • pa.string() - 必須包含 "path" 資料
  • pa.binary() - 必須包含音訊位元組資料
  • pa.struct({"bytes": pa.binary()})
  • pa.struct({"path": pa.string()})
  • pa.struct({"bytes": pa.binary(), "path": pa.string()}) - 順序無關

decode_example

< >

( value: dict token_per_repo_id: typing.Optional[dict[str, typing.Union[str, bool, NoneType]]] = None )

引數

  • value (dict) — 一個包含以下鍵的字典:

    • path: 包含相對音訊檔案路徑的字串。
    • bytes: 音訊檔案的位元組內容。
  • token_per_repo_id (dict, 可選) — 要訪問和解碼來自 Hub 上私有倉庫的音訊檔案,您可以傳遞一個 repo_id (str) -> token (boolstr) 的字典。

將示例音訊檔案解碼為音訊資料。

embed_storage

< >

( storage: StructArray token_per_repo_id = None ) pa.StructArray

引數

  • storage (pa.StructArray) — 要嵌入的 PyArrow 陣列。

返回

pa.StructArray

Audio Arrow 儲存型別的陣列,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

將音訊檔案嵌入到 Arrow 陣列中。

encode_example

< >

( value: typing.Union[str, bytes, bytearray, dict, ForwardRef('AudioDecoder')] ) dict

引數

  • value (str, bytes,bytearray,dict, AudioDecoder) — 作為輸入傳遞給 Audio 特徵的資料。

返回

字典

將樣本編碼為 Arrow 格式。

flatten

< >

( )

如果處於可解碼狀態,則引發錯誤,否則將特徵展平為字典。

Image

class datasets.Image

< >

( mode: typing.Optional[str] = None decode: bool = True id: typing.Optional[str] = None )

引數

  • mode (str, 可選) — 影像轉換的目標模式。如果為 None,則使用影像的原始模式。
  • decode (bool, 預設為 True) — 是否解碼影像資料。如果為 False,則返回底層字典,格式為 {"path": image_path, "bytes": image_bytes}

Image Feature (影像特徵) 用於從影像檔案中讀取影像資料。

輸入:影像特徵接受以下輸入

  • 一個 str:影像檔案的絕對路徑(即允許隨機訪問)。

  • 一個包含以下鍵的 dict

    • path:字串,表示影像檔案相對於歸檔檔案的路徑。
    • bytes:影像檔案的位元組內容。

    這對於嵌入影像檔案的 parquet 或 webdataset 檔案很有用。

  • 一個 np.ndarray:表示影像的 NumPy 陣列。

  • 一個 PIL.Image.Image:PIL 影像物件。

輸出:影像特徵以 PIL.Image.Image 物件的形式輸出資料。

示例

>>> from datasets import load_dataset, Image
>>> ds = load_dataset("AI-Lab-Makerere/beans", split="train")
>>> ds.features["image"]
Image(decode=True, id=None)
>>> ds[0]["image"]
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=500x500 at 0x15E52E7F0>
>>> ds = ds.cast_column('image', Image(decode=False))
{'bytes': None,
 'path': '/root/.cache/huggingface/datasets/downloads/extracted/b0a21163f78769a2cf11f58dfc767fb458fc7cea5c05dccc0144a2c0f0bc1292/train/healthy/healthy_train.85.jpg'}

cast_storage

< >

( storage: typing.Union[pyarrow.lib.StringArray, pyarrow.lib.StructArray, pyarrow.lib.ListArray] ) pa.StructArray

引數

  • storage (Union[pa.StringArray, pa.StructArray, pa.ListArray]) — 要轉換的 PyArrow 陣列。

返回

pa.StructArray

Image Arrow 儲存型別的陣列,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

將 Arrow 陣列轉換為 Image Arrow 儲存型別。可轉換為 Image PyArrow 儲存型別的 Arrow 型別包括:

  • pa.string() - 必須包含 "path" 資料
  • pa.binary() - 必須包含影像位元組資料
  • pa.struct({"bytes": pa.binary()})
  • pa.struct({"path": pa.string()})
  • pa.struct({"bytes": pa.binary(), "path": pa.string()}) - 順序無關
  • pa.list(*) - 必須包含影像陣列資料

decode_example

< >

( value: dict token_per_repo_id = None )

引數

  • value (strdict) — 一個包含影像檔案絕對路徑的字串,或一個包含以下鍵的字典:

    • path: 包含絕對或相對影像檔案路徑的字串。
    • bytes: 影像檔案的位元組內容。
  • token_per_repo_id (dict, 可選) — 要訪問和解碼來自 Hub 上私有倉庫的影像檔案,您可以傳遞一個 repo_id (str) -> token (boolstr) 的字典。

將示例影像檔案解碼為影像資料。

embed_storage

< >

( storage: StructArray token_per_repo_id = None ) pa.StructArray

引數

  • storage (pa.StructArray) — 要嵌入的 PyArrow 陣列。

返回

pa.StructArray

Image Arrow 儲存型別的陣列,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

將影像檔案嵌入到 Arrow 陣列中。

encode_example

< >

( value: typing.Union[str, bytes, bytearray, dict, numpy.ndarray, ForwardRef('PIL.Image.Image')] )

引數

  • value (str, np.ndarray, PIL.Image.Imagedict) — 作為輸入傳遞給 Image 特徵的資料。

將樣本編碼為 Arrow 格式。

flatten

< >

( )

如果處於可解碼狀態,則返回特徵本身,否則將特徵展平為字典。

Video

class datasets.Video

< >

( decode: bool = True stream_index: typing.Optional[int] = None dimension_order: typing.Literal['NCHW', 'NHWC'] = 'NCHW' num_ffmpeg_threads: int = 1 device: typing.Union[str, ForwardRef('torch.device'), NoneType] = 'cpu' seek_mode: typing.Literal['exact', 'approximate'] = 'exact' id: typing.Optional[str] = None )

引數

  • mode (str, 可選) — 影片轉換的目標模式。如果為 None,則使用影片的原始模式。
  • decode (bool, 預設為 True) — 是否解碼影片資料。如果為 False,則返回底層字典,格式為 {"path": video_path, "bytes": video_bytes}
  • stream_index (int, 可選) — 要從檔案中使用的流索引。如果為 None,則預設為“最佳”索引。
  • dimension_order (str, 預設為 NCHW) — 解碼幀的維度順序。其中 N 是批次大小,C 是通道數,H 是高度,W 是幀的寬度。
  • num_ffmpeg_threads (int, 預設為 1) — 用於解碼影片的執行緒數。(建議保持為 1)
  • device (strtorch.device, 預設為 cpu) — 用於解碼影片的裝置。
  • seek_mode (str, 預設為 exact) — 決定幀訪問是“精確”還是“近似”。精確模式保證請求幀 i 總是返回幀 i,但這需要對檔案進行初始掃描。近似模式速度更快,因為它避免了掃描檔案,但準確性較低,因為它使用檔案的元資料來計算 i 可能的位置。更多資訊請閱讀這裡

Video Feature (影片特徵) 用於從影片檔案中讀取影片資料。

輸入:影片特徵接受以下輸入

  • 一個 str:影片檔案的絕對路徑(即允許隨機訪問)。

  • 一個包含以下鍵的 dict

    • path:字串,表示影片檔案在資料集倉庫中的相對路徑。
    • bytes:影片檔案的位元組內容。

    這對於嵌入影片檔案的 parquet 或 webdataset 檔案很有用。

  • 一個 torchcodec.decoders.VideoDecoder:torchcodec 影片解碼器物件。

輸出:影片特徵以 torchcodec.decoders.VideoDecoder 物件的形式輸出資料。

示例

>>> from datasets import Dataset, Video
>>> ds = Dataset.from_dict({"video":["path/to/Screen Recording.mov"]}).cast_column("video", Video())
>>> ds.features["video"]
Video(decode=True, id=None)
>>> ds[0]["video"]
<torchcodec.decoders._video_decoder.VideoDecoder object at 0x14a61e080>
>>> video = ds[0]["video"]
>>> video.get_frames_in_range(0, 10)
FrameBatch:
data (shape): torch.Size([10, 3, 50, 66])
pts_seconds: tensor([0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333, 0.4333,
        0.4333], dtype=torch.float64)
duration_seconds: tensor([0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167, 0.0167,
        0.0167], dtype=torch.float64)
>>> ds.cast_column('video', Video(decode=False))[0]["video]
{'bytes': None,
 'path': 'path/to/Screen Recording.mov'}

cast_storage

< >

( storage: typing.Union[pyarrow.lib.StringArray, pyarrow.lib.StructArray, pyarrow.lib.ListArray] ) pa.StructArray

引數

  • storage (Union[pa.StringArray, pa.StructArray, pa.ListArray]) — 要轉換的 PyArrow 陣列。

返回

pa.StructArray

Video Arrow 儲存型別的陣列,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

將 Arrow 陣列轉換為 Video Arrow 儲存型別。可轉換為 Video PyArrow 儲存型別的 Arrow 型別包括:

  • pa.string() - 必須包含 "path" 資料
  • pa.binary() - 必須包含影片位元組資料
  • pa.struct({"bytes": pa.binary()})
  • pa.struct({"path": pa.string()})
  • pa.struct({"bytes": pa.binary(), "path": pa.string()}) - 順序無關
  • pa.list(*) - 必須包含影片陣列資料

decode_example

< >

( value: typing.Union[str, datasets.features.video.Example] token_per_repo_id: typing.Optional[dict[str, typing.Union[bool, str]]] = None )

引數

  • value (strdict) — 包含影片檔案絕對路徑的字串,或包含以下鍵的字典:

    • path: 包含影片檔案絕對或相對路徑的字串。
    • bytes: 影片檔案的位元組。
  • token_per_repo_id (dict, 可選) — 要從 Hub 上的私有倉庫訪問和解碼影片檔案,你可以傳遞一個 repo_id (str) -> token (boolstr) 的字典。

將示例影片檔案解碼為影片資料。

encode_example

< >

( value: typing.Union[str, bytes, bytearray, datasets.features.video.Example, numpy.ndarray, ForwardRef('VideoDecoder')] )

引數

  • value (str, np.ndarray, bytes, bytearray, VideoDecoderdict) — 傳遞給影片特徵作為輸入的資料。

將樣本編碼為 Arrow 格式。

flatten

< >

( )

如果處於可解碼狀態,則返回特徵本身,否則將特徵展平為字典。

Pdf

class datasets.Pdf

< >

( decode: bool = True id: typing.Optional[str] = None )

引數

  • mode (str, 可選) — 轉換 pdf 的模式。如果為 None,則使用 pdf 的原生模式。
  • decode (bool, 預設為 True) — 是否解碼 pdf 資料。如果為 False,則返回格式為 {"path": pdf_path, "bytes": pdf_bytes} 的底層字典。

實驗性功能。 用於從 pdf 檔案中讀取 pdf 文件的 Pdf Feature

輸入:Pdf 特徵接受以下輸入

  • 一個 str:pdf 檔案的絕對路徑(即允許隨機訪問)。

  • 一個包含以下鍵的 dict

    • path:資料倉庫中 pdf 檔案的相對路徑字串。
    • bytes:pdf 檔案的位元組。這對於具有順序訪問的歸檔檔案很有用。
  • 一個 pdfplumber.pdf.PDF:pdfplumber pdf 物件。

示例

>>> from datasets import Dataset, Pdf
>>> ds = Dataset.from_dict({"pdf": ["path/to/pdf/file.pdf"]}).cast_column("pdf", Pdf())
>>> ds.features["pdf"]
Pdf(decode=True, id=None)
>>> ds[0]["pdf"]
<pdfplumber.pdf.PDF object at 0x7f8a1c2d8f40>
>>> ds = ds.cast_column("pdf", Pdf(decode=False))
>>> ds[0]["pdf"]
{'bytes': None,
'path': 'path/to/pdf/file.pdf'}

cast_storage

< >

( storage: typing.Union[pyarrow.lib.StringArray, pyarrow.lib.StructArray, pyarrow.lib.ListArray] ) pa.StructArray

引數

  • storage (Union[pa.StringArray, pa.StructArray, pa.ListArray]) — 要轉換的 PyArrow 陣列。

返回

pa.StructArray

Pdf arrow 儲存型別中的陣列,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

將 Arrow 陣列轉換為 Pdf arrow 儲存型別。可以轉換為 Pdf pyarrow 儲存型別的 Arrow 型別有

  • pa.string() - 必須包含 "path" 資料
  • pa.binary() - 必須包含影像位元組資料
  • pa.struct({"bytes": pa.binary()})
  • pa.struct({"path": pa.string()})
  • pa.struct({"bytes": pa.binary(), "path": pa.string()}) - 順序無關
  • pa.list(*) - 它必須包含 pdf 陣列資料

decode_example

< >

( value: dict token_per_repo_id = None )

引數

  • value (strdict) — 包含 pdf 檔案絕對路徑的字串,或包含以下鍵的字典:

    • path: 包含 pdf 檔案絕對或相對路徑的字串。
    • bytes: pdf 檔案的位元組。
  • token_per_repo_id (dict, 可選) — 要從 Hub 上的私有倉庫訪問和解碼 pdf 檔案,你可以傳遞一個 repo_id (str) -> token (boolstr) 的字典。

將示例 pdf 檔案解碼為 pdf 資料。

embed_storage

< >

( storage: StructArray token_per_repo_id = None ) pa.StructArray

引數

  • storage (pa.StructArray) — 要嵌入的 PyArrow 陣列。

返回

pa.StructArray

PDF arrow 儲存型別中的陣列,即 pa.struct({"bytes": pa.binary(), "path": pa.string()})

將 PDF 檔案嵌入到 Arrow 陣列中。

encode_example

< >

( value: typing.Union[str, bytes, bytearray, dict, ForwardRef('pdfplumber.pdf.PDF')] )

引數

  • value (str, bytes, pdfplumber.pdf.PDFdict) — 傳遞給 Pdf 特徵作為輸入的資料。

將樣本編碼為 Arrow 格式。

flatten

< >

( )

如果處於可解碼狀態,則返回特徵本身,否則將特徵展平為字典。

檔案系統

datasets.filesystems.is_remote_filesystem

< >

( fs: AbstractFileSystem )

引數

  • fs (fsspec.spec.AbstractFileSystem) — Pythonic 檔案系統的抽象超類,例如 fsspec.filesystem('file')s3fs.S3FileSystem

檢查 fs 是否為遠端檔案系統。

指紋

class datasets.fingerprint.Hasher

< >

( )

接受 python 物件作為輸入的雜湊器。

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.