-
Notifications
You must be signed in to change notification settings - Fork 7.2k
FER2013 dataset #5120
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
FER2013 dataset #5120
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import csv | ||
| import os | ||
| import os.path | ||
| from typing import Any, Callable, Optional, Tuple | ||
|
|
||
| import torch | ||
| from PIL import Image | ||
|
|
||
| from .utils import verify_str_arg, check_integrity | ||
| from .vision import VisionDataset | ||
|
|
||
|
|
||
| class FER2013(VisionDataset): | ||
| """`FER2013 | ||
| <https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge>`_ Dataset. | ||
|
|
||
| Args: | ||
| root (string): Root directory of dataset where directory | ||
| ``caltech101`` exists or will be saved to if download is set to True. | ||
| split (string, optional): The dataset split, supports ``"train"`` (default), or ``"test"``. | ||
| transform (callable, optional): A function/transform that takes in an PIL image and returns a transformed | ||
| version. E.g, ``transforms.RandomCrop`` | ||
| target_transform (callable, optional): A function/transform that takes in the target and transforms it. | ||
| """ | ||
|
|
||
| _RESOURCES = { | ||
| "train": ("train.csv", "3f0dfb3d3fd99c811a1299cb947e3131"), | ||
| "test": ("test.csv", "b02c2298636a634e8c2faabbf3ea9a23"), | ||
| } | ||
|
|
||
| def __init__( | ||
| self, | ||
| root: str, | ||
| split: str = "train", | ||
| transform: Optional[Callable] = None, | ||
| target_transform: Optional[Callable] = None, | ||
| ) -> None: | ||
| self._split = verify_str_arg(split, "split", self._RESOURCES.keys()) | ||
| super().__init__(root, transform=transform, target_transform=target_transform) | ||
|
|
||
| with open(self._verify_integrity(), "r", newline="") as file: | ||
pmeier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self._samples = [ | ||
| ( | ||
| torch.tensor([int(idx) for idx in row["pixels"].split()], dtype=torch.uint8).reshape(48, 48), | ||
| int(row["emotion"]) if "emotion" in row else None, | ||
| ) | ||
| for row in csv.DictReader(file) | ||
| ] | ||
|
|
||
| def __len__(self) -> int: | ||
| return len(self._samples) | ||
|
|
||
| def __getitem__(self, idx: int) -> Tuple[Any, Any]: | ||
| image_tensor, target = self._samples[idx] | ||
| image = Image.fromarray(image_tensor.numpy()) | ||
|
|
||
| if self.transform is not None: | ||
| image = self.transform(image) | ||
|
|
||
| if self.target_transform is not None: | ||
| target = self.target_transform(target) | ||
|
|
||
| return image, target | ||
|
|
||
| def _verify_integrity(self): | ||
| base_folder = os.path.join(self.root, type(self).__name__.lower()) | ||
pmeier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| file_name, md5 = self._RESOURCES[self._split] | ||
| file = os.path.join(base_folder, file_name) | ||
| if not check_integrity(file, md5=md5): | ||
| raise RuntimeError( | ||
| f"{file_name} not found in {base_folder} or corrupted. " | ||
| f"You can download it from " | ||
| f"https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge" | ||
| ) | ||
| return file | ||
|
|
||
| def extra_repr(self) -> str: | ||
| return f"split={self._split}" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import functools | ||
| import io | ||
| from typing import Any, Callable, Dict, List, Optional, Union, cast | ||
|
|
||
| import torch | ||
| from torchdata.datapipes.iter import IterDataPipe, Mapper, CSVDictParser | ||
| from torchvision.prototype.datasets.decoder import raw | ||
| from torchvision.prototype.datasets.utils import ( | ||
| Dataset, | ||
| DatasetConfig, | ||
| DatasetInfo, | ||
| OnlineResource, | ||
| DatasetType, | ||
| KaggleDownloadResource, | ||
| ) | ||
| from torchvision.prototype.datasets.utils._internal import ( | ||
| hint_sharding, | ||
| hint_shuffling, | ||
| image_buffer_from_array, | ||
| ) | ||
| from torchvision.prototype.features import Label, Image | ||
|
|
||
|
|
||
| class FER2013(Dataset): | ||
| def _make_info(self) -> DatasetInfo: | ||
| return DatasetInfo( | ||
| "fer2013", | ||
| type=DatasetType.RAW, | ||
| homepage="https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge", | ||
| categories=("angry", "disgust", "fear", "happy", "sad", "surprise", "neutral"), | ||
| valid_options=dict(split=("train", "test")), | ||
| ) | ||
|
|
||
| _CHECKSUMS = { | ||
| "train": "a2b7c9360cc0b38d21187e5eece01c2799fce5426cdeecf746889cc96cda2d10", | ||
| "test": "dec8dfe8021e30cd6704b85ec813042b4a5d99d81cb55e023291a94104f575c3", | ||
| } | ||
|
|
||
| def resources(self, config: DatasetConfig) -> List[OnlineResource]: | ||
| archive = KaggleDownloadResource( | ||
| cast(str, self.info.homepage), | ||
| file_name=f"{config.split}.csv.zip", | ||
| sha256=self._CHECKSUMS[config.split], | ||
| ) | ||
| return [archive] | ||
|
|
||
| def _collate_and_decode_sample( | ||
| self, | ||
| data: Dict[str, Any], | ||
| *, | ||
| decoder: Optional[Callable[[io.IOBase], torch.Tensor]], | ||
| ) -> Dict[str, Any]: | ||
| raw_image = torch.tensor([int(idx) for idx in data["pixels"].split()], dtype=torch.uint8).reshape(48, 48) | ||
| label_id = data.get("emotion") | ||
| label_idx = int(label_id) if label_id is not None else None | ||
|
|
||
| image: Union[Image, io.BytesIO] | ||
| if decoder is raw: | ||
| image = Image(raw_image) | ||
| else: | ||
| image_buffer = image_buffer_from_array(raw_image.numpy()) | ||
| image = decoder(image_buffer) if decoder else image_buffer # type: ignore[assignment] | ||
|
|
||
| return dict( | ||
| image=image, | ||
| label=Label(label_idx, category=self.info.categories[label_idx]) if label_idx is not None else None, | ||
| ) | ||
|
|
||
| def _make_datapipe( | ||
| self, | ||
| resource_dps: List[IterDataPipe], | ||
| *, | ||
| config: DatasetConfig, | ||
| decoder: Optional[Callable[[io.IOBase], torch.Tensor]], | ||
| ) -> IterDataPipe[Dict[str, Any]]: | ||
| dp = resource_dps[0] | ||
| dp = CSVDictParser(dp) | ||
| dp = hint_sharding(dp) | ||
| dp = hint_shuffling(dp) | ||
| return Mapper(dp, functools.partial(self._collate_and_decode_sample, decoder=decoder)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| from . import _internal | ||
| from ._dataset import DatasetType, DatasetConfig, DatasetInfo, Dataset | ||
| from ._query import SampleQuery | ||
| from ._resource import OnlineResource, HttpResource, GDriveResource, ManualDownloadResource | ||
| from ._resource import OnlineResource, HttpResource, GDriveResource, ManualDownloadResource, KaggleDownloadResource |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.