This lab builds simple linear regression (y = Wx + b) from scratch in TensorFlow 2. It creates the weight and bias with tf.Variable, computes gradients of the mean squared error with tf.GradientTape and updates the parameters with plain gradient descent. Below the notebook you will find what each cell does, a corrected runnable script that trains for 10, 50 and 100 epochs as the lab note asks, a way to check the result and fixes for common errors.
What the notebook does
The notebook above creates 130 synthetic points on the line y = 2x + 0.5 and adds Gaussian noise with a standard deviation of 0.5. It then learns W and b back from the data. A Keras Dense layer could do the same job, but writing the loop by hand shows what Keras does inside fit(): run the forward pass, compute the loss, compute the gradients and update the parameters.
| Piece | Role |
|---|---|
LinearModel | Holds two trainable scalars, weight and bias, and returns weight * x + bias when called |
loss() | Mean squared error: tf.reduce_mean(tf.square(y - y_pred)) |
tf.GradientTape | Records the operations inside the with block so that tape.gradient() can compute dLoss/dW and dLoss/db |
assign_sub(lr * grad) | Gradient descent step that updates the variable in place: param = param – lr * grad |
weights, biases lists | Store the parameter values at each epoch so you can plot how training converges |
Note: The loss in the example output levels off at about 0.263 and does not reach zero. That is expected. The noise has a standard deviation of 0.5, so its variance is 0.25, and no straight line can get the mean squared error much below that value.
Prerequisites
- A Python version that your TensorFlow release supports (check the TensorFlow install page for the current range)
- A virtual environment, so that the Jupyter kernel and
pipuse the same interpreter - Basic NumPy and an idea of what a derivative is
python3 -m venv tf-lab
source tf-lab/bin/activate
pip install --upgrade pip
pip install tensorflow numpy matplotlib jupyter
python -c "import tensorflow as tf; print(tf.__version__)"
jupyter notebookCode language: JavaScript (javascript)
Corrected and complete script
This version fixes the inconsistencies in the notebook. It uses one learning rate throughout, sets seeds so results are reproducible, uses explicit float32 dtypes and runs the 10, 50 and 100 epoch comparison described in the lab note. It runs as a single notebook cell or as a .py file.
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
# Reproducibility
np.random.seed(42)
tf.random.set_seed(42)
# Synthetic data: y = 2x + 0.5 + noise
W_true, b_true = 2.0, 0.5
x = np.linspace(0, 3, 130).astype(np.float32)
y = (W_true * x + b_true + np.random.randn(*x.shape) * 0.5).astype(np.float32)
class LinearModel(tf.Module):
def __init__(self):
super().__init__()
self.weight = tf.Variable(tf.random.normal([]), name="W")
self.bias = tf.Variable(tf.random.normal([]), name="b")
def __call__(self, x):
return self.weight * x + self.bias
def loss(y, y_pred):
return tf.reduce_mean(tf.square(y - y_pred))
def train_step(model, x, y, lr):
with tf.GradientTape() as tape:
current_loss = loss(y, model(x))
d_w, d_b = tape.gradient(current_loss, [model.weight, model.bias])
model.weight.assign_sub(lr * d_w)
model.bias.assign_sub(lr * d_b)
return current_loss # loss measured before this update
def fit(epochs, lr=0.12):
model = LinearModel()
weights, biases, losses = [], [], []
for _ in range(epochs):
weights.append(model.weight.numpy())
biases.append(model.bias.numpy())
losses.append(train_step(model, x, y, lr).numpy())
return model, weights, biases, losses
for epochs in (10, 50, 100):
model, weights, biases, losses = fit(epochs, lr=0.12)
print(f"epochs={epochs:3d} W={model.weight.numpy():.3f} "
f"b={model.bias.numpy():.3f} last loss={losses[-1]:.4f}")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
ax1.scatter(x, y, s=12, label="data")
ax1.plot(x, model(x).numpy(), "r", label="fitted line")
ax1.plot(x, W_true * x + b_true, "g--", label="true line")
ax1.set_title(f"Fit after {epochs} epochs")
ax1.legend()
ax2.plot(weights, label="W")
ax2.plot(biases, label="b")
ax2.axhline(W_true, color="C0", ls=":")
ax2.axhline(b_true, color="C1", ls=":")
ax2.set_xlabel("epoch")
ax2.set_title("Parameter values per epoch")
ax2.legend()
plt.show()
Expected result: the printed W approaches 2 and b approaches 0.5 as the number of epochs grows, and the loss settles a little above 0.25. In the plots, the weight converges quickly. The bias takes longer, because with all x values positive the two parameters are correlated and gradient descent moves slowly along that direction. That slow bias is why 10 epochs leaves a visible gap between the fitted line and the true line, while 100 epochs nearly closes it.
Choosing the learning rate
The learning rate matters more than any other setting in this lab. The default lr = 0.01 in the original train() function is safe, but on this data it is too small to converge in 100 epochs. The bias is still far from 0.5 at the end. The notebook's loop overrides it with 0.12, which converges well.
| Learning rate | Behaviour on this data (x in 0 to 3) |
|---|---|
| 0.01 | Loss falls steadily but slowly; parameters are not converged after 100 epochs |
| 0.05 to 0.15 | Fast, stable convergence; a good range for the lab |
| Above roughly 0.25 | Updates overshoot, the loss grows every epoch and soon becomes inf or nan |
Note: The stable range depends on the scale of x. If you change np.linspace(0, 3, 130) to something like np.linspace(0, 100, 130), a learning rate of 0.12 will diverge. Standardise the inputs, or lower the learning rate, whenever you change the data.
Verify the result
Simple linear regression has an exact least-squares solution, so you can check the trained parameters against it. After enough epochs, gradient descent should match np.polyfit to about two or three decimal places.
slope, intercept = np.polyfit(x, y, 1)
print(f"closed form: W={slope:.3f}, b={intercept:.3f}")
print(f"gradient descent: W={model.weight.numpy():.3f}, b={model.bias.numpy():.3f}")Code language: PHP (php)
The same model in Keras takes a few lines. It is useful for comparison once you understand the manual loop:
keras_model = tf.keras.Sequential([
tf.keras.Input(shape=(1,)),
tf.keras.layers.Dense(1),
])
keras_model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.12), loss="mse")
keras_model.fit(x.reshape(-1, 1), y, epochs=100, batch_size=len(x), verbose=0)
kernel, bias = keras_model.layers[0].get_weights()
print(kernel.ravel(), bias)Code language: PHP (php)
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
InvalidArgumentError saying an input was expected to be a float tensor but is a double tensor | A float32 variable is mixed with a float64 tensor, for example tf.constant(x) built from a NumPy float64 array | Cast the data with .astype(np.float32) or tf.cast(..., tf.float32) |
Loss becomes inf or nan after a few epochs | Learning rate too high for the input scale | Lower lr or standardise x |
| Loss barely moves | Learning rate too low or too few epochs | Increase lr (for example to 0.1) or the number of epochs |
tape.gradient returns None | The forward pass ran outside the with tf.GradientTape() block, or a value was turned into NumPy with .numpy() inside it | Keep every operation from the variables to the loss inside the tape as TensorFlow ops |
ModuleNotFoundError: No module named 'tensorflow' in Jupyter | The notebook kernel uses a different Python than the one pip installed into | Install from the notebook with %pip install tensorflow, or register the venv as a kernel |
Frequently asked questions
What does tf.GradientTape do in linear regression?
It records the operations that use trainable variables inside its context. tape.gradient(loss, [W, b]) then returns the derivative of the loss with respect to each variable, which the update step uses.
Why does the loss not go to zero?
The data has random noise with a standard deviation of 0.5. A straight line cannot fit the noise, so the mean squared error levels off near the noise variance of 0.25.
Why use assign_sub instead of W = W – lr * grad?
assign_sub updates the existing tf.Variable in place, so the model keeps tracking the same trainable object. Plain reassignment replaces the variable with a regular tensor, and later gradient calls then return None for it.
Should I use Keras instead of a manual training loop?
For real projects, Keras Dense layers with model.fit() or a built-in optimizer such as tf.keras.optimizers.SGD take less code and are less error-prone. The manual loop is for learning how gradients and updates work, and for custom training logic that fit() does not support.
How do I make the results reproducible?
Call np.random.seed() and tf.random.set_seed() before you generate data or create variables. The original notebook sets no seed, so every run gives different data and starting values.
Related tutorials
- More Machine Learning tutorials
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals