Replies: 1 comment 4 replies
-
Hi chos1npc, nn.BCEWithLogitsLoss function expects raw logits as it's input to calculate the loss. Our model should look similiar to this the nn.ReLU() is our non linear layer
|
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
My error
TODO: I try to add the sigmoid to the model on bottom, I think it can work, but it didn't.
My code
Build a model with non-linear activation functions
from torch import nn
class CircleModelV2(nn.Module):
def init(self):
super().init()
self.layer_1 = nn.Linear(in_features=2, out_features=10)
self.layer_2 = nn.Linear(in_features=10, out_features=10)
self.layer_3 = nn.Linear(in_features=10, out_features=1)
self.relu = nn.ReLU() # relu is a non-linear activation function
self.sigmoid = nn.Sigmoid()
def forward(self, x):
# Where should we put our non-linear activation functions?
return self.layer_3(self.relu(self.layer_2(self.relu(self.layer_1(x)))))
return self.sigmoid(self.layer_3(self.relu(self.layer_2(self.relu(self.layer_1(x))))))
model_3 = CircleModelV2().to(device)
Random seeds
torch.manual_seed(42)
torch.cuda.manual_seed(42)
Put all data on target device
X_train, y_train = X_train.to(device), y_train.to(device)
X_test, y_test = X_test.to(device), y_test.to(device)
Loop through data
epochs = 1000
for epoch in range(epochs):
Training
model_3.train()
1. Forward pass
y_logits = model_3(X_train).squeeze()
y_pred = torch.round(torch.sigmoid(y_logits)) # logits -> prediction probabilities -> prediction labels
y_pred = y_logits
2. Calculate the loss
loss = loss_fn(y_logits, y_train) # BCEWithLogitsLoss (takes in logits as first input)
acc = accuracy_fn(y_true=y_train,
y_pred=y_pred)
3. Optimizer zero grad
optimizer.zero_grad()
4. Loss backward
loss.backward()
5. Step the optimizer
optimizer.step()
Testing
model_3.eval()
with torch.inference_mode():
test_logits = model_3(X_test).squeeze()
test_pred = test_logits
# test_pred = torch.round(torch.sigmoid(test_logits))
Print out what's this happenin'
if epoch % 100 == 0:
print(f"Epoch: {epoch} | Loss: {loss:.4f}, Acc: {acc:.2f}% | Test Loss: {test_loss:.4f}, Test Acc: {test_acc:.2f}%")
Beta Was this translation helpful? Give feedback.
All reactions