{"id":47531,"date":"2026-11-24T22:04:55","date_gmt":"2026-11-24T22:04:55","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=47531"},"modified":"2026-11-24T22:04:55","modified_gmt":"2026-11-24T22:04:55","slug":"tensorsflow-lab6-tensorsflow-simplelinearregression","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/tensorsflow-lab6-tensorsflow-simplelinearregression\/","title":{"rendered":"Tensorsflow Lab6 &#8211; Tensorsflow SimpleLinearRegression"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">This lab builds simple linear regression (y = Wx + b) from scratch in TensorFlow 2. It creates the weight and bias with <code>tf.Variable<\/code>, computes gradients of the mean squared error with <code>tf.GradientTape<\/code> 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.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/4137fc81af30bcafa0dccf4b211304d9.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What the notebook does<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>W<\/code> and <code>b<\/code> back from the data. A Keras <code>Dense<\/code> layer could do the same job, but writing the loop by hand shows what Keras does inside <code>fit()<\/code>: run the forward pass, compute the loss, compute the gradients and update the parameters.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Piece<\/th><th>Role<\/th><\/tr><\/thead><tbody><tr><td><code>LinearModel<\/code><\/td><td>Holds two trainable scalars, <code>weight<\/code> and <code>bias<\/code>, and returns <code>weight * x + bias<\/code> when called<\/td><\/tr><tr><td><code>loss()<\/code><\/td><td>Mean squared error: <code>tf.reduce_mean(tf.square(y - y_pred))<\/code><\/td><\/tr><tr><td><code>tf.GradientTape<\/code><\/td><td>Records the operations inside the <code>with<\/code> block so that <code>tape.gradient()<\/code> can compute dLoss\/dW and dLoss\/db<\/td><\/tr><tr><td><code>assign_sub(lr * grad)<\/code><\/td><td>Gradient descent step that updates the variable in place: param = param &#8211; lr * grad<\/td><\/tr><tr><td><code>weights<\/code>, <code>biases<\/code> lists<\/td><td>Store the parameter values at each epoch so you can plot how training converges<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A Python version that your TensorFlow release supports (check the TensorFlow install page for the current range)<\/li>\n\n\n<li>A virtual environment, so that the Jupyter kernel and <code>pip<\/code> use the same interpreter<\/li>\n\n\n<li>Basic NumPy and an idea of what a derivative is<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">python3 -m venv tf-lab\nsource tf-lab\/bin\/activate\npip install --upgrade pip\npip install tensorflow numpy matplotlib jupyter\npython -c <span class=\"hljs-string\">\"import tensorflow as tf; print(tf.__version__)\"<\/span>\njupyter notebook<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Corrected and complete script<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This version fixes the inconsistencies in the notebook. It uses one learning rate throughout, sets seeds so results are reproducible, uses explicit <code>float32<\/code> 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 <code>.py<\/code> file.<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\n# Reproducibility\nnp.random.seed(42)\ntf.random.set_seed(42)\n\n# Synthetic data: y = 2x + 0.5 + noise\nW_true, b_true = 2.0, 0.5\nx = np.linspace(0, 3, 130).astype(np.float32)\ny = (W_true * x + b_true + np.random.randn(*x.shape) * 0.5).astype(np.float32)\n\nclass LinearModel(tf.Module):\n    def __init__(self):\n        super().__init__()\n        self.weight = tf.Variable(tf.random.normal(&#91;]), name=\"W\")\n        self.bias = tf.Variable(tf.random.normal(&#91;]), name=\"b\")\n\n    def __call__(self, x):\n        return self.weight * x + self.bias\n\ndef loss(y, y_pred):\n    return tf.reduce_mean(tf.square(y - y_pred))\n\ndef train_step(model, x, y, lr):\n    with tf.GradientTape() as tape:\n        current_loss = loss(y, model(x))\n    d_w, d_b = tape.gradient(current_loss, &#91;model.weight, model.bias])\n    model.weight.assign_sub(lr * d_w)\n    model.bias.assign_sub(lr * d_b)\n    return current_loss  # loss measured before this update\n\ndef fit(epochs, lr=0.12):\n    model = LinearModel()\n    weights, biases, losses = &#91;], &#91;], &#91;]\n    for _ in range(epochs):\n        weights.append(model.weight.numpy())\n        biases.append(model.bias.numpy())\n        losses.append(train_step(model, x, y, lr).numpy())\n    return model, weights, biases, losses\n\nfor epochs in (10, 50, 100):\n    model, weights, biases, losses = fit(epochs, lr=0.12)\n    print(f\"epochs={epochs:3d}  W={model.weight.numpy():.3f}  \"\n          f\"b={model.bias.numpy():.3f}  last loss={losses&#91;-1]:.4f}\")\n\n    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))\n    ax1.scatter(x, y, s=12, label=\"data\")\n    ax1.plot(x, model(x).numpy(), \"r\", label=\"fitted line\")\n    ax1.plot(x, W_true * x + b_true, \"g--\", label=\"true line\")\n    ax1.set_title(f\"Fit after {epochs} epochs\")\n    ax1.legend()\n\n    ax2.plot(weights, label=\"W\")\n    ax2.plot(biases, label=\"b\")\n    ax2.axhline(W_true, color=\"C0\", ls=\":\")\n    ax2.axhline(b_true, color=\"C1\", ls=\":\")\n    ax2.set_xlabel(\"epoch\")\n    ax2.set_title(\"Parameter values per epoch\")\n    ax2.legend()\n    plt.show()<\/code><\/span><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Expected result:<\/strong> the printed <code>W<\/code> approaches 2 and <code>b<\/code> 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 <code>x<\/code> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Choosing the learning rate<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The learning rate matters more than any other setting in this lab. The default <code>lr = 0.01<\/code> in the original <code>train()<\/code> 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&#039;s loop overrides it with 0.12, which converges well.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Learning rate<\/th><th>Behaviour on this data (x in 0 to 3)<\/th><\/tr><\/thead><tbody><tr><td>0.01<\/td><td>Loss falls steadily but slowly; parameters are not converged after 100 epochs<\/td><\/tr><tr><td>0.05 to 0.15<\/td><td>Fast, stable convergence; a good range for the lab<\/td><\/tr><tr><td>Above roughly 0.25<\/td><td>Updates overshoot, the loss grows every epoch and soon becomes <code>inf<\/code> or <code>nan<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> The stable range depends on the scale of <code>x<\/code>. If you change <code>np.linspace(0, 3, 130)<\/code> to something like <code>np.linspace(0, 100, 130)<\/code>, a learning rate of 0.12 will diverge. Standardise the inputs, or lower the learning rate, whenever you change the data.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Verify the result<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>np.polyfit<\/code> to about two or three decimal places.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">slope, intercept = np.polyfit(x, y, <span class=\"hljs-number\">1<\/span>)\n<span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">\"closed form: W={slope:.3f}, b={intercept:.3f}\"<\/span>)\n<span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">\"gradient descent: W={model.weight.numpy():.3f}, b={model.bias.numpy():.3f}\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The same model in Keras takes a few lines. It is useful for comparison once you understand the manual loop:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">keras_model = tf.keras.Sequential(&#91;\n    tf.keras.Input(shape=(<span class=\"hljs-number\">1<\/span>,)),\n    tf.keras.layers.Dense(<span class=\"hljs-number\">1<\/span>),\n])\nkeras_model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=<span class=\"hljs-number\">0.12<\/span>), loss=<span class=\"hljs-string\">\"mse\"<\/span>)\nkeras_model.fit(x.reshape(<span class=\"hljs-number\">-1<\/span>, <span class=\"hljs-number\">1<\/span>), y, epochs=<span class=\"hljs-number\">100<\/span>, batch_size=len(x), verbose=<span class=\"hljs-number\">0<\/span>)\nkernel, bias = keras_model.layers&#91;<span class=\"hljs-number\">0<\/span>].get_weights()\n<span class=\"hljs-keyword\">print<\/span>(kernel.ravel(), bias)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>InvalidArgumentError<\/code> saying an input was expected to be a float tensor but is a double tensor<\/td><td>A <code>float32<\/code> variable is mixed with a <code>float64<\/code> tensor, for example <code>tf.constant(x)<\/code> built from a NumPy float64 array<\/td><td>Cast the data with <code>.astype(np.float32)<\/code> or <code>tf.cast(..., tf.float32)<\/code><\/td><\/tr><tr><td>Loss becomes <code>inf<\/code> or <code>nan<\/code> after a few epochs<\/td><td>Learning rate too high for the input scale<\/td><td>Lower <code>lr<\/code> or standardise <code>x<\/code><\/td><\/tr><tr><td>Loss barely moves<\/td><td>Learning rate too low or too few epochs<\/td><td>Increase <code>lr<\/code> (for example to 0.1) or the number of epochs<\/td><\/tr><tr><td><code>tape.gradient<\/code> returns <code>None<\/code><\/td><td>The forward pass ran outside the <code>with tf.GradientTape()<\/code> block, or a value was turned into NumPy with <code>.numpy()<\/code> inside it<\/td><td>Keep every operation from the variables to the loss inside the tape as TensorFlow ops<\/td><\/tr><tr><td><code>ModuleNotFoundError: No module named &#039;tensorflow&#039;<\/code> in Jupyter<\/td><td>The notebook kernel uses a different Python than the one <code>pip<\/code> installed into<\/td><td>Install from the notebook with <code>%pip install tensorflow<\/code>, or register the venv as a kernel<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What does tf.GradientTape do in linear regression?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It records the operations that use trainable variables inside its context. <code>tape.gradient(loss, [W, b])<\/code> then returns the derivative of the loss with respect to each variable, which the update step uses.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why does the loss not go to zero?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why use assign_sub instead of W = W &#8211; lr * grad?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>assign_sub<\/code> updates the existing <code>tf.Variable<\/code> 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 <code>None<\/code> for it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I use Keras instead of a manual training loop?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For real projects, Keras <code>Dense<\/code> layers with <code>model.fit()<\/code> or a built-in optimizer such as <code>tf.keras.optimizers.SGD<\/code> 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 <code>fit()<\/code> does not support.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I make the results reproducible?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Call <code>np.random.seed()<\/code> and <code>tf.random.set_seed()<\/code> before you generate data or create variables. The original notebook sets no seed, so every run gives different data and starting values.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/artificial-intelligence\/machine-learning\/\">More Machine Learning tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/lead-machine-learning-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/staff-mlops-engineer-role-blueprint-responsibilities-skills-kpis-and-career-path\/\">Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[6512],"tags":[7380],"class_list":["post-47531","post","type-post","status-publish","format-standard","hentry","category-machine-learning","tag-tensorflow"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47531","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=47531"}],"version-history":[{"count":2,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47531\/revisions"}],"predecessor-version":[{"id":80204,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/47531\/revisions\/80204"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=47531"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=47531"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=47531"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}