{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":21755,"databundleVersionId":1475600,"sourceType":"competition"},{"sourceId":471612,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":380242,"modelId":399998},{"sourceId":471979,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":380488,"modelId":400203}],"dockerImageVersionId":31089,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":"2025-07-16T04:02:03.265037Z","iopub.execute_input":"2025-07-16T04:02:03.265692Z","iopub.status.idle":"2025-07-16T04:02:06.077763Z","shell.execute_reply.started":"2025-07-16T04:02:03.265655Z","shell.execute_reply":"2025-07-16T04:02:06.076756Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\n\n'''\nClass for Generator component for DCGAN (Deep Convolutional Adverserial Network)\n'''\nclass Generator(nn.Module):\n    def __init__(self, noise_dim=100, image_channels=3, feature_maps=64):\n        super(Generator, self).__init__()\n\n        '''\n        Generator generates image from noise. That is why we use ConvTranspose2D as its internal layers, and output an image at the end.\n        '''\n        self.net = nn.Sequential(\n            # Input: N * noise_dim * 1 * 1\n            nn.ConvTranspose2d(noise_dim, feature_maps*8, kernel_size=4, stride=1, padding=0, bias=False),\n            nn.BatchNorm2d(feature_maps*8),\n            nn.ReLU(True),\n            # Shape: (N, (feature_maps * 8), 4, 4): (number of images, feature_maps*8, [(I - 1)*S] - 2*P + K, [(I - 1)*S] - 2*P + K --- I = 1\n\n            nn.ConvTranspose2d(feature_maps*8, feature_maps*4, kernel_size=4, stride=2, padding=1, bias=True),\n            nn.BatchNorm2d(feature_maps*4),\n            nn.ReLU(True),\n            # Shape: N * (feature_maps * 4) * 8 * 8: (number of images, feature_maps*8, [(I - 1)*S] - 2*P + K, [(I - 1)*S] - 2*P + K --- I = 4\n\n            nn.ConvTranspose2d(feature_maps*4, feature_maps*2, kernel_size=4, stride=2, padding=1, bias=False),\n            nn.BatchNorm2d(feature_maps*2),\n            nn.ReLU(True),\n            # Shape: N * (feature_maps * 2) * 16 * 16: (number of images, feature_maps*4, [(I - 1)*S] - 2*P + K, [(I - 1)*S] - 2*P + K --- I = 4\n\n            nn.ConvTranspose2d(feature_maps * 2, feature_maps, kernel_size=4, stride=2, padding=1, bias=False),\n            nn.BatchNorm2d(feature_maps),\n            nn.ReLU(True),\n            # Shape: N x (feature_maps) x 32 x 32: (number of images, feature_maps*4, [(I - 1)*S] - 2*P + K, [(I - 1)*S] - 2*P + K --- I = 16\n\n            nn.ConvTranspose2d(feature_maps, feature_maps // 2, kernel_size=4, stride=2, padding=1, bias=False),\n            nn.BatchNorm2d(feature_maps // 2),\n            nn.ReLU(True),\n            # Shape: N x (feature_maps//2) x 64 x 64: (number of images, feature_maps*4, [(I - 1)*S] - 2*P + K, [(I - 1)*S] - 2*P + K --- I = 32\n\n            nn.ConvTranspose2d(feature_maps//2, feature_maps // 4, kernel_size=4, stride=2, padding=1, bias=False),\n            nn.BatchNorm2d(feature_maps // 4),\n            nn.ReLU(True),\n            # Shape: N x (feature_maps//2) x 128 x 128: (number of images, feature_maps*4, [(I - 1)*S] - 2*P + K, [(I - 1)*S] - 2*P + K --- I = 64\n\n            nn.ConvTranspose2d(feature_maps // 4, image_channels, kernel_size=4, stride=2, padding=1, bias=False),\n            nn.Tanh()\n            # Final Output: N x 3 x 256 x 256: (number of images, feature_maps*4, [(I - 1)*S] - 2*P + K, [(I - 1)*S] - 2*P + K --- I = 128\n        )\n    \n    '''\n    Produce output from the network.\n    '''\n    def forward(self, x):\n        return self.net(x)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-16T04:18:42.242025Z","iopub.execute_input":"2025-07-16T04:18:42.242421Z","iopub.status.idle":"2025-07-16T04:18:42.258345Z","shell.execute_reply.started":"2025-07-16T04:18:42.242393Z","shell.execute_reply":"2025-07-16T04:18:42.256668Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\n\n# Initialize model\ngen = Generator()\ngen.load_state_dict(torch.load(\"/kaggle/input/dcgan-checkpoint/pytorch/99-checkpoint/1/gan_checkpoint_99.pth\", map_location='cpu')['generator'])\nprint(gen.eval())\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-16T04:02:12.174018Z","iopub.execute_input":"2025-07-16T04:02:12.174497Z","iopub.status.idle":"2025-07-16T04:02:14.429071Z","shell.execute_reply.started":"2025-07-16T04:02:12.174468Z","shell.execute_reply":"2025-07-16T04:02:14.427582Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-16T04:18:44.493465Z","iopub.execute_input":"2025-07-16T04:18:44.494012Z","iopub.status.idle":"2025-07-16T04:18:44.500554Z","shell.execute_reply.started":"2025-07-16T04:18:44.493978Z","shell.execute_reply":"2025-07-16T04:18:44.499460Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tqdm import tqdm\nimport os\nfrom PIL import Image\nimport zipfile\nimport io\n\nbatch_size = 100\nz_dim = 100  # latent dim\nnum_images = 10_000\n\nzip_path = \"images.zip\"\nzipf = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)\n\nidx = 0\nwith torch.no_grad():\n    for i in tqdm(range(0, num_images, batch_size)):\n        z = torch.randn(batch_size, z_dim, 1, 1).to(device)\n        fake_imgs = gen(z)\n        fake_imgs = (fake_imgs + 1) / 2  # scale from [-1, 1] to [0, 1]\n\n        fake_imgs = (fake_imgs * 255).clamp(0, 255).byte().cpu()  # shape: [B, 3, H, W]\n        for img_tensor in fake_imgs:\n            idx += 1\n            img_pil = Image.fromarray(img_tensor.permute(1, 2, 0).numpy())  # CHW → HWC\n            img_bytes = io.BytesIO()\n            img_pil.save(img_bytes, format='PNG')\n            zipf.writestr(f'image_{idx:05d}.png', img_bytes.getvalue())\n            idx += 1\n\nzipf.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-16T04:32:34.154365Z","iopub.execute_input":"2025-07-16T04:32:34.154783Z","iopub.status.idle":"2025-07-16T04:40:23.718953Z","shell.execute_reply.started":"2025-07-16T04:32:34.154758Z","shell.execute_reply":"2025-07-16T04:40:23.717336Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!zip -rq /kaggle/working/images.zip /kaggle/working/images\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-14T16:25:16.568964Z","iopub.execute_input":"2025-07-14T16:25:16.569475Z","iopub.status.idle":"2025-07-14T16:25:16.753963Z","shell.execute_reply.started":"2025-07-14T16:25:16.569428Z","shell.execute_reply":"2025-07-14T16:25:16.752563Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}