{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":21755,"databundleVersionId":1475600,"sourceType":"competition"}],"dockerImageVersionId":30787,"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\nimport os\nfor 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","trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:38.498884Z","iopub.execute_input":"2024-11-27T11:34:38.499135Z","iopub.status.idle":"2024-11-27T11:34:50.195394Z","shell.execute_reply.started":"2024-11-27T11:34:38.499109Z","shell.execute_reply":"2024-11-27T11:34:50.194588Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport cv2\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import Dataset, DataLoader, Subset\nimport torchvision\nfrom torchvision import transforms\nimport numpy as np\nfrom PIL import Image\nfrom tqdm import tqdm\nimport shutil\nfrom pathlib import Path\nimport glob\nimport sys\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nimport torch.optim as optim\nfrom torchvision.utils import save_image\nimport copy\nimport random\nfrom sklearn.model_selection import train_test_split\nimport shutil\nfrom PIL import Image","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:50.197122Z","iopub.execute_input":"2024-11-27T11:34:50.197944Z","iopub.status.idle":"2024-11-27T11:34:55.417339Z","shell.execute_reply.started":"2024-11-27T11:34:50.197903Z","shell.execute_reply":"2024-11-27T11:34:55.416417Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"! mkdir ../images","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:55.418566Z","iopub.execute_input":"2024-11-27T11:34:55.419086Z","iopub.status.idle":"2024-11-27T11:34:56.450080Z","shell.execute_reply.started":"2024-11-27T11:34:55.419044Z","shell.execute_reply":"2024-11-27T11:34:56.449059Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def save_checkpoint(model, optimizer, filename=\"my_checkpoint.pth.tar\"):\n    print(\"=> Saving checkpoint\")\n    checkpoint = {\n        \"state_dict\": model.state_dict(),\n        \"optimizer\": optimizer.state_dict(),\n    }\n    torch.save(checkpoint, filename)\n\n\ndef load_checkpoint(checkpoint_file, model, optimizer, lr):\n    print(\"=> Loading checkpoint\")\n    checkpoint = torch.load(checkpoint_file, map_location=DEVICE)\n    model.load_state_dict(checkpoint[\"state_dict\"])\n    optimizer.load_state_dict(checkpoint[\"optimizer\"])\n\n    # If we don't do this then it will just have learning rate of old checkpoint\n    # and it will lead to many hours of debugging \\:\n    for param_group in optimizer.param_groups:\n        param_group[\"lr\"] = lr\n\n\ndef seed_everything(seed=42):\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:56.452191Z","iopub.execute_input":"2024-11-27T11:34:56.452512Z","iopub.status.idle":"2024-11-27T11:34:56.459627Z","shell.execute_reply.started":"2024-11-27T11:34:56.452479Z","shell.execute_reply":"2024-11-27T11:34:56.458774Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Block\nclass Block(nn.Module):\n    def __init__(self, i_cha, o_cha, stride):\n        super().__init__()\n        self.seq = nn.Sequential(\n            nn.Conv2d(i_cha, o_cha, kernel_size= 4, stride = stride, padding=1, bias = True, padding_mode=\"reflect\"),\n            nn.InstanceNorm2d(o_cha),\n            nn.LeakyReLU(0.2)\n        )\n    def forward(self, x):\n        return self.seq(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:56.460706Z","iopub.execute_input":"2024-11-27T11:34:56.460967Z","iopub.status.idle":"2024-11-27T11:34:56.471450Z","shell.execute_reply.started":"2024-11-27T11:34:56.460943Z","shell.execute_reply":"2024-11-27T11:34:56.470717Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Disc\nclass Discriminator(nn.Module):\n    def __init__(self, i_cha = 3, features = [64, 128, 256, 512]):\n        super().__init__()\n        self.initial = nn.Sequential(\n            nn.Conv2d(i_cha, features[0], kernel_size= 4, stride = 2, padding= 1, padding_mode= \"reflect\"),\n            nn.LeakyReLU(0.2)\n        )\n        layers = []\n        for i in range(len(features) - 1):\n            layers.append(Block(features[i], features[i+1], stride= 1 if i == (len(features) - 2) else 2))\n        layers.append(nn.Conv2d(features[-1], 1, kernel_size= 4, stride= 1, padding= 1, padding_mode= \"reflect\"))\n        self.model = nn.Sequential(*layers)\n\n    def forward(self, x):\n        x = self.initial(x)\n        return torch.sigmoid(self.model(x))\n\ndef test():\n    x = torch.randn((5,3,256,256))\n    model = Discriminator(i_cha=3)\n    preds = model(x)\n    print(preds.shape)\ntest()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:56.472507Z","iopub.execute_input":"2024-11-27T11:34:56.472817Z","iopub.status.idle":"2024-11-27T11:34:56.904729Z","shell.execute_reply.started":"2024-11-27T11:34:56.472782Z","shell.execute_reply":"2024-11-27T11:34:56.903791Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ConvBlock\nclass ConvBlock(nn.Module):\n    def __init__(self, i_cha, o_cha, down = True, use_act = True, **kwargs):\n        super().__init__()\n        self.seq = nn.Sequential(\n            nn.Conv2d(i_cha, o_cha, padding_mode=\"reflect\", **kwargs) if down else nn.ConvTranspose2d(i_cha, o_cha, **kwargs),\n            nn.InstanceNorm2d(o_cha),\n            nn.ReLU(inplace=True) if use_act else nn.Identity()\n        )\n    def forward(self, x):\n        return self.seq(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:56.905888Z","iopub.execute_input":"2024-11-27T11:34:56.906180Z","iopub.status.idle":"2024-11-27T11:34:56.912041Z","shell.execute_reply.started":"2024-11-27T11:34:56.906150Z","shell.execute_reply":"2024-11-27T11:34:56.911075Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Residual\nclass ResidualBlock(nn.Module):\n    def __init__(self, channels):\n        super().__init__()\n        self.seq = nn.Sequential(\n            ConvBlock(channels, channels, kernel_size=3, padding=1),\n            ConvBlock(channels, channels, kernel_size=3, use_act= False ,padding=1),\n            )\n    def forward(self, x):\n        return x + self.seq(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:56.913166Z","iopub.execute_input":"2024-11-27T11:34:56.913510Z","iopub.status.idle":"2024-11-27T11:34:56.921377Z","shell.execute_reply.started":"2024-11-27T11:34:56.913473Z","shell.execute_reply":"2024-11-27T11:34:56.920609Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Gen\nclass Generator(nn.Module):\n    def __init__(self, i_channels, num_features = 64 ,num_residuals = 9):\n        super().__init__()\n        self.initial = nn.Sequential(\n            nn.Conv2d(i_channels, num_features , kernel_size= 7, stride = 1, padding=3, padding_mode= \"reflect\"),\n            nn.ReLU(inplace=True)\n        )\n\n        self.down_blocks = nn.ModuleList(\n            [\n                ConvBlock(num_features, num_features *2, kernel_size = 3, stride= 2, padding = 1),\n                ConvBlock(num_features*2, num_features *4, kernel_size = 3, stride= 2, padding = 1),\n            ]\n        )\n\n        self.residual = nn.Sequential(\n            *[ResidualBlock(num_features*4) for _ in range(num_residuals)]\n        )\n\n        self.up_blocks = nn.ModuleList(\n            [\n                ConvBlock(num_features*4, num_features *2, down = False,kernel_size = 3, stride= 2, padding = 1, output_padding= 1),\n                ConvBlock(num_features*2, num_features, down= False,kernel_size = 3, stride= 2, padding = 1, output_padding = 1),\n            ]\n        )\n\n        self.last = nn.Conv2d(num_features, i_channels, kernel_size= 7, stride= 1, padding= 3, padding_mode= \"reflect\")\n\n\n    def forward(self, x ):\n        x = self.initial(x)\n        for layer in self.down_blocks:\n            x = layer(x)\n        x = self.residual(x)\n        for layer in self.up_blocks:\n            x = layer(x)\n        return torch.tanh(self.last(x))\n\ndef test():\n    i_cha = 3\n    img_size = 256\n    x = torch.randn((2, i_cha, img_size, img_size))\n    gen = Generator(i_cha, 9)\n    print(gen)\n    print(gen(x).shape)\n\ntest()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:56.922488Z","iopub.execute_input":"2024-11-27T11:34:56.922783Z","iopub.status.idle":"2024-11-27T11:34:57.131213Z","shell.execute_reply.started":"2024-11-27T11:34:56.922754Z","shell.execute_reply":"2024-11-27T11:34:57.130317Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class Monet(Dataset):\n    def __init__(self):\n        self.monet_paths = sorted(glob.glob(os.path.join(\"/kaggle/input/gan-getting-started/monet_jpg\", '*.jpg')))\n        self.photo_paths = sorted(glob.glob(os.path.join(\"/kaggle/input/gan-getting-started/photo_jpg\", '*.jpg')))\n        self.transform = A.Compose([\n            A.Resize(256,256),\n            A.Normalize(0.5,0.5),\n            ToTensorV2()\n        ],\n        additional_targets= {\"image0\": \"image\"}\n        )\n        \n        \n    def __len__(self):\n        return max(len(self.monet_paths), len(self.photo_paths))\n\n    def __getitem__(self, index):\n        monet_img = cv2.imread(self.monet_paths[index % len(self.monet_paths)])\n        monet_img = cv2.cvtColor(monet_img, cv2.COLOR_BGR2RGB)\n\n        img = cv2.imread(self.photo_paths[index % len(self.photo_paths)])\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n        aug = self.transform(image = monet_img, image0 = img)\n        monet_img = aug[\"image\"]\n        img = aug[\"image0\"]\n        \n        return monet_img, img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:57.134741Z","iopub.execute_input":"2024-11-27T11:34:57.135235Z","iopub.status.idle":"2024-11-27T11:34:57.142096Z","shell.execute_reply.started":"2024-11-27T11:34:57.135204Z","shell.execute_reply":"2024-11-27T11:34:57.141162Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dataset = Monet()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:57.143174Z","iopub.execute_input":"2024-11-27T11:34:57.143467Z","iopub.status.idle":"2024-11-27T11:34:57.180087Z","shell.execute_reply.started":"2024-11-27T11:34:57.143437Z","shell.execute_reply":"2024-11-27T11:34:57.179145Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def showImg(img):\n    plt.imshow(img.detach().cpu().numpy().transpose(1,2,0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:57.181227Z","iopub.execute_input":"2024-11-27T11:34:57.181782Z","iopub.status.idle":"2024-11-27T11:34:57.186372Z","shell.execute_reply.started":"2024-11-27T11:34:57.181744Z","shell.execute_reply":"2024-11-27T11:34:57.185331Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"showImg(dataset[0][0])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:57.187384Z","iopub.execute_input":"2024-11-27T11:34:57.187657Z","iopub.status.idle":"2024-11-27T11:34:57.593926Z","shell.execute_reply.started":"2024-11-27T11:34:57.187627Z","shell.execute_reply":"2024-11-27T11:34:57.592961Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nBATCH_SIZE = 16\nLEARNING_RATE = 3e-4\nLAMBDA_IDENTITY = 0.0\nLAMBDA_CYCLE = 10\nNUM_WORKERS = 4\nNUM_EPOCHS = 30\nLOAD_MODEL = False\nSAVE_MODEL = True\nCHECKPOINT_GEN_P = \"genh.pth.tar\"\nCHECKPOINT_GEN_M = \"genz.pth.tar\"\nCHECKPOINT_CRITIC_P = \"critich.pth.tar\"\nCHECKPOINT_CRITIC_M = \"criticz.pth.tar\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:57.594960Z","iopub.execute_input":"2024-11-27T11:34:57.595207Z","iopub.status.idle":"2024-11-27T11:34:57.645896Z","shell.execute_reply.started":"2024-11-27T11:34:57.595183Z","shell.execute_reply":"2024-11-27T11:34:57.644963Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def save_checkpoint(model, optimizer, filename=\"my_checkpoint.pth.tar\"):\n    print(\"=> Saving checkpoint\")\n    checkpoint = {\n        \"state_dict\": model.state_dict(),\n        \"optimizer\": optimizer.state_dict(),\n    }\n    torch.save(checkpoint, filename)\n\n\ndef load_checkpoint(checkpoint_file, model, optimizer, lr):\n    print(\"=> Loading checkpoint\")\n    checkpoint = torch.load(checkpoint_file, map_location=DEVICE)\n    model.load_state_dict(checkpoint[\"state_dict\"])\n    optimizer.load_state_dict(checkpoint[\"optimizer\"])\n\n    # If we don't do this then it will just have learning rate of old checkpoint\n    # and it will lead to many hours of debugging \\:\n    for param_group in optimizer.param_groups:\n        param_group[\"lr\"] = lr\n\n\ndef seed_everything(seed=42):\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = False","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:57.647095Z","iopub.execute_input":"2024-11-27T11:34:57.647571Z","iopub.status.idle":"2024-11-27T11:34:57.659380Z","shell.execute_reply.started":"2024-11-27T11:34:57.647531Z","shell.execute_reply":"2024-11-27T11:34:57.658513Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# !mkdir saved_images","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:57.660514Z","iopub.execute_input":"2024-11-27T11:34:57.660843Z","iopub.status.idle":"2024-11-27T11:34:57.670905Z","shell.execute_reply.started":"2024-11-27T11:34:57.660806Z","shell.execute_reply":"2024-11-27T11:34:57.670116Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def train_fn(disc_P, disc_M, gen_P, gen_M, loader, opt_disc, opt_gen, l1, mse, d_scaler, g_scaler, epoch):\n    loop = tqdm(loader, leave = True)\n    for idx, (monet, photo) in enumerate(loop):\n        monet = monet.to(DEVICE)\n        photo = photo.to(DEVICE)\n\n        with torch.cuda.amp.autocast():\n            fake_photo = gen_P(monet)\n            disc_pho_real = disc_P(photo)\n            disc_pho_fake = disc_P(fake_photo.detach())\n            disc_pho_real_loss = mse(disc_pho_real, torch.ones_like(disc_pho_real))\n            disc_pho_fake_loss = mse(disc_pho_fake, torch.zeros_like(disc_pho_fake))\n            disc_pho_loss = disc_pho_fake_loss + disc_pho_real_loss\n\n            fake_monet = gen_P(photo)\n            disc_mon_real = disc_M(monet)\n            disc_mon_fake = disc_M(fake_monet.detach())\n            disc_mon_real_loss = mse(disc_mon_real, torch.ones_like(disc_mon_real))\n            disc_mon_fake_loss = mse(disc_mon_fake, torch.zeros_like(disc_mon_fake))\n            disc_mon_loss = disc_mon_fake_loss + disc_mon_real_loss\n\n            disc_loss = (disc_mon_loss + disc_pho_loss) / 2\n\n        opt_disc.zero_grad()\n        d_scaler.scale(disc_loss).backward()\n        d_scaler.step(opt_disc)\n        d_scaler.update()\n\n\n        with torch.cuda.amp.autocast():\n            disc_pho_fake = disc_P(fake_photo)\n            disc_mon_fake = disc_M(fake_monet)\n            loss_gen_mon = mse(disc_mon_fake, torch.ones_like(disc_mon_fake))\n            loss_gen_pho = mse(disc_pho_fake, torch.ones_like(disc_pho_fake))\n\n            cycle_monet = gen_M(fake_photo)\n            cycle_photo = gen_P(fake_monet)\n            cycle_mon_loss = l1(monet, cycle_monet)\n            cycle_pho_loss = l1(photo, cycle_photo)\n\n            idt_monet = gen_M(monet)\n            idt_photo = gen_P(photo)\n            idt_mon_loss = l1(monet, idt_monet)\n            idt_pho_loss = l1(photo, idt_photo)\n\n            gen_loss = (loss_gen_mon \n                        + loss_gen_pho \n                        + cycle_mon_loss*LAMBDA_CYCLE \n                        + cycle_pho_loss*LAMBDA_CYCLE \n                        + idt_mon_loss*LAMBDA_IDENTITY \n                        + idt_pho_loss*LAMBDA_IDENTITY)\n            \n            opt_gen.zero_grad()\n            g_scaler.scale(gen_loss).backward()\n            g_scaler.step(opt_gen)\n            g_scaler.update()\n\n            # if idx % 200 == 0:\n            #     save_image(fake_photo*0.5+0.5, f\"/kaggle/working/saved_images/photo_{epoch}_{idx}.png\")\n            #     save_image(fake_monet*0.5+0.5, f\"/kaggle/working/saved_images/monet_{epoch}_{idx}.png\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:57.672268Z","iopub.execute_input":"2024-11-27T11:34:57.672778Z","iopub.status.idle":"2024-11-27T11:34:57.682456Z","shell.execute_reply.started":"2024-11-27T11:34:57.672737Z","shell.execute_reply":"2024-11-27T11:34:57.681594Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def main():\n    disc_P = Discriminator(3).to(DEVICE)\n    disc_M = Discriminator(3).to(DEVICE)\n    gen_M = Generator(3, 9).to(DEVICE)\n    gen_P = Generator(3, 9).to(DEVICE)\n    opt_disc = optim.Adam(\n        list(disc_P.parameters()) + list(disc_M.parameters()),\n        lr=LEARNING_RATE,\n        betas=(0.5, 0.999),\n    )\n\n    opt_gen = optim.Adam(\n        list(gen_M.parameters()) + list(gen_P.parameters()),\n        lr=LEARNING_RATE,\n        betas=(0.5, 0.999),\n    )\n\n    L1 = nn.L1Loss()\n    mse = nn.MSELoss()\n\n    if LOAD_MODEL:\n        load_checkpoint(\n            CHECKPOINT_GEN_P,\n            gen_P,\n            opt_gen,\n            LEARNING_RATE,\n        )\n        load_checkpoint(\n            CHECKPOINT_GEN_M,\n            gen_M,\n            opt_gen,\n            LEARNING_RATE,\n        )\n        load_checkpoint(\n            CHECKPOINT_CRITIC_P,\n            disc_P,\n            opt_disc,\n            LEARNING_RATE,\n        )\n        load_checkpoint(\n            CHECKPOINT_CRITIC_M,\n            disc_M,\n            opt_disc,\n            LEARNING_RATE,\n        )\n\n    tot_dataset = Monet()\n    #train_indices, val_indices = train_test_split(range(len(tot_dataset)), test_size= 0.2)\n    #dataset = Subset(tot_dataset, train_indices)\n    #val_dataset = Subset(dataset, val_indices)\n    #val_loader = DataLoader(\n    #    val_dataset,\n    #    batch_size=1,\n    #    shuffle=False,\n     #   pin_memory=True,\n    #)\n    loader = DataLoader(\n        tot_dataset,\n        batch_size=BATCH_SIZE,\n        shuffle=True,\n        num_workers=NUM_WORKERS,\n        pin_memory=True,\n    )\n    g_scaler = torch.amp.GradScaler()\n    d_scaler = torch.amp.GradScaler()\n\n    for epoch in range(NUM_EPOCHS):\n        train_fn(\n            disc_P,\n            disc_M,\n            gen_M,\n            gen_P,\n            loader,\n            opt_disc,\n            opt_gen,\n            L1,\n            mse,\n            d_scaler,\n            g_scaler,\n            epoch\n        )\n\n        # if SAVE_MODEL:\n        #     save_checkpoint(gen_P, opt_gen, filename=CHECKPOINT_GEN_P)\n        #     save_checkpoint(gen_M, opt_gen, filename=CHECKPOINT_GEN_M)\n        #     save_checkpoint(disc_P, opt_disc, filename=CHECKPOINT_CRITIC_P)\n        #     save_checkpoint(disc_M, opt_disc, filename=CHECKPOINT_CRITIC_M)\n\n    newdataset = Monet()\n    with torch.no_grad():\n        for i, (_,img) in enumerate(DataLoader(newdataset, batch_size=1, shuffle=False)):\n            prediction = gen_M(img.to(DEVICE))[0].cpu().permute(1, 2, 0).numpy()* 0.5 + 0.5\n            im = Image.fromarray((prediction * 255).astype(np.uint8))\n            im.save(\"../images/\" + str(i) + \".jpg\")\n            print(str(i) + \".jpg saved\")\n    shutil.make_archive(\"/kaggle/working/images\", 'zip', \"/kaggle/images\")\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:57.683831Z","iopub.execute_input":"2024-11-27T11:34:57.684175Z","iopub.status.idle":"2024-11-27T11:34:57.696184Z","shell.execute_reply.started":"2024-11-27T11:34:57.684140Z","shell.execute_reply":"2024-11-27T11:34:57.695408Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"main()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-27T11:34:57.697277Z","iopub.execute_input":"2024-11-27T11:34:57.698055Z","iopub.status.idle":"2024-11-27T14:12:11.419394Z","shell.execute_reply.started":"2024-11-27T11:34:57.698017Z","shell.execute_reply":"2024-11-27T14:12:11.418530Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}