Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

How Neural Networks Learn: Weighted Inputs to Python Loop

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks through how a neural network learns by adjusting weighted inputs, then shows you how to implement a complete training loop in Python. You'll go from the core math of forward propagation and backpropagation to a working gradient descent loop that updates weights and biases. By the end, you'll have a reusable training script that can learn from any small dataset.

What You'll Need

  • Python 3.7 or newer installed on your machine.
  • NumPy library (install with pip install numpy if not present).
  • A text editor or IDE (VS Code, PyCharm, or even Notepad++).
  • Basic familiarity with Python syntax and functions.
  • No prior machine learning experience required—this guide explains every step.

Step-by-Step

  1. Understand the learning goal. A neural network learns by adjusting its weights and biases to minimize the difference between its predictions and the true outputs. This difference is measured by a loss function (e.g., mean squared error). The training loop repeatedly feeds data, computes loss, and updates weights to reduce that loss.
  2. Set up your data. Create a small dataset with input features (X) and target outputs (y). For example, a simple linear relationship: y = 2*x1 + 3*x2 + 1. Use NumPy arrays with shape (number_of_samples, features).
  3. Initialize weights and biases. Start with random small numbers. For a single layer network with 2 inputs and 1 output, create weights = np.random.randn(2, 1) * 0.1 and bias = np.zeros((1, 1)). Random initialization breaks symmetry and helps the network learn.
  4. Define the forward pass. Compute the predicted output: z = np.dot(X, weights) + bias. For a linear regression style network, the output is y_pred = z. For classification, you'd apply an activation like sigmoid, but for this example keep it linear.
  5. Compute the loss. Use mean squared error: loss = np.mean((y_pred - y) ** 2). This gives a single number representing how wrong the predictions are.
  6. Calculate gradients. The gradient tells you how much each weight and bias contributes to the loss. For linear regression, the gradient of loss with respect to weights is dw = (1/N) * np.dot(X.T, (y_pred - y)), and for bias db = (1/N) * np.sum(y_pred - y). These come from the chain rule of calculus.
  7. Update weights and biases. Move the parameters in the opposite direction of the gradient to reduce loss: weights -= learning_rate * dw and bias -= learning_rate * db. The learning rate controls step size; typical values are 0.01 to 0.1.
  8. Loop over epochs. Repeat steps 4–7 for a set number of epochs (e.g., 1000). Each epoch processes the entire dataset once. Track the loss each epoch to see it decrease.
  9. Add mini-batch training (optional). Instead of using all data at once, split into small batches. This makes training faster and more stable. For each batch, compute gradients and update weights.
  10. Write the full training loop. Combine everything into a function that takes X, y, learning_rate, and epochs, and returns the trained weights and loss history. Here's a minimal working example:
import numpy as np

def train_linear(X, y, lr=0.01, epochs=1000):
    N, D = X.shape
    w = np.random.randn(D, 1) * 0.1
    b = np.zeros((1, 1))
    losses = []
    for epoch in range(epochs):
        y_pred = np.dot(X, w) + b
        loss = np.mean((y_pred - y) ** 2)
        dw = (1/N) * np.dot(X.T, (y_pred - y))
        db = (1/N) * np.sum(y_pred - y)
        w -= lr * dw
        b -= lr * db
        losses.append(loss)
        if epoch % 100 == 0:
            print(f"Epoch {epoch}, Loss: {loss:.4f}")
    return w, b, losses

Common Mistakes

  • Forgetting to normalize inputs. If features have very different scales (e.g., age 0-100 and income 0-100000), gradients can become unstable. Standardize features to mean 0 and variance 1.
  • Using too high a learning rate. This causes the loss to oscillate or diverge. Start with 0.01 and decrease if needed.
  • Not reshaping data correctly. Ensure X is 2D (samples, features) and y is 2D (samples, 1). A common error is using a 1D array for y, which breaks matrix multiplication.
  • Forgetting to include bias. Without bias, the model can only fit lines through the origin, which limits learning.
  • Using the entire dataset for every epoch without shuffling. For mini-batch training, shuffle data each epoch to avoid order bias.

Tips

  • Plot the loss over epochs to see if it's decreasing smoothly. If it plateaus too early, reduce learning rate or increase epochs.
  • Use a validation split (e.g., 80% train, 20% test) to check if the model generalizes, not just memorizes.
  • Start with a tiny dataset (like 10 samples) to debug your code before scaling up.
  • For classification problems, replace linear output with a sigmoid activation and use binary cross-entropy loss.
  • Add a small amount of L2 regularization to prevent overfitting if you have many features.
  • Use NumPy's np.random.seed(42) for reproducible results.

Troubleshooting

  • Loss is NaN or infinity. This usually means the learning rate is too high. Reduce it drastically (e.g., 0.0001) and check for any division by zero in your loss.
  • Loss doesn't decrease. Check if your gradients are computed correctly. Try a simple linear dataset and manually verify the first update step. Also ensure your data is not all zeros.
  • Matrix dimension errors. Print the shapes of X, y, and weights. Common fix: use X.shape[1] for input dimension, and reshape y to (-1, 1).
  • Training is too slow. Use vectorized operations (dot products) instead of loops. If you have many features, consider using mini-batches.
  • Model predicts constant value. This happens if the network is too simple or learning rate is too low. Add more layers or increase learning rate slightly.

Frequently Asked Questions

What is backpropagation in simple terms?

Backpropagation is the algorithm that computes how much each weight and bias contributed to the loss. It works backward from the output to the input, applying the chain rule to calculate gradients. Those gradients then guide the weight updates.

Why do we need activation functions?

Activation functions introduce non-linearity, allowing the network to learn complex patterns. Without them, multiple layers would collapse into a single linear transformation, limiting the model's capacity.

How do I choose the number of epochs?

There's no fixed rule. Watch the loss curve: when it stops decreasing significantly, stop training. Too many epochs can cause overfitting on training data.

What is the difference between a weight and a bias?

A weight determines the strength of influence of an input feature on the output. A bias is an offset that allows the activation to shift, giving the model more flexibility to fit the data.

Can I use this code for image classification?

Not directly. Images require convolutional layers and more complex architectures. However, the core training loop—forward pass, loss, backprop, update—remains the same; you'd just replace the network structure.

How do I know if my model is learning correctly?

Monitor the loss on both training and validation sets. If training loss decreases but validation loss increases, you're overfitting. If both decrease slowly, learning is working.