{"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":"none","dataSources":[{"sourceId":15062,"databundleVersionId":545987,"sourceType":"competition"}],"dockerImageVersionId":30746,"isInternetEnabled":true,"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","execution":{"iopub.status.busy":"2024-07-16T18:35:53.732708Z","iopub.execute_input":"2024-07-16T18:35:53.73313Z","iopub.status.idle":"2024-07-16T18:35:54.956767Z","shell.execute_reply.started":"2024-07-16T18:35:53.733093Z","shell.execute_reply":"2024-07-16T18:35:54.955358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np, pandas as pd, os\nimport xml.etree.ElementTree as ET \nimport matplotlib.pyplot as plt, zipfile \nfrom PIL import Image \nfrom glob import glob","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:35:54.959174Z","iopub.execute_input":"2024-07-16T18:35:54.959859Z","iopub.status.idle":"2024-07-16T18:35:54.965855Z","shell.execute_reply.started":"2024-07-16T18:35:54.959813Z","shell.execute_reply":"2024-07-16T18:35:54.96451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt # for plotting\nimport numpy as np # for transformation\n\nimport torch # PyTorch package\nimport torchvision # load datasets\nimport torchvision.transforms as transforms # transform data\nimport torch.nn as nn # basic building block for neural neteorks\nimport torch.nn.functional as F # import convolution functions like Relu\nimport torch.optim as optim # optimzer","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:35:54.967434Z","iopub.execute_input":"2024-07-16T18:35:54.967871Z","iopub.status.idle":"2024-07-16T18:36:00.89188Z","shell.execute_reply.started":"2024-07-16T18:35:54.967839Z","shell.execute_reply":"2024-07-16T18:36:00.890674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms\nfrom torchvision.utils import save_image\nfrom tqdm import tqdm\nimport torchvision.datasets as datasets  \nfrom torch.utils.data import DataLoader  \n#from torchvision.datasets import ImageFolder","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:00.89438Z","iopub.execute_input":"2024-07-16T18:36:00.894916Z","iopub.status.idle":"2024-07-16T18:36:00.902821Z","shell.execute_reply.started":"2024-07-16T18:36:00.894881Z","shell.execute_reply":"2024-07-16T18:36:00.901465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#!pip install models","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:00.904443Z","iopub.execute_input":"2024-07-16T18:36:00.904814Z","iopub.status.idle":"2024-07-16T18:36:00.91361Z","shell.execute_reply.started":"2024-07-16T18:36:00.904782Z","shell.execute_reply":"2024-07-16T18:36:00.912355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.utils.data import TensorDataset, DataLoader\nfrom collections import defaultdict\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:00.915051Z","iopub.execute_input":"2024-07-16T18:36:00.915436Z","iopub.status.idle":"2024-07-16T18:36:02.325698Z","shell.execute_reply.started":"2024-07-16T18:36:00.915401Z","shell.execute_reply":"2024-07-16T18:36:02.324494Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd /kaggle/input/generative-dog-images","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:02.327346Z","iopub.execute_input":"2024-07-16T18:36:02.327866Z","iopub.status.idle":"2024-07-16T18:36:02.335511Z","shell.execute_reply.started":"2024-07-16T18:36:02.327776Z","shell.execute_reply":"2024-07-16T18:36:02.334343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\nimport os","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:02.336771Z","iopub.execute_input":"2024-07-16T18:36:02.337166Z","iopub.status.idle":"2024-07-16T18:36:02.346351Z","shell.execute_reply.started":"2024-07-16T18:36:02.337136Z","shell.execute_reply":"2024-07-16T18:36:02.345252Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#os.mkdir('/kaggle/working/generative-dog-images/')","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:13.281033Z","iopub.execute_input":"2024-07-16T18:36:13.281954Z","iopub.status.idle":"2024-07-16T18:36:13.28673Z","shell.execute_reply.started":"2024-07-16T18:36:13.281916Z","shell.execute_reply":"2024-07-16T18:36:13.285334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = '/kaggle/working/generative-dog-images/'","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:13.464456Z","iopub.execute_input":"2024-07-16T18:36:13.464871Z","iopub.status.idle":"2024-07-16T18:36:13.471109Z","shell.execute_reply.started":"2024-07-16T18:36:13.46484Z","shell.execute_reply":"2024-07-16T18:36:13.469622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"unzipper = zipfile.ZipFile('Annotation.zip', 'r')\nunzipper.extractall(path)","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:13.690583Z","iopub.execute_input":"2024-07-16T18:36:13.691011Z","iopub.status.idle":"2024-07-16T18:36:21.896708Z","shell.execute_reply.started":"2024-07-16T18:36:13.690978Z","shell.execute_reply":"2024-07-16T18:36:21.895483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#os.mkdir('/kaggle/working/generative-dog-images/')","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:21.898666Z","iopub.execute_input":"2024-07-16T18:36:21.899028Z","iopub.status.idle":"2024-07-16T18:36:21.904097Z","shell.execute_reply.started":"2024-07-16T18:36:21.899Z","shell.execute_reply":"2024-07-16T18:36:21.902825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#path = '/kaggle/working/generative-dog-images/'","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:21.905568Z","iopub.execute_input":"2024-07-16T18:36:21.905977Z","iopub.status.idle":"2024-07-16T18:36:21.918973Z","shell.execute_reply.started":"2024-07-16T18:36:21.905915Z","shell.execute_reply":"2024-07-16T18:36:21.917692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"unzipper = zipfile.ZipFile('all-dogs.zip', 'r')\nunzipper.extractall(path)","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:21.921214Z","iopub.execute_input":"2024-07-16T18:36:21.921632Z","iopub.status.idle":"2024-07-16T18:36:37.745636Z","shell.execute_reply.started":"2024-07-16T18:36:21.9216Z","shell.execute_reply":"2024-07-16T18:36:37.744341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ComputeLB = True\nDogsOnly = True\n\nROOT = '/kaggle/working/generative-dog-images/'\nif not ComputeLB: ROOT = '../input/'\nIMAGES = os.listdir(ROOT + 'all-dogs')\nbreeds = os.listdir(ROOT + 'Annotation') \n\nidxIn = 0; namesIn = []\nimagesIn = np.zeros((25000,64,64,3))\n\n# CROP WITH BOUNDING BOXES TO GET DOGS ONLY\n# https://www.kaggle.com/paulorzp/show-annotations-and-breeds\nif DogsOnly:\n    for breed in breeds:\n        for dog in os.listdir(ROOT+'Annotation/'+breed):\n            try: img = Image.open(ROOT+'all-dogs/'+dog+'.jpg') \n            except: continue           \n            tree = ET.parse(ROOT+'Annotation/'+breed+'/'+dog)\n            root = tree.getroot()\n            objects = root.findall('object')\n            for o in objects:\n                bndbox = o.find('bndbox') \n                xmin = int(bndbox.find('xmin').text)\n                ymin = int(bndbox.find('ymin').text)\n                xmax = int(bndbox.find('xmax').text)\n                ymax = int(bndbox.find('ymax').text)\n                w = np.min((xmax - xmin, ymax - ymin))\n                img2 = img.crop((xmin, ymin, xmin+w, ymin+w))\n                img2 = img2.resize((64,64), Image.ANTIALIAS)\n                imagesIn[idxIn,:,:,:] = np.asarray(img2)\n                #if idxIn%1000==0: print(idxIn)\n                namesIn.append(breed)\n                idxIn += 1\n    idx = np.arange(idxIn)\n    np.random.shuffle(idx)\n    imagesIn = imagesIn[idx,:,:,:]\n    namesIn = np.array(namesIn)[idx]\n    \n# RANDOMLY CROP FULL IMAGES\nelse:\n    x = np.random.choice(np.arange(20579),10000)\n    for k in range(len(x)):\n        img = Image.open(ROOT + 'all-dogs/all-dogs/' + IMAGES[x[k]])\n        w = img.size[0]\n        h = img.size[1]\n        sz = np.min((w,h))\n        a=0; b=0\n        if w<h: b = (h-sz)//2\n        else: a = (w-sz)//2\n        img = img.crop((0+a, 0+b, sz+a, sz+b))  \n        img = img.resize((64,64), Image.ANTIALIAS)   \n        imagesIn[idxIn,:,:,:] = np.asarray(img)\n        namesIn.append(IMAGES[x[k]])\n        if idxIn%1000==0: print(idxIn)\n        idxIn += 1\n    \n# DISPLAY CROPPED IMAGES\nx = np.random.randint(0,idxIn,25)\nfor k in range(5):\n    plt.figure(figsize=(15,3))\n    for j in range(5):\n        plt.subplot(1,5,j+1)\n        img = Image.fromarray( imagesIn[x[k*5+j],:,:,:].astype('uint8') )\n        plt.axis('off')\n        if not DogsOnly: plt.title(namesIn[x[k*5+j]],fontsize=11)\n        else: plt.title(namesIn[x[k*5+j]].split('-')[1],fontsize=11)\n        plt.imshow(img)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:36:37.747603Z","iopub.execute_input":"2024-07-16T18:36:37.748003Z","iopub.status.idle":"2024-07-16T18:37:52.886026Z","shell.execute_reply.started":"2024-07-16T18:36:37.747971Z","shell.execute_reply":"2024-07-16T18:37:52.884883Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# transform = transforms.Compose( # composing several transforms together\n#     [transforms.ToTensor(), # to tensor object\n#      transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) # mean = 0.5, std = 0.5\n\n# set batch_size\nbatch_size = 4\n\n# set number of workers\nnum_workers = 2","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:52.887548Z","iopub.execute_input":"2024-07-16T18:37:52.88797Z","iopub.status.idle":"2024-07-16T18:37:52.894757Z","shell.execute_reply.started":"2024-07-16T18:37:52.887934Z","shell.execute_reply":"2024-07-16T18:37:52.89343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"idxIn = 25000; namesIn = []\n#imagesIn = np.zeros((25000,64,64,3))\nimagesIn = np.zeros((120,64,64,3))","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:52.896988Z","iopub.execute_input":"2024-07-16T18:37:52.897457Z","iopub.status.idle":"2024-07-16T18:37:52.920982Z","shell.execute_reply.started":"2024-07-16T18:37:52.897426Z","shell.execute_reply":"2024-07-16T18:37:52.919669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#ls /kaggle/working/generative-dog-images/Annotation\n#I might need to wrap the following dog names in quotes\n#it is showing 'NameError: _ is undefined'","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:52.922751Z","iopub.execute_input":"2024-07-16T18:37:52.923331Z","iopub.status.idle":"2024-07-16T18:37:52.929344Z","shell.execute_reply.started":"2024-07-16T18:37:52.923287Z","shell.execute_reply":"2024-07-16T18:37:52.928011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"namesIn = ['African_hunting_dog',\n'Chihuahua',\n'Japanese_spaniel',\n'Maltese_dog',\n'Pekinese',\n'Tzu',\n'Blenheim_spaniel',\n'papillon',\n'toy_terrier',\n'Rhodesian_ridgeback',\n'Afghan_hound',\n'basset',\n'beagle',\n'bloodhound',\n'bluetick',\n'tan_coonhound',\n'Walker_hound',\n'English_foxhound',\n'redbone',\n'borzoi',\n'Irish_wolfhound',\n'Italian_greyhound',\n'whippet',\n'Ibizan_hound',\n'Norwegian_elkhound',\n'otterhound',\n'Saluki',\n'Scottish_deerhound',\n'Weimaraner',\n'Staffordshire_bullterrier',\n'American_Staffordshire_terrier',\n'Bedlington_terrier',\n'Border_terrier',\n'Kerry_blue_terrier',\n'Irish_terrier',\n'Norfolk_terrier',\n'Norwich_terrier',\n'Yorkshire_terrier',\n'haired_fox_terrier',\n'Lakeland_terrier',\n'Sealyham_terrier',\n'Airedale',\n'cairn',\n'Australian_terrier',\n'Dandie_Dinmont',\n'Boston_bull',\n'miniature_schnauzer',\n'giant_schnauzer',\n'standard_schnauzer',\n'Scotch_terrier',\n'Tibetan_terrier',\n'silky_terrier',\n'coated_wheaten_terrier',\n'West_Highland_white_terrier',\n'Lhasa',\n'coated_retriever',\n#'coated_retriever',\n'golden_retriever',\n'Labrador_retriever',\n'Chesapeake_Bay_retriever',\n'haired_pointer',\n'vizsla',\n'English_setter',\n'Irish_setter',\n'Gordon_setter',\n'Brittany_spaniel',\n'clumber',\n'English_springer',\n'Welsh_springer_spaniel',\n'cocker_spaniel',\n'Sussex_spaniel',\n'Irish_water_spaniel',\n'kuvasz',\n'schipperke',\n'groenendael',\n'malinois',\n'briard',\n'kelpie',\n'komondor',\n'Old_English_sheepdoc',\n'Shetland_sheepdog',\n'collie',\n'Border_collie',\n'Bouvier_des_Flandres',\n'Rottweiler',\n'German_shepherd',\n'Doberman',\n'miniature_pinscher',\n'Greater_Swiss_Mountain_dog',\n'Bernese_mountain_dog',\n'Appenzeller',\n'EntleBucher',\n'boxer',\n'bull_mastiff',\n'Tibetan_mastiff',\n'French_bulldog',\n'Great_Dane',\n'Saint_Bernard',\n'Eskimo_dog',\n'malamute',\n'Siberian_husky',\n'affenpinscher',\n'basenji',\n'pug',\n'Leonberg',\n'Newfoundland',\n'Great_Pyrenees',\n'Samoyed',\n'Pomeranian',\n'chow',\n'keeshond',\n'Brabancon_griffon',\n'Pembroke',\n'Cardigan',\n'toy_poodle',\n'miniature_poodle',\n'standard_poode',\n'Mexican_hairless',\n'dingo',\n'dhole',\n'African_hunting_dog']","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:52.930941Z","iopub.execute_input":"2024-07-16T18:37:52.931497Z","iopub.status.idle":"2024-07-16T18:37:52.944919Z","shell.execute_reply.started":"2024-07-16T18:37:52.931453Z","shell.execute_reply":"2024-07-16T18:37:52.943362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# idxIn = 0; namesIn = []\n# imagesIn = np.zeros((25000,64,64,3))\n              \n#print(f'The shape of image is {imagesIn.shape}, the shape of imagename is {namesIn.shape}')\nimagesIntorch = np.array([np.array(image).transpose(2, 1, 0) for image in imagesIn])\nprint(f'The shape of reshaped image is {imagesIntorch.shape}')\ndogs = list(set(namesIn))\nlen_dogs = len(dogs)\nprint(f'the number of dogs is {len_dogs}')\ndog2id = {dogs[i]:i for i in range(len(dogs))}\nid2dog = {v : k for k, v in dog2id.items()}\n# print(dog2id, id2dog)\nidIn = [dog2id[name] for name in namesIn]\n\ntrain_X, validation_X, train_y, validation_y = train_test_split(imagesIntorch, idIn, test_size=0.2, random_state=42)\n\nnp.array(train_X).shape, np.array(validation_X).shape, np.array(train_y).shape, np.array(validation_y).shape\n# train_X = train_X/255.\n# validation_X = validation_X/255.\n\ntraining_data = TensorDataset(torch.Tensor(train_X), torch.Tensor(train_y))\nvalidation_data = TensorDataset(torch.Tensor(validation_X), torch.Tensor(validation_y))\ndata_variance = np.var(train_X)","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:52.949673Z","iopub.execute_input":"2024-07-16T18:37:52.950086Z","iopub.status.idle":"2024-07-16T18:37:53.029454Z","shell.execute_reply.started":"2024-07-16T18:37:52.950055Z","shell.execute_reply":"2024-07-16T18:37:53.028155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset=imagesIntorch","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:53.030902Z","iopub.execute_input":"2024-07-16T18:37:53.031242Z","iopub.status.idle":"2024-07-16T18:37:53.036228Z","shell.execute_reply.started":"2024-07-16T18:37:53.031216Z","shell.execute_reply":"2024-07-16T18:37:53.034799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = transforms.Compose([\n    transforms.Grayscale(num_output_channels=1),\n    transforms.Resize((224, 224)),\n    transforms.ToTensor(),\n    #transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n])","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:53.037792Z","iopub.execute_input":"2024-07-16T18:37:53.038151Z","iopub.status.idle":"2024-07-16T18:37:53.049674Z","shell.execute_reply.started":"2024-07-16T18:37:53.038122Z","shell.execute_reply":"2024-07-16T18:37:53.048339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_loader = DataLoader(training_data, \n                             batch_size=batch_size, \n                             shuffle=True,\n                             pin_memory=True)","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:53.050993Z","iopub.execute_input":"2024-07-16T18:37:53.051372Z","iopub.status.idle":"2024-07-16T18:37:53.067608Z","shell.execute_reply.started":"2024-07-16T18:37:53.051343Z","shell.execute_reply":"2024-07-16T18:37:53.06647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"testloader = DataLoader(validation_data,\n                               batch_size=batch_size,\n                               shuffle=True,\n                               pin_memory=True)","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:53.069178Z","iopub.execute_input":"2024-07-16T18:37:53.069967Z","iopub.status.idle":"2024-07-16T18:37:53.080735Z","shell.execute_reply.started":"2024-07-16T18:37:53.0699Z","shell.execute_reply":"2024-07-16T18:37:53.078968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_loader = DataLoader(validation_data,\n                               batch_size=batch_size,\n                               shuffle=True,\n                               pin_memory=True)","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:53.082566Z","iopub.execute_input":"2024-07-16T18:37:53.082965Z","iopub.status.idle":"2024-07-16T18:37:53.094446Z","shell.execute_reply.started":"2024-07-16T18:37:53.082936Z","shell.execute_reply":"2024-07-16T18:37:53.093253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nINPUT_DIM = 64*64\nZ_DIM = 20\nH_DIM = 200\nNUM_EPOCHS = 10\nBATCH_SIZE = 32\nLR_RATE = 3e-4","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:53.095872Z","iopub.execute_input":"2024-07-16T18:37:53.096274Z","iopub.status.idle":"2024-07-16T18:37:53.108512Z","shell.execute_reply.started":"2024-07-16T18:37:53.096229Z","shell.execute_reply":"2024-07-16T18:37:53.107296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nclass VariationalAutoEncoder(nn.Module):\n    def __init__(self, input_dim, z_dim, h_dim=200):\n        super().__init__()\n        # encoder\n        self.img_2hid1 = nn.Linear(49152, 12544)\n        self.img_2hid2 = nn.Linear(12544, 2601)\n        self.img_2hid3 = nn.Linear(2601, 200)\n\n        # one for mu and one for stds, note how we only output\n        # diagonal values of covariance matrix. Here we assume\n        # the pixels are conditionally independent \n        self.hid_2mu = nn.Linear(200, 2)\n        self.hid_2sigma = nn.Linear(200, 2)\n\n        # decoder\n        self.z_2hid1 = nn.Linear(2, 200)\n        self.z_2hid2 = nn.Linear(200, 2601)\n        self.z_2hid3 = nn.Linear(2601, 12544)\n        self.hid_2img = nn.Linear(12544, 49152)\n\n    def encode(self, x):\n        h = F.relu(self.img_2hid1(x))\n        h = F.relu(self.img_2hid2(h))\n        h = F.relu(self.img_2hid3(h))\n        mu = self.hid_2mu(h)\n        sigma = self.hid_2sigma(h)\n        return mu, sigma\n\n    def decode(self, z):\n        new_h = F.relu(self.z_2hid1(z))\n        new_h = F.relu(self.z_2hid2(new_h))\n        new_h = F.relu(self.z_2hid3(new_h))\n        x = torch.sigmoid(self.hid_2img(new_h))\n        return x\n\n    def forward(self, x):\n        mu, sigma = self.encode(x)\n\n        # Sample from latent distribution from encoder\n        epsilon = torch.randn_like(sigma)\n        z_reparametrized = mu + sigma*epsilon\n\n        x = self.decode(z_reparametrized)\n        return x, mu, sigma","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:53.109677Z","iopub.execute_input":"2024-07-16T18:37:53.110037Z","iopub.status.idle":"2024-07-16T18:37:53.124677Z","shell.execute_reply.started":"2024-07-16T18:37:53.11Z","shell.execute_reply":"2024-07-16T18:37:53.123056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def train(num_epochs, model, optimizer, loss_fn):\n    # Start training\n    for epoch in range(num_epochs):\n        loop = tqdm(enumerate(train_loader))\n        for i, (x, y) in loop:\n            # Forward pass\n            #x = x.to(device).view(-1, INPUT_DIM)\n            x = x.to(device).view(49152)\n            x_reconst, mu, sigma = model(x)\n\n            # loss, formulas from https://www.youtube.com/watch?v=igP03FXZqgo&t=2182s\n            reconst_loss = loss_fn(x_reconst, x)\n            kl_div = - torch.sum(1 + torch.log(sigma.pow(2)) - mu.pow(2) - sigma.pow(2))\n\n            # Backprop and optimize\n            loss = reconst_loss + kl_div\n            optimizer.zero_grad()\n            loss.backward()\n            optimizer.step()\n            loop.set_postfix(loss=loss.item())\n# Initialize model, optimizer, loss\n","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:53.126386Z","iopub.execute_input":"2024-07-16T18:37:53.126805Z","iopub.status.idle":"2024-07-16T18:37:53.144451Z","shell.execute_reply.started":"2024-07-16T18:37:53.126774Z","shell.execute_reply":"2024-07-16T18:37:53.143077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = VariationalAutoEncoder(4096, 20).to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=LR_RATE)\nloss_fn = nn.BCELoss(reduction=\"sum\")","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:37:53.146092Z","iopub.execute_input":"2024-07-16T18:37:53.146967Z","iopub.status.idle":"2024-07-16T18:38:07.399853Z","shell.execute_reply.started":"2024-07-16T18:37:53.146925Z","shell.execute_reply":"2024-07-16T18:38:07.398149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train(NUM_EPOCHS, model, optimizer, loss_fn)","metadata":{"execution":{"iopub.status.busy":"2024-07-16T18:38:07.40184Z","iopub.execute_input":"2024-07-16T18:38:07.402388Z","iopub.status.idle":"2024-07-16T19:41:05.00303Z","shell.execute_reply.started":"2024-07-16T18:38:07.402342Z","shell.execute_reply":"2024-07-16T19:41:05.000964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def inference(digit, num_examples=1):\n    \"\"\"\n    Generates (num_examples) of a particular digit.\n    Specifically we extract an example of each digit,\n    then after we have the mu, sigma representation for\n    each digit we can sample from that.\n\n    After we sample we can run the decoder part of the VAE\n    and generate examples.\n    \"\"\"\n    images = []\n    idx = 0\n    for (x, y) in dataset:\n        if y == idx:\n            images.append(x)\n            idx += 1\n        if idx == 2:\n            break\n\n    encodings_digit = []\n    for d in range(2):\n        with torch.no_grad():\n            mu, sigma = model.encode(images[d].view(1, 4096))\n        encodings_digit.append((mu, sigma))\n\n    mu, sigma = encodings_digit[digit]\n    for example in range(num_examples):\n        epsilon = torch.randn_like(sigma)\n        z = mu + sigma * epsilon\n        out = model.decode(z)\n        out = out.view(-1, 1, 28, 28)\n        save_image(out, f\"generated_{digit}_ex{example}.png\")\ninference(1)","metadata":{"execution":{"iopub.status.busy":"2024-07-16T20:04:27.667922Z","iopub.execute_input":"2024-07-16T20:04:27.668414Z","iopub.status.idle":"2024-07-16T20:04:27.746736Z","shell.execute_reply.started":"2024-07-16T20:04:27.668377Z","shell.execute_reply":"2024-07-16T20:04:27.74513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install models","metadata":{"execution":{"iopub.status.busy":"2024-07-16T20:04:20.505576Z","iopub.execute_input":"2024-07-16T20:04:20.506129Z","iopub.status.idle":"2024-07-16T20:04:23.301358Z","shell.execute_reply.started":"2024-07-16T20:04:20.506097Z","shell.execute_reply":"2024-07-16T20:04:23.299822Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Works Cited**","metadata":{}},{"cell_type":"markdown","source":"https://medium.com/bitgrit-data-science-publication/building-an-image-classification-model-with-pytorch-from-scratch-f10452073212 - i could not make it work - too confusing.\n\nhttps://www.kaggle.com/code/tenffe/vqvae-for-dog-image-generation\n\nhttps://github.com/t-m-d-k/Pytorch-Series/blob/main/CustomVAE-Final.ipynb\n\n#the one with the image cropper","metadata":{}},{"cell_type":"markdown","source":"**Notes**","metadata":{}},{"cell_type":"markdown","source":"Ten epochs are unnecessary.  the loss becomes teeny tiny around 6","metadata":{}},{"cell_type":"markdown","source":"I do not know how to solve these except by extensive tinkering.  Apparently, you *can* use a Bayesian CNN in this situation, no one did though.  I wonder why not?","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}