{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":21755,"databundleVersionId":1475600,"sourceType":"competition"}],"dockerImageVersionId":30748,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n# import os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-09-05T08:42:33.645949Z","iopub.execute_input":"2024-09-05T08:42:33.646524Z","iopub.status.idle":"2024-09-05T08:42:34.653352Z","shell.execute_reply.started":"2024-09-05T08:42:33.646496Z","shell.execute_reply":"2024-09-05T08:42:34.652425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%reload_ext autoreload\n%autoreload 2\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:34.655348Z","iopub.execute_input":"2024-09-05T08:42:34.655838Z","iopub.status.idle":"2024-09-05T08:42:34.683655Z","shell.execute_reply.started":"2024-09-05T08:42:34.655805Z","shell.execute_reply":"2024-09-05T08:42:34.682793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from glob import glob\nimport itertools\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport PIL\nfrom PIL import Image\nimport random\nimport shutil\nfrom sklearn.model_selection import GroupKFold\nfrom sklearn.metrics import roc_curve\nfrom sklearn import metrics\nimport time\nfrom tqdm.notebook import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\nfrom torch.utils.data import Dataset, random_split, DataLoader\n\nimport torchvision.models as models\nimport torchvision.transforms as transforms","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:34.684813Z","iopub.execute_input":"2024-09-05T08:42:34.685588Z","iopub.status.idle":"2024-09-05T08:42:41.003221Z","shell.execute_reply.started":"2024-09-05T08:42:34.685556Z","shell.execute_reply":"2024-09-05T08:42:41.002469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Seed","metadata":{}},{"cell_type":"code","source":"def set_seed(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:41.005707Z","iopub.execute_input":"2024-09-05T08:42:41.006768Z","iopub.status.idle":"2024-09-05T08:42:41.052856Z","shell.execute_reply.started":"2024-09-05T08:42:41.006731Z","shell.execute_reply":"2024-09-05T08:42:41.052012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = 'cuda' if torch.cuda.is_available() else 'cpu'\ndevice","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:41.053803Z","iopub.execute_input":"2024-09-05T08:42:41.054057Z","iopub.status.idle":"2024-09-05T08:42:41.132259Z","shell.execute_reply.started":"2024-09-05T08:42:41.054035Z","shell.execute_reply":"2024-09-05T08:42:41.131300Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"set_seed(719)","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:41.133337Z","iopub.execute_input":"2024-09-05T08:42:41.133735Z","iopub.status.idle":"2024-09-05T08:42:41.180809Z","shell.execute_reply.started":"2024-09-05T08:42:41.133638Z","shell.execute_reply":"2024-09-05T08:42:41.180107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dataset and Dataloader","metadata":{}},{"cell_type":"code","source":"class ImageDataset(Dataset):\n    def __init__(self, monet_dir, photo_dir, size=(256, 256), normalize=True):\n        super().__init__()\n        self.monet_dir = monet_dir\n        self.photo_dir = photo_dir\n        self.monet_idx = dict()\n        self.photo_idx = dict()\n        if normalize:\n            self.transform = transforms.Compose([\n                transforms.Resize(size),\n                transforms.ToTensor(),\n                transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # pixel range -->  -1 ~ 1\n            ])\n        else:\n            self.transform = transforms.Compose([\n                transforms.Resize(size),\n                transforms.ToTensor()\n            ])\n        for ii, fl in enumerate(os.listdir(self.monet_dir)):\n            self.monet_idx[ii] = fl\n        for ii, fl in enumerate(os.listdir(self.photo_dir)):\n            self.photo_idx[ii] = fl\n            \n    def __getitem__(self, idx):\n        rand_idx = int(np.random.uniform(0, len(self.monet_idx.keys())))\n        photo_path = os.path.join(self.photo_dir, self.photo_idx[rand_idx])\n        monet_path = os.path.join(self.monet_dir, self.monet_idx[idx])\n        photo_img = Image.open(photo_path)\n        photo_img = self.transform(photo_img)\n        monet_img = Image.open(monet_path)\n        monet_img = self.transform(monet_img)\n        return photo_img, monet_img\n    \n    def __len__(self):\n        return min(len(self.monet_idx.keys()), len(self.photo_idx.keys()))","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:41.181844Z","iopub.execute_input":"2024-09-05T08:42:41.182106Z","iopub.status.idle":"2024-09-05T08:42:41.231793Z","shell.execute_reply.started":"2024-09-05T08:42:41.182084Z","shell.execute_reply":"2024-09-05T08:42:41.230989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_ds = ImageDataset('/kaggle/input/gan-getting-started/monet_jpg/', \\\n                      '/kaggle/input/gan-getting-started/photo_jpg/')","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:41.232957Z","iopub.execute_input":"2024-09-05T08:42:41.233698Z","iopub.status.idle":"2024-09-05T08:42:41.925156Z","shell.execute_reply.started":"2024-09-05T08:42:41.233667Z","shell.execute_reply":"2024-09-05T08:42:41.924287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_dl = DataLoader(img_ds, batch_size=1, pin_memory=True)","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:41.926318Z","iopub.execute_input":"2024-09-05T08:42:41.926619Z","iopub.status.idle":"2024-09-05T08:42:41.971840Z","shell.execute_reply.started":"2024-09-05T08:42:41.926595Z","shell.execute_reply":"2024-09-05T08:42:41.970919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"photo_img, monet_img = next(iter(img_dl))","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:41.974512Z","iopub.execute_input":"2024-09-05T08:42:41.974769Z","iopub.status.idle":"2024-09-05T08:42:42.241742Z","shell.execute_reply.started":"2024-09-05T08:42:41.974747Z","shell.execute_reply":"2024-09-05T08:42:42.240738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def unnorm(img, mean = [0.5, 0.5, 0.5], std = [0.5, 0.5, 0.5]):\n    for t, m, s in zip(img, mean, std):\n        t.mul_(s).add_(s)\n        \n        return img","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:42.243247Z","iopub.execute_input":"2024-09-05T08:42:42.243550Z","iopub.status.idle":"2024-09-05T08:42:42.288858Z","shell.execute_reply.started":"2024-09-05T08:42:42.243525Z","shell.execute_reply":"2024-09-05T08:42:42.287891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.shape(monet_img[0])","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:42.289864Z","iopub.execute_input":"2024-09-05T08:42:42.290130Z","iopub.status.idle":"2024-09-05T08:42:42.337333Z","shell.execute_reply.started":"2024-09-05T08:42:42.290106Z","shell.execute_reply":"2024-09-05T08:42:42.336517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"f = plt.figure(figsize=(8, 8))\n\nf.add_subplot(1, 2, 1)\nplt.title('Photo')\nphoto_img = unnorm(photo_img)\nplt.imshow(photo_img[0].permute(1, 2, 0))\n\nf.add_subplot(1, 2, 2)\nplt.title('Monet')\nmonet_img = unnorm(monet_img)\nplt.imshow(monet_img[0].permute(1, 2, 0))","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:42.338435Z","iopub.execute_input":"2024-09-05T08:42:42.338694Z","iopub.status.idle":"2024-09-05T08:42:42.959620Z","shell.execute_reply.started":"2024-09-05T08:42:42.338672Z","shell.execute_reply":"2024-09-05T08:42:42.958680Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Save and Load","metadata":{}},{"cell_type":"code","source":"def load_checkpoint(ckpt_path, map_location=None):\n    ckpt = torch.load(ckpt_path, map_location=map_location)\n    print(' [*] Loading checkpoint from %s succed!' % ckpt_path)\n    return ckpt","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:42.960783Z","iopub.execute_input":"2024-09-05T08:42:42.961068Z","iopub.status.idle":"2024-09-05T08:42:43.011034Z","shell.execute_reply.started":"2024-09-05T08:42:42.961043Z","shell.execute_reply":"2024-09-05T08:42:43.010219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def save_checkpoint(state, save_path):\n    torch.save(state, save_path)","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:43.012053Z","iopub.execute_input":"2024-09-05T08:42:43.012357Z","iopub.status.idle":"2024-09-05T08:42:43.056859Z","shell.execute_reply.started":"2024-09-05T08:42:43.012333Z","shell.execute_reply":"2024-09-05T08:42:43.056122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"code","source":"def Upsample(in_ch, out_ch, use_dropout=True, dropout_ratio=0.5):\n    if use_dropout:\n        return nn.Sequential(\n            nn.ConvTranspose2d(in_ch, out_ch, 3, stride=2, padding=1, output_padding=1),\n            nn.InstanceNorm2d(out_ch),\n            nn.GELU())\n    else:\n        return nn.Sequential(\n            nn.ConvTranspose2d(in_ch, out_ch, 3, stride=2, padding=1, output_padding=1),\n            nn.InstanceNorm2d(out_ch),\n            nn.GELU())","metadata":{"execution":{"iopub.status.busy":"2024-09-05T08:42:43.057908Z","iopub.execute_input":"2024-09-05T08:42:43.058205Z","iopub.status.idle":"2024-09-05T08:42:43.104065Z","shell.execute_reply.started":"2024-09-05T08:42:43.058174Z","shell.execute_reply":"2024-09-05T08:42:43.103209Z"},"trusted":true},"execution_count":null,"outputs":[]}]}