1
1
import sklearn
2
2
from sklearn .datasets import make_circles
3
3
# Make 100 Samples
4
- n_samples = 10000
5
- X ,y = make_circles (n_samples ,noise = 0.125 ,random_state = 42 )
4
+ n_samples = 25000
5
+ X ,y = make_circles (n_samples ,noise = 0.0625 ,random_state = 42 )
6
6
7
7
8
8
import matplotlib .pyplot as plt
67
67
class CircleModelV0 (nn .Module ):
68
68
def __init__ (self ):
69
69
super ().__init__ ()
70
- self .layer_1 = nn .Linear (2 ,1024 ) #
71
- self .layer_2 = nn .Linear (1024 ,1 )
70
+ self .layer_1 = nn .Linear (2 ,2048 ) #
71
+ self .layer_2 = nn .Linear (2048 ,1 )
72
+ self .relu = nn .ReLU ()
72
73
73
74
def forward (self ,X ):
74
- return self .layer_2 (self .layer_1 (X )) # x -> layer_1 -> layer_2
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 ))
75
77
76
78
77
79
model_0 = CircleModelV0 ().to (device )
@@ -83,10 +85,10 @@ def forward(self,X):
83
85
list (model_0 .parameters ())
84
86
85
87
86
- model_0 = nn .Sequential (
87
- nn .Linear (in_features = 2 ,out_features = 64 ),
88
- nn .Linear (64 ,1 )
89
- ).to (device )
88
+ # model_0 = nn.Sequential(
89
+ # nn.Linear(in_features=2,out_features=64),
90
+ # nn.Linear(64,1)
91
+ # ).to(device)
90
92
91
93
92
94
untrained_preds = model_0 (X_test )
@@ -99,10 +101,10 @@ def forward(self,X):
99
101
# BCELoss() requries sigmoid to be builtin to the model itself
100
102
101
103
102
- optimizer = torch .optim .SGD (model_0 .parameters (), lr = 0.01 )
104
+ optimizer = torch .optim .Adam (model_0 .parameters ())
103
105
104
106
105
- epochs = 100
107
+ epochs = 10
106
108
batch_size = 32
107
109
108
110
@@ -113,7 +115,174 @@ def accuracy_fn(y_true,y_preds):
113
115
return acc
114
116
115
117
118
+ y_logits = model_0 (X_test )
116
119
117
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
+
118
287
119
288
0 commit comments