{"id":31366266,"url":"https://github.com/developer0hye/custom-cnn-based-image-classification-in-pytorch","last_synced_at":"2025-09-27T10:02:49.006Z","repository":{"id":57740465,"uuid":"163427925","full_name":"developer0hye/Custom-CNN-based-Image-Classification-in-PyTorch","owner":"developer0hye","description":null,"archived":false,"fork":false,"pushed_at":"2019-01-28T03:52:21.000Z","size":69,"stargazers_count":42,"open_issues_count":1,"forks_count":4,"subscribers_count":4,"default_branch":"master","last_synced_at":"2023-03-05T18:59:26.251Z","etag":null,"topics":["cnn","custom-dataset","image-classification","image-classifier","pytorch","pytorch-tutorial"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/developer0hye.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-12-28T16:09:57.000Z","updated_at":"2023-01-24T15:31:40.000Z","dependencies_parsed_at":"2022-09-02T18:51:37.026Z","dependency_job_id":null,"html_url":"https://github.com/developer0hye/Custom-CNN-based-Image-Classification-in-PyTorch","commit_stats":null,"previous_names":[],"tags_count":null,"template":null,"template_full_name":null,"purl":"pkg:github/developer0hye/Custom-CNN-based-Image-Classification-in-PyTorch","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developer0hye%2FCustom-CNN-based-Image-Classification-in-PyTorch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developer0hye%2FCustom-CNN-based-Image-Classification-in-PyTorch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developer0hye%2FCustom-CNN-based-Image-Classification-in-PyTorch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developer0hye%2FCustom-CNN-based-Image-Classification-in-PyTorch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/developer0hye","download_url":"https://codeload.github.com/developer0hye/Custom-CNN-based-Image-Classification-in-PyTorch/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/developer0hye%2FCustom-CNN-based-Image-Classification-in-PyTorch/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":277213139,"owners_count":25780315,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-27T02:00:08.978Z","response_time":73,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cnn","custom-dataset","image-classification","image-classifier","pytorch","pytorch-tutorial"],"created_at":"2025-09-27T10:01:59.224Z","updated_at":"2025-09-27T10:02:48.993Z","avatar_url":"https://github.com/developer0hye.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Custom-CNN-Based-Classifier-in-PyTorch\n\n본 튜토리얼에서는 **PyTorch** 를 사용하여 **Image Classifier** 를 만들어보도록 하겠습니다.\n\n본 튜토리얼을 통해 다음 방법들을 배울 수 있습니다.\n\n* **CNN(Convolutional Neural Network)** 기반의 **Image Classifier** 모델 설계 방법\n* 기존의 데이터셋(MNIST, CIFAR-10 등)이 아닌 **Custom Dataset**(개인이 수집한 데이터셋)을 처리하기 위한 **PyTorch** 의 **Dataset** 및 **DataLoader** 사용 방법\n\n**본 튜토리얼에서는 PyTorch 의 Dataset 및 DataLoader 에 능숙해지기 위하여 PyTorch 의 ImageFolder 를 사용하지 않습니다.**\n\n## Setup\n\n### Requirements\n\n본 튜토리얼에 앞서 다음의 라이브러리들을 필요로 합니다.\n* PyTorch\n* PIL\n\n추가적으로 NVIDIA GPU 를 사용하신다면 CUDA 와 CUDNN 을 설치하는 것을 권장합니다.\n\n### Custom Dataset\n\n본 튜토리얼에서는 만화 **\"쿠로코의 농구\"** 의 등장 인물인 **\"쿠로코\"** 와 **\"카가미\"** 를 분류해보겠습니다.\n\n**Kuroko's basketball**\n\n![60136-kuroko_no_basket-blue-basketball](https://user-images.githubusercontent.com/35001605/51658134-693e2700-1fea-11e9-8045-b2d49231246f.jpg)\n\n**Kuroko**\n\n![65d739597a4f1bfd7085615cadf2c38e1367394101_full](https://user-images.githubusercontent.com/35001605/51658137-6c391780-1fea-11e9-9493-313b93f6166b.png)\n\n**Kagami**\n\n![kurokonobaske_a03](https://user-images.githubusercontent.com/35001605/51658140-6e9b7180-1fea-11e9-9804-9ff222d3d079.jpg)\n\n#### Examples\n\n정면 얼굴이 나온 사진 위주로 쿠로코 60장, 카가미 60 장 수집\n\n![example_dataset3](https://user-images.githubusercontent.com/35001605/51650040-12285a00-1fca-11e9-95d1-189352ef2d58.PNG)\n\n![example_dataset2](https://user-images.githubusercontent.com/35001605/51650039-105e9680-1fca-11e9-89be-868234ae3241.PNG)\n\n#### Download\n\n[다운로드 ](https://drive.google.com/open?id=1dQePxrd9xdtvLr9E-jiUb-TdyWG1EFlJ)\n\n데이터셋은 학습을 위한 train 폴더와 성능 평가를 위한 test 폴더로 나누어져 있습니다.\n\ntrain 폴더와 test 폴더 내부에는 분류하고자 하는 클래스별로 하위 폴더가 존재하며 각 하위 폴더에는 해당 클래스에 속하는 이미지들이 저장되어 있습니다.\n\n```python\ndata/\n  train/\n    kuroko/\n      *.png\n    kagami/\n      *.png\n  test/\n    kuroko/\n      *.png\n    kagami/\n      *.png\n```\n\n### Structure of Directory\n\n본 튜토리얼 에서는 **Custom Dataset**에 대한 처리를 보다 쉽게 하기 위하여 다음과 같이 main.py 파일(코드를 작성할 파일)과 **Custom Dataset**이 동일한 경로에 있음을 가정하겠습니다. \n\n```python\n\ndata/\n  train/\n    kuroko/\n      *.png\n    kagami/\n      *.png\n  test/\n    kuroko/\n      *.png\n    kagami/\n      *.png\n      \nmain.py\n```\n## Data Loading and Processing\n\nPyTorch 에는 데이터셋에 대한 처리를 용이하게 하기 위하여 **Dataset** 과 **DataLoader** 클래스를 제공합니다.\n\n**Dataset** 클래스는 torch.utils.data.Dataset 에 정의된 추상 클래스(Abstract class) 로써 사용자는 **Custom Dataset** 을 읽기 위하여 **Dataset** 클래스를 상속받는 클래스를 작성해야 합니다.\n\n**DataLoader**는 **Dataset** 클래스를 상속받는 클래스에 정의된 작업에 따라 데이터를 읽어오며, 이때 설정에 따라 원하는 **배치(Batch) 크기**로 데이터를 읽어올 수 있고 병렬 처리 설정, 데이터 셔플(Shuffle) 등의 작업을 설정할 수 있습니다.\n\n본 튜토리얼에서는 **Dataset** 클래스를 상속받는 클래스를 **Dataset** 클래스라 칭하도록 하겠습니다.\n\n### Dataset Class \u0026 DataLoader Class\n\n일반적인 **Dataset** 클래스의 형태는 아래와 같습니다.\n\n```python\nfrom torch.utils.data.dataset import Dataset\n\nclass MyCustomDataset(Dataset):\n    def __init__(self, ...):\n        # stuff\n        \n    def __getitem__(self, index):\n        # stuff\n        return (img, label)\n\n    def __len__(self):\n        return count # of how many examples(images?) you have\n```\n**Custom Dataset** 을 읽기 위하여 다음의 3가지 함수를 정의해야 합니다.\n\n* `__init__()` \n\n* `__getitem__()`\n\n* `__len__()`\n\n`__init__()` 함수는 클래스 생성자로써 데이터에 대한 Transform(데이터 형 변환, Augmentation 등)을 설정하고 데이터를 읽기 위한 기초적인 초기화 작업들을 수행하도록 정의합니다.\n\n`__getitem__()` 함수는 **Custom Dataset** 에 존재하는 데이터를 읽고 반환하는 함수입니다. 따라서 본인이 어떤 작업을 수행하는지에 따라 반환하는 값들이 달라질 수 있습니다. 본 튜토리얼에서 구현할 작업은 **Image Classifier** 이므로 `__getitem__()` 함수는 이미지와 해당 이미지가 어떤 클래스에 속하는지에 대한 값을 반환할 것입니다. **1개의 데이터셋에 대한 값((이미지 , 클래스))만을 반환하면 됩니다!**\n\n주의할 점은 `__getitem__()` 을 통해 반환되는 값이 PyTorch 에서 처리 가능한 데이터 타입(tensor, numpy array etc.)이 아닐 경우, **DataLoader** 를 통해 데이터를 읽을 때 다음과 같은 에러가 발생될 것입니다.\n\n`TypeError: batch must contain tensors, numbers, dicts or lists; found \u003cclass 'PIL.PngImagePlugin.PngImageFile'\u003e`\n\n`__len__()` 함수는 데이터셋의 크기를 반환하는 함수입니다. **Image Classifier** 로 예를 들면, 우리가 가진 이미지의 갯수가 곧 데이터셋의 크기 입니다. 즉 50장을 가지고 있다면 `__len__()` 함수는 50 을 반환해야 합니다.\n\n### Programming\n\n#### modules\n```python\nimport os\nfrom PIL import Image\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch import nn\nfrom torchvision import transforms\n```\n#### Declaration \u0026 Definition class\n```python\nclass CustomImageDataset(Dataset):\n    def read_data_set(self):\n\n        all_img_files = []\n        all_labels = []\n\n        class_names = os.walk(self.data_set_path).__next__()[1]\n\n        for index, class_name in enumerate(class_names):\n            label = index\n            img_dir = os.path.join(self.data_set_path, class_name)\n            img_files = os.walk(img_dir).__next__()[2]\n\n            for img_file in img_files:\n                img_file = os.path.join(img_dir, img_file)\n                img = Image.open(img_file)\n                if img is not None:\n                    all_img_files.append(img_file)\n                    all_labels.append(label)\n\n        return all_img_files, all_labels, len(all_img_files), len(class_names)\n\n    def __init__(self, data_set_path, transforms=None):\n        self.data_set_path = data_set_path\n        self.image_files_path, self.labels, self.length, self.num_classes = self.read_data_set()\n        self.transforms = transforms\n\n    def __getitem__(self, index):\n        image = Image.open(self.image_files_path[index])\n        image = image.convert(\"RGB\")\n\n        if self.transforms is not None:\n            image = self.transforms(image)\n\n        return {'image': image, 'label': self.labels[index]}\n\n    def __len__(self):\n        return self.length\n```\n\n**Image Classifer**를 위한 **Dataset** 클래스는 위와 같이 구현되며 실제 객체 생성시에는 아래와 같이 사용됩니다.\n\n\n```python\ncustom_dataset_train = CustomImageDataset('./data/train',transforms=transfrom_train)\ncustom_dataset_test = CustomImageDataset('./data/test',transforms=transfrom_test)\n```\n\nCustomImageDataset 클래스의 내부를 살펴보면 생성자(`__init__`)를 통하여 이미지들이 저장된 경로(data_set_path)를 입력받게 되고 이 값은 `self.data_set_path` 에 저장됩니다.\n\n```python\ndef __init__(self, data_set_path, transforms=None):\n```\n\n이 후 `__init__` 함수에서는 `read_data_set` 함수를 호출하고 `self.data_set_path` 에 저장된 경로를 통해 이미지들의 경로(`self.image_files_path`), 각 이미지가 속한 클래스(`self.labels`), 데이터 셋의 크기(`self.length`), 분류하고자 하는 클래스의 갯수(`self.num_classes`) 를 초기화 합니다.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeveloper0hye%2Fcustom-cnn-based-image-classification-in-pytorch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdeveloper0hye%2Fcustom-cnn-based-image-classification-in-pytorch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeveloper0hye%2Fcustom-cnn-based-image-classification-in-pytorch/lists"}