Datasets documentation
데이터셋 이해하기
데이터셋 이해하기
데이터셋 객체는 일반 Dataset과 ✨ IterableDataset ✨ 두 가지 유형이 있습니다. Dataset은 행에 대한 빠른 랜덤 액세스와 메모리 매핑을 제공하여, 큰 데이터셋을 로드해도 상대적으로 적은 양의 디바이스 메모리만 사용합니다. 그러나 디스크나 메모리에조차 담기지 않을 정도로 정말로 큰 데이터셋의 경우, IterableDataset을 사용하면 완전히 다운로드될 때까지 기다리지 않고도 데이터셋에 액세스하고 사용할 수 있습니다!
이 튜토리얼에서는 Dataset과 IterableDataset을 로드하고 액세스하는 방법을 보여줍니다.
데이터셋
데이터셋 스플릿을 로드하면 Dataset 객체를 얻습니다. Dataset 객체로는 다양한 작업을 수행할 수 있으므로, 내부에 저장된 데이터를 조작하고 상호작용하는 방법을 학습하는 것이 중요합니다.
이 튜토리얼은 rotten_tomatoes 데이터셋을 사용하지만, 원하는 데이터셋을 로드하여 따라 해보셔도 됩니다!
>>> from datasets import load_dataset
>>> dataset = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")인덱싱
Dataset에는 데이터의 열이 포함되며, 각 열은 서로 다른 유형의 데이터를 가질 수 있습니다. index 또는 축 레이블은 데이터셋에서 예시를 접근하는 데 사용됩니다. 예를 들어, 행 인덱싱을 통해 데이터셋의 예시 딕셔너리를 반환합니다:
# Get the first row in the dataset
>>> dataset[0]
{'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 .'}- 연산자를 사용하여 데이터셋의 끝에서부터 시작합니다:
# Get the last row in the dataset
>>> dataset[-1]
{'label': 0,
'text': 'things really get weird , though not particularly scary : the movie is all portent and no content .'}열 이름으로 인덱싱하면 해당 열의 모든 값이 포함된 리스트가 반환됩니다:
>>> dataset["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 .',
'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 .',
'effective but too-tepid biopic',
...,
'things really get weird , though not particularly scary : the movie is all portent and no content .']행 이름과 열 이름 인덱싱을 조합하여 특정 위치의 값을 반환할 수 있습니다:
>>> dataset[0]["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 .'인덱싱 순서는 중요하지 않습니다. 먼저 열 이름으로 인덱싱하면 Column 객체를 반환하며, 이 객체는 행 인덱스를 사용하여 일반적
>>> import time
>>> start_time = time.time()
>>> text = dataset[0]["text"]
>>> end_time = time.time()
>>> print(f"Elapsed time: {end_time - start_time:.4f} seconds")
Elapsed time: 0.0031 seconds
>>> start_time = time.time()
>>> text = dataset["text"][0]
>>> end_time = time.time()
>>> print(f"Elapsed time: {end_time - start_time:.4f} seconds")
Elapsed time: 0.0042 seconds슬라이싱
Slicing은 데이터셋의 일부, 즉 부분 집합을 반환하며, 여러 행을 한 번에 확인하는 데 유용합니다. 데이터셋을 슬라이싱하려면 : 연산자를 사용하여 위치 범위를 지정합니다.
# Get the first three rows
>>> dataset[:3]
{'label': [1, 1, 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 .',
'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 .',
'effective but too-tepid biopic']}
# Get rows between three and six
>>> dataset[3:6]
{'label': [1, 1, 1],
'text': ['if you sometimes like to go to the movies to have fun , wasabi is a good place to start .',
"emerges as something rare , an issue movie that's so honest and keenly observed that it doesn't feel like one .",
'the film provides some great insight into the neurotic mindset of all comics -- even those who have reached the absolute top of the game .']}IterableDataset
IterableDataset은 load_dataset()에서 streaming 매개변수를 True로 설정하면 로드됩니다:
>>> from datasets import load_dataset
>>> iterable_dataset = load_dataset("ethz/food101", split="train", streaming=True)
>>> for example in iterable_dataset:
... print(example)
... break
{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=384x512 at 0x7F0681F5C520>, 'label': 6}existing Dataset에서 IterableDataset을 생성할 수도 있습니다. 이 경우 데이터셋이 로컬 파일에서 스트리밍되므로 스트리밍 모드보다 빠릅니다:
>>> from datasets import load_dataset
>>> dataset = load_dataset("cornell-movie-review-data/rotten_tomatoes", split="train")
>>> iterable_dataset = dataset.to_iterable_dataset()IterableDataset은 데이터셋을 한 예시씩 순차적으로 반복하므로, 전체 데이터셋 다운로드를 기다리지 않고 바로 사용할 수 있습니다. 바로 사용하고자 하는 대규모 데이터셋에서 이 방식이 매우 유용하다는 것은 쉽게 상상할 수 있습니다!
인덱싱
IterableDataset의 동작은 일반적인 Dataset과 다릅니다. IterableDataset에서는 예제에 대한 랜덤 액세스를 사용할 수 없습니다. 대신, next(iter())를 호출하거나 for 루프를 사용하여 IterableDataset에서 다음 항목을 반환하도록 반복해야 합니다:
>>> next(iter(iterable_dataset))
{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=384x512 at 0x7F0681F59B50>,
'label': 6}
>>> for example in iterable_dataset:
... print(example)
... break
{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=384x512 at 0x7F7479DE82B0>, 'label': 6}하지만 IterableDataset은 컬럼 값에 대한 반복 가능 객체를 반환하는 컬럼 인덱싱을 지원합니다:
>>> next(iter(iterable_dataset["label"]))
6서브셋 생성
IterableDataset.take()를 사용하면 특정 개수의 예제를 포함하는 데이터셋의 부분 집합을 반환할 수 있습니다:
# Get first three examples
>>> list(iterable_dataset.take(3))
[{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=384x512 at 0x7F7479DEE9D0>,
'label': 6},
{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=512x512 at 0x7F7479DE8190>,
'label': 6},
{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=512x383 at 0x7F7479DE8310>,
'label': 6}]하지만 슬라이싱과 달리 IterableDataset.take()는 새로운 IterableDataset를 생성합니다.
다음 단계
이 두 유형의 데이터셋 간 차이에 대해 더 알고 싶으신가요? Dataset과 IterableDataset의 차이점 개념 가이드에서 자세히 알아보세요.
이러한 데이터셋 유형을 더 직접적으로 다루려면, Process 가이드에서 Dataset을 전처리하는 방법이나 Stream 가이드에서 IterableDataset을 전처리하는 방법을 확인해 보세요.
Update on GitHub