GGoMa/Dacon_FashionMNIST

Dacon Fashion MNIST 경진대회

Updated on 22.09.20
Dacon_FashionMNIST.py
''' ---GGoMa/Dacon_FashionMNIST Auto Generate Code--- Author : GGoMa Project Name: Dacon_FashionMNIST Project Link: https://blockai.kr/GGoMa/Dacon_FashionMNIST (BlockAI) Create Date : 2022-09-21 ---Requirements--- # 사용자의 환경(OS, CUDA 등)에 따라 라이브러리 버전을 맞춰주세요 pip install torch==1.12 torchvision==0.13.0 torchtext==0.13.0 torchaudio==0.12.0 pip install pytorch-lightning pip install tqdm pip install pandas pip install scikit-learn ---Folder Structure--- --📂 data |--📂 input |--📄 train.* |--📄 test.* --📄 Dacon_FashionMNIST.py --📄 Dacon_FashionMNIST.ipynb --📄 requirements.txt ''' import os import argparse import copy from glob import glob from tqdm import tqdm import numpy as np import pandas as pd from sklearn import preprocessing import torch import pytorch_lightning as pl path_sep = os.sep # https://pytorch.org/tutorials/beginner/basics/data_tutorial.html#creating-a-custom-dataset-for-your-files class Dataset(torch.utils.data.Dataset): def __init__(self, inputs, targets=[]): self.inputs = inputs self.targets = targets # 학습 및 추론 과정에서 데이터를 1개씩 꺼내오는 곳 def __getitem__(self, idx): # 정답이 있다면 if문을, 없다면 else문을 수행합니다 if len(self.targets) == 0: return torch.tensor(self.inputs[idx]) else: return torch.tensor(self.inputs[idx]), torch.tensor(self.targets[idx]) # 입력하는 개수만큼 데이터를 사용합니다 # 'return 100'이면 1에폭에 100개의 데이터만 사용합니다 def __len__(self): return len(self.inputs) # https://pytorch-lightning.readthedocs.io/en/stable/extensions/datamodules.html class Dataloader(pl.LightningDataModule): # 데이터의 종류에 따라 코드 수정이 필요할 수 있습니다 def __init__(self, data_folder, batch_size, train_ratio, shuffle): super().__init__() self.data_folder = data_folder self.batch_size = batch_size self.train_ratio = train_ratio self.shuffle = shuffle self.train_dataset = None self.test_dataset = None self.predict_dataset = None self.set_preprocessing() def set_preprocessing(self): data = pd.read_csv(glob(os.path.join(self.data_folder, 'input', 'train.*'))[0], sep=',', index_col=0, encoding='utf-8') columns = data.columns self.target_columns = [columns[0]] def preprocessing(self, data): columns = data.columns.tolist() # 타겟 데이터가 없으면 빈 배열을 리턴합니다. try: targets = data[self.target_columns].values.tolist() inputs = data.drop(self.target_columns, axis=1).values.tolist() except: targets = [] inputs = data.values.tolist() return inputs, targets def setup(self, stage='fit'): if stage == 'fit': train_data = pd.read_csv(glob(os.path.join(self.data_folder, 'input', 'train.*'))[0], sep=',', index_col=0, encoding='utf-8') # 학습데이터 준비 train_inputs, train_targets = self.preprocessing(train_data) # train 데이터만 shuffle을 적용해줍니다, 필요하다면 val, test 데이터에도 shuffle을 적용할 수 있습니다 self.train_dataset = Dataset(train_inputs, train_targets) else: # 평가데이터 준비 test_data = pd.read_csv(glob(os.path.join(self.data_folder, 'input', 'test.*'))[0], sep=',', index_col=0, encoding='utf-8') test_inputs, test_targets = self.preprocessing(test_data) self.test_dataset = Dataset(test_inputs, test_targets) self.predict_dataset = Dataset(test_inputs, []) def train_dataloader(self): return torch.utils.data.DataLoader(self.train_dataset, batch_size=self.batch_size, shuffle=args.shuffle) def test_dataloader(self): return torch.utils.data.DataLoader(self.test_dataset, batch_size=self.batch_size) def predict_dataloader(self): return torch.utils.data.DataLoader(self.predict_dataset, batch_size=self.batch_size) # https://pytorch-lightning.readthedocs.io/en/stable/common/lightning_module.html class Model(pl.LightningModule): def __init__(self): super().__init__() self.save_hyperparameters() self.conv2d_1 = torch.nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, padding=0) self.maxpool2d_1 = torch.nn.MaxPool2d(kernel_size=2) self.batchnorm2d_1 = torch.nn.BatchNorm2d(num_features=32) self.conv2d_2 = torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=2, padding=0) self.maxpool2d_2 = torch.nn.MaxPool2d(kernel_size=2) self.batchnorm2d_2 = torch.nn.BatchNorm2d(num_features=64) self.linear_1 = torch.nn.Linear(in_features=2304, out_features=128) self.batchnorm1d_1 = torch.nn.BatchNorm1d(num_features=128) self.linear_2 = torch.nn.Linear(in_features=128, out_features=10) self.dropout2d_1 = torch.nn.Dropout2d(p=0.3) self.relu_1 = torch.nn.ReLU() self.dropout_1 = torch.nn.Dropout() self.crossentropyloss_1 = torch.nn.CrossEntropyLoss() def forward(self, x): x = torch.reshape(x, shape=(-1, 1, 28, 28)) x = self.conv2d_1(x) x = self.maxpool2d_1(x) x = self.dropout2d_1(x) x = self.batchnorm2d_1(x) x = self.relu_1(x) x = self.conv2d_2(x) x = self.maxpool2d_2(x) x = self.dropout2d_1(x) x = self.batchnorm2d_2(x) x = self.relu_1(x) x = torch.flatten(x, start_dim=1) x = self.linear_1(x) x = self.dropout_1(x) x = self.batchnorm1d_1(x) x = self.relu_1(x) x = self.linear_2(x) return x def training_step(self, batch, batch_idx): x, y = batch logits = self(x) loss = self.crossentropyloss_1(logits, y.long().squeeze()) self.log("train_loss", loss) return loss def validation_step(self, batch, batch_idx): x, y = batch logits = self(x) loss = self.crossentropyloss_1(logits, y.long().squeeze()) self.log("val_loss", loss) return loss def test_step(self, batch, batch_idx): x, y = batch logits = self(x) loss = self.crossentropyloss_1(logits, y.long().squeeze()) self.log("test_loss", loss) return loss def predict_step(self, batch, batch_idx): x = batch logits = self(x) return logits def configure_optimizers(self): # 이곳에서 lr 값을 변경할 수 있습니다 optimizer = torch.optim.Adam(self.parameters(), lr=0.0005) return optimizer if __name__ == '__main__': # https://docs.python.org/ko/3/library/argparse.html # 하이퍼 파라미터 등 각종 설정값을 입력받습니다 # 터미널 실행 예시 : python3 run.py --batch_size=64 ... # 실행 시 '--batch_size=64' 같은 인자를 입력하지 않으면 default 값이 기본으로 실행됩니다 parser = argparse.ArgumentParser() parser.add_argument('--data_folder', default='./data') parser.add_argument('--batch_size', default=128) parser.add_argument('--max_epoch', default=100) parser.add_argument('--shuffle', default=True) parser.add_argument('--train_ratio', default=0.8) args = parser.parse_args() dataloader = Dataloader(args.data_folder, args.batch_size, args.train_ratio, args.shuffle) model = Model() # 'patience=5'이면 5에폭동안 monitor값이 좋아지지 않으면 학습을 자동 중단합니다 early_stop_callback = pl.callbacks.EarlyStopping(monitor='train_loss', patience=5) # https://pytorch-lightning.readthedocs.io/en/stable/common/trainer.html # 학습 및 추론을 위한 Trainer 설정 # gpu가 없으면 'gpus=0'을, gpu가 여러개면 'gpus=4'처럼 사용하실 gpu의 개수를 입력해주세요 trainer = pl.Trainer(gpus=1, max_epochs=args.max_epoch, callbacks=[early_stop_callback]) trainer.fit(model=model, datamodule=dataloader) # 테스트 데이터에 타겟값이 있을때만 trainer.test를 실행할 수 있습니다 trainer.test(model=model, datamodule=dataloader) predictions = trainer.predict(model=model, datamodule=dataloader)
Readme.md

Dacon FashionMNIST 경진대회 코드입니다!

코드는 생성한 후 일부 수정하였는데 코랩에서 확인할 수 있습니다!!

단순하게 CNN만 써서 그런지 성능이 엄청 높지는 않네요 ㅠㅠ

service
문의하기