{"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":30684,"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\nimport random\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport torch\nfrom torchvision import transforms\nfrom PIL import Image\nconvert_tensor = transforms.ToTensor()\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\nimages = []\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input/'):\n    for filename in filenames:\n        if filename.find(\".jpg\") != -1:\n            if random.random() > 0.5:\n                images.append(convert_tensor(Image.open(dirname + \"/\" + filename)))\nimages = torch.stack(images)\nprint(images.shape)\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-04-18T15:45:11.114229Z","iopub.execute_input":"2024-04-18T15:45:11.114597Z","iopub.status.idle":"2024-04-18T15:46:01.162434Z","shell.execute_reply.started":"2024-04-18T15:45:11.114556Z","shell.execute_reply":"2024-04-18T15:46:01.161407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")","metadata":{"execution":{"iopub.status.busy":"2024-04-18T15:46:01.164475Z","iopub.execute_input":"2024-04-18T15:46:01.165101Z","iopub.status.idle":"2024-04-18T15:46:01.189269Z","shell.execute_reply.started":"2024-04-18T15:46:01.165067Z","shell.execute_reply":"2024-04-18T15:46:01.188027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images = images.view(images.shape[0], -1).to(device)","metadata":{"execution":{"iopub.status.busy":"2024-04-18T15:46:01.190347Z","iopub.execute_input":"2024-04-18T15:46:01.190583Z","iopub.status.idle":"2024-04-18T15:46:02.129797Z","shell.execute_reply.started":"2024-04-18T15:46:01.190562Z","shell.execute_reply":"2024-04-18T15:46:02.128729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch.nn as nn","metadata":{"execution":{"iopub.status.busy":"2024-04-18T15:46:02.132045Z","iopub.execute_input":"2024-04-18T15:46:02.132356Z","iopub.status.idle":"2024-04-18T15:46:02.136511Z","shell.execute_reply.started":"2024-04-18T15:46:02.132331Z","shell.execute_reply":"2024-04-18T15:46:02.135501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class GAN(nn.Module):\n    def __init__(self, in_size, hidden_size, out_size):\n        super().__init__()\n        self.picasso = nn.Sequential(\n            nn.Linear(in_size, hidden_size),\n            nn.ReLU(),\n            nn.Linear(hidden_size, out_size),\n            nn.Sigmoid()\n        )\n        self.critic = nn.Sequential(\n            nn.Linear(out_size, 1),\n            nn.Sigmoid()\n        )\n    def forward(self, ins):\n        return self.picasso(ins)\n    def gan_forward(self, ins):\n        return self.critic(ins)\n    def __call__(self, ins):\n        return self.forward(ins)","metadata":{"execution":{"iopub.status.busy":"2024-04-18T15:46:02.137644Z","iopub.execute_input":"2024-04-18T15:46:02.137930Z","iopub.status.idle":"2024-04-18T15:46:02.145420Z","shell.execute_reply.started":"2024-04-18T15:46:02.137907Z","shell.execute_reply":"2024-04-18T15:46:02.144549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"net = GAN(10, 200, 3 * 256 * 256).to(device)","metadata":{"execution":{"iopub.status.busy":"2024-04-18T15:46:02.146404Z","iopub.execute_input":"2024-04-18T15:46:02.146726Z","iopub.status.idle":"2024-04-18T15:46:02.496320Z","shell.execute_reply.started":"2024-04-18T15:46:02.146696Z","shell.execute_reply":"2024-04-18T15:46:02.495362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"net.gan_forward(net(torch.randn(10).to(device)))","metadata":{"execution":{"iopub.status.busy":"2024-04-18T15:46:02.497550Z","iopub.execute_input":"2024-04-18T15:46:02.497841Z","iopub.status.idle":"2024-04-18T15:46:02.842209Z","shell.execute_reply.started":"2024-04-18T15:46:02.497817Z","shell.execute_reply":"2024-04-18T15:46:02.841244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_epochs = 2\nbatch_size = 2\ntrain_len = len(images)\nnum_steps = (train_len//batch_size) * num_epochs\nlr = 0.0001\noptimG = torch.optim.AdamW(net.picasso.parameters(), lr=lr)\noptimD = torch.optim.SGD(net.critic.parameters(), lr=lr)","metadata":{"execution":{"iopub.status.busy":"2024-04-18T15:46:02.843767Z","iopub.execute_input":"2024-04-18T15:46:02.844137Z","iopub.status.idle":"2024-04-18T15:46:02.850330Z","shell.execute_reply.started":"2024-04-18T15:46:02.844105Z","shell.execute_reply":"2024-04-18T15:46:02.849450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for step in range(num_steps):\n    d_batch_real = images[torch.randint(1, train_len-1, (batch_size//2,))]\n    d_batch_gen = net(torch.randn(batch_size//2, 10).to(device))\n    d_batch = torch.cat((d_batch_real, d_batch_gen)).to(device)\n    d_ys = torch.cat((torch.zeros(batch_size//2, 1), torch.ones(batch_size//2, 1))).to(device)\n    d_out = net.gan_forward(d_batch)\n    \n    d_loss = nn.functional.binary_cross_entropy(d_out, d_ys)\n    optimD.zero_grad()\n    d_loss.backward()\n    optimD.step()\n    \n    \n    g_batch = torch.randn(batch_size, 10).to(device)\n    g_out = net(g_batch)\n    \n    g_loss = net.gan_forward(g_out).sum() / len(g_out)\n    optimG.zero_grad()\n    g_loss.backward()\n    optimG.step()\n    \n    if step % 100 == 0:\n        print(\"Step\", str(step) + \", loss D:\", str(d_loss.item()) + \", loss G:\", g_loss.item())","metadata":{"execution":{"iopub.status.busy":"2024-04-18T15:46:02.851293Z","iopub.execute_input":"2024-04-18T15:46:02.851541Z","iopub.status.idle":"2024-04-18T15:46:51.216428Z","shell.execute_reply.started":"2024-04-18T15:46:02.851519Z","shell.execute_reply":"2024-04-18T15:46:51.215334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torchvision","metadata":{"execution":{"iopub.status.busy":"2024-04-18T15:46:51.224374Z","iopub.execute_input":"2024-04-18T15:46:51.224682Z","iopub.status.idle":"2024-04-18T15:46:51.228781Z","shell.execute_reply.started":"2024-04-18T15:46:51.224656Z","shell.execute_reply":"2024-04-18T15:46:51.227843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with torch.no_grad():\n    ins = torch.randn(10).to(device)\n    net_out = net(ins).view(3, 256, 256)\n    image = torchvision.transforms.functional.to_pil_image(net_out)\n    display(image)","metadata":{"execution":{"iopub.status.busy":"2024-04-18T15:46:51.231388Z","iopub.execute_input":"2024-04-18T15:46:51.231690Z","iopub.status.idle":"2024-04-18T15:46:51.455393Z","shell.execute_reply.started":"2024-04-18T15:46:51.231645Z","shell.execute_reply":"2024-04-18T15:46:51.454425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#import zipfile\n#from PIL import Image\n\n# Create a ZipFile object\n#with zipfile.ZipFile('images.zip', 'w') as zip_file:\n    # Iterate over the PIL images\n#    for x in range(8000):\n#        seed = torch.randn(10).to(device)\n#        out = net(seed).view(3, 256, 256)\n#        image = torchvision.transforms.functional.to_pil_image(out)\n#        # Write the image to the zip file\n#        zip_file.writestr(\"image_\" + str(x) + \".jpg\", image.tobytes())\n\n# Close the ZipFile object\n#zip_file.close()","metadata":{"execution":{"iopub.status.busy":"2024-04-18T15:47:38.285153Z","iopub.execute_input":"2024-04-18T15:47:38.285517Z","iopub.status.idle":"2024-04-18T15:48:01.087008Z","shell.execute_reply.started":"2024-04-18T15:47:38.285489Z","shell.execute_reply":"2024-04-18T15:48:01.085985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"! mkdir ../images\n\nfor i in range(8000):\n    seed = torch.randn(10).to(device)\n    out = net(seed).view(3, 256, 256)\n    image = torchvision.transforms.functional.to_pil_image(out)\n    image.save(\"../images/\" + str(i) + \".jpg\")\n    i += 1\nimport shutil\nshutil.make_archive(\"/kaggle/working/images\", 'zip', \"/kaggle/images\")","metadata":{},"execution_count":null,"outputs":[]}]}