|
| 1 | +import sklearn |
| 2 | +from sklearn.datasets import make_circles |
| 3 | +# Make 100 Samples |
| 4 | +n_samples = 25000 |
| 5 | +X,y = make_circles(n_samples,noise=0.0625,random_state=42) |
| 6 | + |
| 7 | + |
| 8 | +import matplotlib.pyplot as plt |
| 9 | +import numpy as np |
| 10 | +import torch |
| 11 | +device = 'cuda' if torch.cuda.is_available() else 'cpu' |
| 12 | + |
| 13 | + |
| 14 | +X[:5],y[:5] |
| 15 | + |
| 16 | + |
| 17 | +# Make a DataFrame of circle data |
| 18 | +import pandas as pd |
| 19 | + |
| 20 | + |
| 21 | +circles = pd.DataFrame({"X1":X[:,0],"X2":X[:,1],"y":y}) |
| 22 | + |
| 23 | + |
| 24 | +# Visualizing |
| 25 | +plt.scatter(x=X[:,0],y=X[:,1],c=y,cmap=plt.cm.RdYlBu) |
| 26 | + |
| 27 | + |
| 28 | +X_sample = X[0] |
| 29 | +y_sample = y[0] |
| 30 | +X_sample,y_sample,X_sample.shape,y_sample.shape |
| 31 | + |
| 32 | + |
| 33 | +# Turn data into tensors |
| 34 | +import torch |
| 35 | +torch.__version__ |
| 36 | + |
| 37 | + |
| 38 | +X.dtype |
| 39 | + |
| 40 | + |
| 41 | +X = torch.from_numpy(X).type(torch.float32).to(device) |
| 42 | +y = torch.from_numpy(y).type(torch.float32).to(device) |
| 43 | + |
| 44 | + |
| 45 | +X[:2],y[:2] |
| 46 | + |
| 47 | + |
| 48 | +from sklearn.model_selection import train_test_split |
| 49 | + |
| 50 | + |
| 51 | +X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.25,random_state=42) |
| 52 | + |
| 53 | + |
| 54 | +len(X_train),len(y_test) |
| 55 | + |
| 56 | + |
| 57 | +import torch |
| 58 | +from torch import nn |
| 59 | + |
| 60 | +# Make device agnositic code |
| 61 | +device = 'cuda' if torch.cuda.is_available() else 'cpu' |
| 62 | + |
| 63 | + |
| 64 | +device |
| 65 | + |
| 66 | + |
| 67 | +class CircleModelV0(nn.Module): |
| 68 | + def __init__(self): |
| 69 | + super().__init__() |
| 70 | + self.layer_1 = nn.Linear(2,2048) # |
| 71 | + self.layer_2 = nn.Linear(2048,1) |
| 72 | + self.relu = nn.ReLU() |
| 73 | + |
| 74 | + def forward(self,X): |
| 75 | + # return self.layer_2(self.relu(self.layer_1(X))) # x -> layer_1 -> layer_2 |
| 76 | + return self.layer_2(self.layer_1(X)) |
| 77 | + |
| 78 | + |
| 79 | +model_0 = CircleModelV0().to(device) |
| 80 | + |
| 81 | + |
| 82 | +model_0 |
| 83 | + |
| 84 | + |
| 85 | +list(model_0.parameters()) |
| 86 | + |
| 87 | + |
| 88 | +# model_0 = nn.Sequential( |
| 89 | +# nn.Linear(in_features=2,out_features=64), |
| 90 | +# nn.Linear(64,1) |
| 91 | +# ).to(device) |
| 92 | + |
| 93 | + |
| 94 | +untrained_preds = model_0(X_test) |
| 95 | + |
| 96 | + |
| 97 | +untrained_preds[0],y_test[0] |
| 98 | + |
| 99 | + |
| 100 | +loss_fn = nn.BCEWithLogitsLoss() # has the sigmoid function builtin |
| 101 | +# BCELoss() requries sigmoid to be builtin to the model itself |
| 102 | + |
| 103 | + |
| 104 | +optimizer = torch.optim.Adam(model_0.parameters()) |
| 105 | + |
| 106 | + |
| 107 | +epochs = 10 |
| 108 | +batch_size = 32 |
| 109 | + |
| 110 | + |
| 111 | +# Calculate accuracy |
| 112 | +def accuracy_fn(y_true,y_preds): |
| 113 | + correct = torch.eq(y_true,y_preds).sum().item() # gives a False True list -> Tensor no. of true > just normal no. |
| 114 | + acc = correct/len(y_preds)*100 |
| 115 | + return acc |
| 116 | + |
| 117 | + |
| 118 | +y_logits = model_0(X_test) |
| 119 | + |
| 120 | + |
| 121 | +y_preds_probs = torch.sigmoid(y_logits) |
| 122 | + |
| 123 | + |
| 124 | +y_preds_probs.round() |
| 125 | + |
| 126 | + |
| 127 | +y_pred_labels = torch.round(torch.sigmoid(model_0(X_test))) |
| 128 | + |
| 129 | + |
| 130 | +y_preds = torch.round(y_preds_probs) |
| 131 | + |
| 132 | + |
| 133 | +y_preds.squeeze() |
| 134 | + |
| 135 | + |
| 136 | +test_loss_iter = [] |
| 137 | +train_loss_iter = [] |
| 138 | +train_accuracy_iter = [] |
| 139 | +test_accuracy_iter = [] |
| 140 | + |
| 141 | + |
| 142 | +from tqdm import tqdm |
| 143 | + |
| 144 | + |
| 145 | +# get_ipython().run_line_magic("%time", "") |
| 146 | +# epochs = 100 |
| 147 | +# batch_size = 32 |
| 148 | + |
| 149 | +# for epoch in tqdm(range(epochs)): |
| 150 | +# for i in range(0,len(X_train),batch_size): |
| 151 | +# X_batch = X_train[i:i+batch_size] |
| 152 | +# y_batch = y_train[i:i+batch_size] |
| 153 | +# preds = model_0(X_batch) |
| 154 | +# true_preds = torch.round(torch.sigmoid(preds.squeeze())) |
| 155 | +# loss = loss_fn(preds.squeeze(),y_batch.squeeze()) |
| 156 | +# optimizer.zero_grad() |
| 157 | +# loss.backward() |
| 158 | +# optimizer.step() |
| 159 | +# with torch.inference_mode(): |
| 160 | +# y_test_preds = model_0(X_test) |
| 161 | +# loss_test = loss_fn(y_test_preds.squeeze(),y_test.squeeze()) |
| 162 | +# true_test_preds = torch.round(torch.sigmoid(y_test_preds)) |
| 163 | +# train_loss_iter.append(loss.cpu().detach().numpy()) |
| 164 | +# test_loss_iter.append(loss_test.cpu().detach().numpy()) |
| 165 | +# train_accuracy_iter.append(accuracy_fn(y_batch,true_preds)) |
| 166 | +# test_accuracy_iter.append(accuracy_fn(y_test,true_test_preds)) |
| 167 | + |
| 168 | + |
| 169 | +for epoch in tqdm(range(epochs)): |
| 170 | + model_0.train() |
| 171 | + y_logists = model_0(X_train).squeeze() |
| 172 | + y_pred = torch.round(torch.sigmoid(y_logits)) |
| 173 | + loss = loss_fn(y_logists,y_train) |
| 174 | + acc = accuracy_fn(y_true=y_train,y_preds=y_pred) |
| 175 | + optimizer.zero_grad() |
| 176 | + loss.backward() |
| 177 | + optimizer.step() |
| 178 | + model_0.eval() |
| 179 | + with torch.inference_mode(): |
| 180 | + test_logits = model_0(X_test).squeeze() |
| 181 | + test_pred = torch.round(torch.sigmoid(test_logits)) |
| 182 | + |
| 183 | + test_loss = loss_fn(test_logits,y_test) |
| 184 | + test_acc = accuracy_fn(y_true=y_test,y_preds=test_pred) |
| 185 | + |
| 186 | +print(f""" |
| 187 | + Loss : {loss} |
| 188 | + Accuracy : {acc} |
| 189 | + Test Loss : {test_loss} |
| 190 | + Test Accuracy : {test_acc} |
| 191 | + """) |
| 192 | + |
| 193 | + |
| 194 | +import requests |
| 195 | +from pathlib import Path |
| 196 | + |
| 197 | +# Download helper functions from PyTorch repo |
| 198 | +if not Path("helper_functions.py").is_file(): |
| 199 | + request = requests.get("https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/helper_functions.py") |
| 200 | + with open("helper_functions.py","wb") as f: |
| 201 | + f.write(request.content) |
| 202 | + |
| 203 | + |
| 204 | +from helper_functions import * |
| 205 | + |
| 206 | + |
| 207 | +plt.figure(figsize=(12,6)) |
| 208 | +plt.subplot(1,2,1) |
| 209 | +plt.title("Train") |
| 210 | +plot_decision_boundary(model_0,X_train,y_train) |
| 211 | +plt.subplot(1,2,2) |
| 212 | +plt.title("Test") |
| 213 | +plot_decision_boundary(model_0,X_test,y_test) |
| 214 | + |
| 215 | + |
| 216 | +class ClassificationModel(nn.Module): |
| 217 | + def __init__(self): |
| 218 | + super().__init__() |
| 219 | + self.activation = nn.ReLU() |
| 220 | + self.linear1 = nn.Linear(2,256) |
| 221 | + self.linear2 = nn.Linear(256,512) |
| 222 | + self.linear3 = nn.Linear(512,1024) |
| 223 | + self.linear4 = nn.Linear(1024,512) |
| 224 | + self.linear5_output = nn.Linear(512,1) |
| 225 | + |
| 226 | + def forward(self,X): |
| 227 | + X = self.activation(self.linear1(X)) |
| 228 | + X = self.activation(self.linear2(X)) |
| 229 | + X = self.activation(self.linear3(X)) |
| 230 | + X = self.activation(self.linear4(X)) |
| 231 | + X = self.linear5_output(X) |
| 232 | + return X |
| 233 | + |
| 234 | + |
| 235 | +model = ClassificationModel().to(device) |
| 236 | +criterion = nn.BCEWithLogitsLoss() |
| 237 | +optimizer = torch.optim.Adam(model.parameters()) |
| 238 | + |
| 239 | + |
| 240 | +epochs = 150 |
| 241 | +batch_size = 32 |
| 242 | + |
| 243 | + |
| 244 | +import wandb |
| 245 | + |
| 246 | + |
| 247 | +wandb.init(project="02",name="Adjusted") |
| 248 | +for epoch in tqdm(range(epochs)): |
| 249 | + for i in range(0,len(X_train),batch_size): |
| 250 | + torch.cuda.empty_cache() |
| 251 | + model.train() |
| 252 | + X_batch = X_train[i:i+batch_size] |
| 253 | + y_batch = y_train[i:i+batch_size] |
| 254 | + preds = model(X_batch).squeeze() |
| 255 | + norm_preds = torch.round(torch.sigmoid(preds)) |
| 256 | + loss = criterion(preds,y_batch) |
| 257 | + optimizer.zero_grad() |
| 258 | + loss.backward() |
| 259 | + optimizer.step() |
| 260 | + model.eval() |
| 261 | + with torch.inference_mode(): |
| 262 | + train_preds = model(X_train).squeeze() |
| 263 | + test_preds = model(X_test).squeeze() |
| 264 | + loss_test = criterion(test_preds,y_test) |
| 265 | + loss_train = criterion(train_preds,y_train) |
| 266 | + train_preds = torch.round(torch.sigmoid(train_preds)) |
| 267 | + test_preds = torch.round(torch.sigmoid(test_preds)) |
| 268 | + acc_train = accuracy_fn(y_train,train_preds) |
| 269 | + acc_test = accuracy_fn(y_test,test_preds) |
| 270 | + wandb.log({ |
| 271 | + "Train Loss":loss_train, |
| 272 | + "Test Loss":loss_test, |
| 273 | + "Train Accuracy": acc_train, |
| 274 | + "Test Accuracy": acc_test |
| 275 | + }) |
| 276 | +wandb.finish() |
| 277 | + |
| 278 | + |
| 279 | +plt.figure(figsize=(12,6)) |
| 280 | +plt.subplot(1,2,1) |
| 281 | +plt.title("Train") |
| 282 | +plot_decision_boundary(model_0,X_train,y_train) |
| 283 | +plt.subplot(1,2,2) |
| 284 | +plt.title("Test") |
| 285 | +plot_decision_boundary(model_0,X_test,y_test) |
| 286 | + |
| 287 | + |
| 288 | + |
0 commit comments