Skip to main content

7. Neural Network Ex.1 Binary Classification

Binary classification using neural network is essentially same as a logistic Regression in Machine Learning, That is we will be somehow able to teach our computer to choose between 2 choices. However there is one improvement, Logistic Regression is Made only for Binary Classification, But Neural Network can be made to choose between 3,4 and even more choices (In next chapter - Multi Class Classification)

The Project Structure :​

The Sigmoid Function​

To convert the raw logit zz into a probability (a number between 0 and 1), we pass it through the Sigmoid activation function:

σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}

A common decision rule to translate this probability into a final class is:

probability >= 0.5 → Class 1
probability < 0.5 → Class 0

Binary Cross-Entropy (BCE) Loss​

To train our model, we need to penalize it when its predicted probability diverges from the true label. Binary Cross-Entropy (BCE) loss does exactly this. It heavily penalizes the model if it is confidently wrong (e.g., predicting 0.99 for a class that is actually 0).

In PyTorch, you could technically apply nn.Sigmoid() and then nn.BCELoss(). However, for numerical stability, it is standard practice to combine them into a single step:

loss_function = torch.nn.BCEWithLogitsLoss()

This function takes the raw logits (zz) and the target labels directly, applying the sigmoid mathematically under the hood in a way that avoids floating-point precision issues.

Complete Runnable Example​

Let's build a simple PyTorch binary classifier. We'll train a small network to classify some dummy 2D data points.

Code Block