<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Lochan Jangid</title>
    <description>The latest articles on DEV Community by Lochan Jangid (@lochanjangid).</description>
    <link>https://dev.to/lochanjangid</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4231057%2Fb68986a4-b892-4a92-b2ed-f58688b5ec55.jpg</url>
      <title>DEV Community: Lochan Jangid</title>
      <link>https://dev.to/lochanjangid</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/lochanjangid"/>
    <language>en</language>
    <item>
      <title>Lecture on Linear Regression &amp; Gradient Descent From Scratch | by Lochan Jangid</title>
      <dc:creator>Lochan Jangid</dc:creator>
      <pubDate>Wed, 02 Dec 2026 03:01:19 +0000</pubDate>
      <link>https://dev.to/lochanjangid/lecture-on-linear-regression-gradient-descent-from-scratch-by-lochan-jangid-fb5</link>
      <guid>https://dev.to/lochanjangid/lecture-on-linear-regression-gradient-descent-from-scratch-by-lochan-jangid-fb5</guid>
      <description>&lt;p&gt;  &lt;iframe src="https://www.youtube.com/embed/D8Exwj1_yEQ" width="710" height="399"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This post follows my lecture above, from the core idea of gradient descent to a linear regression model in PyTorch. &lt;br&gt;
Full notebook: &lt;a href="https://colab.research.google.com/drive/1vn_ZsqwSp16cI8O7gVltU5sJNSJrXNRW" rel="noopener noreferrer"&gt;https://colab.research.google.com/drive/1vn_ZsqwSp16cI8O7gVltU5sJNSJrXNRW&lt;/a&gt;. &lt;br&gt;
A shorter, code-free explanation is on Medium: &lt;a href="https://medium.com/@lochanjangidcoder/lecture-on-linear-regression-gradient-descent-from-scratch-by-lochan-jangid-f0d5ba9115f8?sharedUserId=lochanjangidcoder" rel="noopener noreferrer"&gt;https://medium.com/@lochanjangidcoder/lecture-on-linear-regression-gradient-descent-from-scratch-by-lochan-jangid-f0d5ba9115f8?sharedUserId=lochanjangidcoder&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;



&lt;p&gt;Linear regression and gradient descent are two of the core ideas of machine learning. We will build the math first, then the model, using code from my lecture notebook.&lt;/p&gt;
&lt;h2&gt;
  
  
  Part 1: The core idea of gradient descent
&lt;/h2&gt;

&lt;p&gt;Take a simple equation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x * 4 = 12
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We know x is 3. Let’s pretend we don’t, and build a system that finds x by itself.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Start with a guess.&lt;/strong&gt; Say x = 0. The output is 4 * 0 = 0, but the target is 12. The distance between the output and the target is the &lt;strong&gt;error&lt;/strong&gt;, here 12. The target is constant, so the only thing we can change is x. If we make the error smaller, the output comes closer to the target, and the smallest possible error is zero.&lt;/p&gt;

&lt;p&gt;That leaves one question: how does the system decide &lt;strong&gt;which direction to move x, and by how much&lt;/strong&gt;? The answer is the derivative.&lt;/p&gt;

&lt;h3&gt;
  
  
  The derivative
&lt;/h3&gt;

&lt;p&gt;A derivative tells us how sensitive a function’s output is to a small change in its input. It measures the slope. For our problem, it tells us whether the error goes up or down if we nudge x in the positive or negative direction.&lt;/p&gt;

&lt;p&gt;Here is the derivative of &lt;code&gt;x**2&lt;/code&gt;, derived by hand from the definition:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# derive the derivative of x**2 by hand&lt;/span&gt;
&lt;span class="c1"&gt;# y = x**2 = f(x)&lt;/span&gt;
&lt;span class="c1"&gt;# L = (f(x+h) - f(x)) / h&lt;/span&gt;
&lt;span class="c1"&gt;# L = ((x+h)**2 - x**2) / h&lt;/span&gt;
&lt;span class="c1"&gt;# L = (x**2 + 2*x*h + h**2 - x**2) / h&lt;/span&gt;
&lt;span class="c1"&gt;# L = (2*x*h + h*h) / h&lt;/span&gt;
&lt;span class="c1"&gt;# L = 2*x + h&lt;/span&gt;
&lt;span class="c1"&gt;# put h = 0&lt;/span&gt;
&lt;span class="c1"&gt;# L = 2*x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We set &lt;code&gt;h = 0&lt;/code&gt; because we want the rate of change at a single point. You don’t have to derive this every time. There are rules, like the derivative of &lt;code&gt;x**n&lt;/code&gt; being &lt;code&gt;n * x**(n-1)&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why we square the error
&lt;/h3&gt;

&lt;p&gt;If we use &lt;code&gt;12 - 4x&lt;/code&gt; as the error, its minimum is negative infinity, which is useless. We need a floor at zero, so we square it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error = (target - 4x)**2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the minimum is zero, and zero means the output equals the target. (You could ask why we square instead of taking the absolute value. That is a separate topic.)&lt;/p&gt;

&lt;h3&gt;
  
  
  The chain rule
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;(target - 4x)**2&lt;/code&gt; is a function inside a function. The chain rule says: take the derivative of the outside first, then multiply it by the derivative of the inside.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Outside: the derivative of &lt;code&gt;t**2&lt;/code&gt; is &lt;code&gt;2 * t&lt;/code&gt;, which gives &lt;code&gt;2 * (target - 4x)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Inside: the derivative of &lt;code&gt;target - 4x&lt;/code&gt; is &lt;code&gt;0 - 4&lt;/code&gt;, because the derivative of a constant is zero.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So the derivative of the error is &lt;code&gt;2 * (target - 4x) * (0 - 4)&lt;/code&gt;. At &lt;code&gt;x = 0&lt;/code&gt; with a target of 12, that is -96. The slope is negative, so the error goes down when x goes up.&lt;/p&gt;

&lt;h3&gt;
  
  
  The update, and the learning rate
&lt;/h3&gt;

&lt;p&gt;We subtract the slope from x. But subtracting -96 directly would send x to 96, far past the answer. So we take small steps by multiplying the slope with a &lt;strong&gt;learning rate&lt;/strong&gt;, here 0.01. The first step moves x from 0 to 0.96, and the next steps are smaller.&lt;/p&gt;

&lt;p&gt;Here is the whole thing in a loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;target&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;12.55&lt;/span&gt;
&lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.01&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="n"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;target&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;
  &lt;span class="n"&gt;derror&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;target&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;derror&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# 3.1374999999999997&lt;/span&gt;
&lt;span class="c1"&gt;# 3.1375&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With &lt;code&gt;target = 12&lt;/code&gt;, x comes out as 2.9999999999999996, which rounds to 3. I changed the target to 12.55 to show that nothing is hard-coded: the system finds x = 3.1375, which is 12.55 / 4. The tiny difference from the exact value is floating-point precision.&lt;/p&gt;

&lt;p&gt;The learning rate matters:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Too big&lt;/strong&gt; (try 0.1): x takes a huge jump, overshoots the answer, and lands even farther away.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Too small&lt;/strong&gt; (try 0.001): x moves so slowly that after 100 steps it is only about 2.88.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We never told the system the answer. It found x by repeating one loop: measure the error, find the slope, take a small step. That is gradient descent, and large models do the same loop with billions of numbers instead of one.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part 2: Linear regression
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Why PyTorch, and why tensors
&lt;/h3&gt;

&lt;p&gt;Now we have 30 houses, each with a living area and a price. We want a model that predicts the price from the living area.&lt;/p&gt;

&lt;p&gt;I use PyTorch here. A Python list is a list of pointers, so its numbers live in different places in memory, and reading them is slow. Gradient descent and linear regression are mostly calculations, so we want fast ones. Pure Python would also need loops inside loops, which would hide the linear regression we’re trying to learn. A &lt;strong&gt;tensor&lt;/strong&gt; stores its numbers in one continuous block of memory, so it is fast to read and fast to compute on. Compared with NumPy, PyTorch can also run on a GPU. And its syntax looks like normal Python, which makes it easy to read.&lt;/p&gt;

&lt;h3&gt;
  
  
  The data
&lt;/h3&gt;

&lt;p&gt;I made up the data, so everything is fake. Price is in the dataset’s own units.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;

&lt;span class="n"&gt;living_area&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt; &lt;span class="mi"&gt;2104&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1600&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1416&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1985&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1534&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1427&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1380&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1494&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1940&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1890&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4478&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1268&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2300&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1320&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1236&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                            &lt;span class="mi"&gt;2609&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3031&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1767&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1888&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1604&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1962&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3890&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1100&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1458&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2526&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2200&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2637&lt;/span&gt; &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;330&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;369&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;232&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;540&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;315&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;285&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;250&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;245&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;259&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;302&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;320&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;295&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;715&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;210&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;355&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;223&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;199&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;499&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;599&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;252&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;290&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;262&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                      &lt;span class="mi"&gt;320&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;765&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;170&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;240&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;490&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;345&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;500&lt;/span&gt; &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="no"&gt;X&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;living_area&lt;/span&gt;
&lt;span class="n"&gt;y&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I use &lt;code&gt;torch.Tensor&lt;/code&gt; with a capital T on purpose: it always creates float32 numbers. With a small &lt;code&gt;torch.tensor&lt;/code&gt; and whole-number input, you get an integer tensor, and weights need to be floats.&lt;/p&gt;

&lt;p&gt;We can’t see a pattern in raw numbers, so we plot them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;matplotlib&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pyplot&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;plt&lt;/span&gt;

&lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;scatter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;living_area&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;price&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As living area grows, price grows too. The pattern is linear, so we can describe it with a line. For a house of 4,000 sq ft, the price would be around 700.&lt;/p&gt;

&lt;h3&gt;
  
  
  The hypothesis function
&lt;/h3&gt;

&lt;p&gt;A line is &lt;code&gt;y = mx + c&lt;/code&gt;. In machine learning we rename the parts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# y = mx + y0 # - hypothesis function&lt;/span&gt;
&lt;span class="c1"&gt;# m = slope = w = weights&lt;/span&gt;
&lt;span class="c1"&gt;# y0 = y-intercept = b = bias&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So the hypothesis is &lt;code&gt;hx = w * X + b&lt;/code&gt;. As in Part 1, we start with a random guess for the parameters, and then improve them.&lt;/p&gt;

&lt;h3&gt;
  
  
  The loss, and two derivatives
&lt;/h3&gt;

&lt;p&gt;The loss is the average of the squared errors over all 30 houses:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;loss&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before we had one parameter, x, so we needed one derivative. Now we have two, &lt;code&gt;w&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt;, so we need two: the derivative of the loss with respect to &lt;code&gt;w&lt;/code&gt;, and with respect to &lt;code&gt;b&lt;/code&gt;. With the chain rule, they are:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;dloss&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;dw&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="no"&gt;X&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;dloss&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(When you differentiate with respect to &lt;code&gt;w&lt;/code&gt;, &lt;code&gt;b&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; are treated as constants.) Each gradient is the error times its input, averaged. The &lt;code&gt;.mean()&lt;/code&gt; is the sum divided by the number of examples.&lt;/p&gt;

&lt;h3&gt;
  
  
  Train it
&lt;/h3&gt;

&lt;p&gt;We update both parameters with the same rule as before. The learning rate is very small, because the living area values are large and the parameters would otherwise explode:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;1e-8&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="n"&gt;hx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="no"&gt;X&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
  &lt;span class="n"&gt;loss&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;dlossdw&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="no"&gt;X&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;dlossdb&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;dlossdw&lt;/span&gt;
  &lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;dlossdb&lt;/span&gt;

&lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;scatter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;X&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;plot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;X&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="no"&gt;X&lt;/span&gt;&lt;span class="o"&gt;+&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;show&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The line now fits the data. The parameters are:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
&lt;span class="c1"&gt;# (tensor(0.1734), tensor(1.0001))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And a new house of 4,000 sq ft gets:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="mi"&gt;4000&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mf"&gt;0.1734&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mf"&gt;1.0001&lt;/span&gt;
&lt;span class="c1"&gt;# 694.6001&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is around 700, as we expected from the plot.&lt;/p&gt;

&lt;h3&gt;
  
  
  A second feature: bedrooms
&lt;/h3&gt;

&lt;p&gt;Now add the number of bedrooms. With two variables the hypothesis becomes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# y = w1 * living_area + w2 * bedrooms + b&lt;/span&gt;

&lt;span class="n"&gt;bedrooms&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt; &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We now need two weights, and three derivatives:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;w1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="n"&gt;w2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;1e-8&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="n"&gt;hx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;w1&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;living_area&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;w2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;bedrooms&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
  &lt;span class="n"&gt;loss&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;dlossdw1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;living_area&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;dlossdw2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;bedrooms&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;dlossdb&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;w1&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;dlossdw1&lt;/span&gt;
  &lt;span class="n"&gt;w2&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;dlossdw2&lt;/span&gt;
  &lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;dlossdb&lt;/span&gt;

&lt;span class="n"&gt;loss&lt;/span&gt;
&lt;span class="c1"&gt;# tensor(1483.5529)&lt;/span&gt;

&lt;span class="n"&gt;w1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;w2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
&lt;span class="c1"&gt;# (tensor(0.1734), tensor(0.0003), tensor(1.0001))&lt;/span&gt;

&lt;span class="mi"&gt;4000&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;w1&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;w2&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
&lt;span class="c1"&gt;# tensor(694.4289)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Look at &lt;code&gt;w2&lt;/code&gt;: it barely moved. Living area is in the thousands and bedrooms are between 2 and 5, so with a learning rate this tiny, the bedroom weight hardly learns. If we raise the learning rate to 0.01 to speed up, the loss becomes &lt;code&gt;nan&lt;/code&gt;, because the parameters explode. The two features are on very different scales.&lt;/p&gt;

&lt;h3&gt;
  
  
  The fix: scale the features
&lt;/h3&gt;

&lt;p&gt;We use z-score scaling: subtract the mean and divide by the standard deviation. After scaling, each feature has a mean of about 0 and a standard deviation of 1, so most values fall between roughly -3 and 3.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;living_area_scaled&lt;/span&gt;  &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;living_area&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;living_area&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;living_area&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;std&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;bedrooms_scaled&lt;/span&gt;  &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bedrooms&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;bedrooms&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;bedrooms&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;std&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now both features are on the same scale, and we can use &lt;code&gt;learning_rate = 0.01&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;w1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="n"&gt;w2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.01&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="n"&gt;hx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;w1&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;living_area_scaled&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;w2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;bedrooms_scaled&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
  &lt;span class="n"&gt;loss&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;dlossdw1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;living_area_scaled&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;dlossdw2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;bedrooms_scaled&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;dlossdb&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="n"&gt;w1&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;dlossdw1&lt;/span&gt;
  &lt;span class="n"&gt;w2&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;dlossdw2&lt;/span&gt;
  &lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;dlossdb&lt;/span&gt;

&lt;span class="n"&gt;loss&lt;/span&gt;
&lt;span class="c1"&gt;# tensor(4059.7141)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To predict, we must scale the new house with the &lt;strong&gt;training&lt;/strong&gt; mean and std. If you feed in a raw 4,000, you get a nonsense price (that was a mistake I made on camera):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4000&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;living_area&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;living_area&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;std&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# tensor(2.5002)&lt;/span&gt;

&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;bedrooms&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;bedrooms&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;std&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# tensor(2.1985)&lt;/span&gt;

&lt;span class="mf"&gt;2.5002&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;w1&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mf"&gt;2.1985&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;w2&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
&lt;span class="c1"&gt;# tensor(645.5610)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The prediction is 645 for a house with 4,000 sq ft and 5 bedrooms. The loss is still 4,059 because we only ran 100 steps, and the model has not converged yet. We’ll fix that next.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part 3: Use the ability of tensors
&lt;/h2&gt;

&lt;p&gt;We have written one variable for each weight. With 10 or 30 features, that would be tedious and not efficient. Instead, we put all the weights in &lt;strong&gt;one tensor&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;requires_grad&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;requires_grad&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.01&lt;/span&gt;

&lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;
&lt;span class="c1"&gt;# torch.Size([2])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;requires_grad = True&lt;/code&gt; tells PyTorch to track every operation on these tensors, so that it can compute their derivatives for us.&lt;/p&gt;

&lt;p&gt;Next, stack the two scaled features into one tensor:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="no"&gt;X&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;living_area_scaled&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;bedrooms_scaled&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dim&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="no"&gt;X&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;
&lt;span class="c1"&gt;# torch.Size([30, 2])&lt;/span&gt;

&lt;span class="no"&gt;X&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="c1"&gt;# tensor([[ 0.0716, -0.1999],&lt;/span&gt;
&lt;span class="c1"&gt;#         [-0.5740, -0.1999],&lt;/span&gt;
&lt;span class="c1"&gt;#         [ 0.4507, -0.1999],&lt;/span&gt;
&lt;span class="c1"&gt;#         [-0.8097, -1.3990],&lt;/span&gt;
&lt;span class="c1"&gt;#         [ 1.2193,  0.9993]])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each &lt;strong&gt;row&lt;/strong&gt; is one house, and each &lt;strong&gt;column&lt;/strong&gt; is one feature. Now we need to multiply each house’s features with the weights, which is a &lt;strong&gt;matrix multiplication&lt;/strong&gt;. Tensors behave like matrices and support most matrix operations. For a (30, 2) matrix times a (2,) weight vector, the inner sizes match (2 and 2), so we get one result per house:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;X&lt;/span&gt; @ &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;shape&lt;/span&gt;
&lt;span class="c1"&gt;# torch.Size([30])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With 100 features, this line doesn’t change. Only the shape of &lt;code&gt;X&lt;/code&gt; does.&lt;/p&gt;

&lt;h3&gt;
  
  
  Forward pass and backward pass
&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;forward pass&lt;/strong&gt; computes the prediction and the loss. The &lt;strong&gt;backward pass&lt;/strong&gt; is &lt;code&gt;loss.backward()&lt;/code&gt;, which finds all the derivatives with the chain rule and stores them in &lt;code&gt;w.grad&lt;/code&gt; and &lt;code&gt;b.grad&lt;/code&gt;. We no longer write the derivatives by hand:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;lossi&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="c1"&gt;# forward pass&lt;/span&gt;
  &lt;span class="n"&gt;hx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;  &lt;span class="no"&gt;X&lt;/span&gt; @ &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
  &lt;span class="n"&gt;loss&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hx&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="c1"&gt;# backward pass&lt;/span&gt;
  &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
  &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
  &lt;span class="n"&gt;loss&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;backward&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="n"&gt;lossi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;loss&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;item&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

  &lt;span class="c1"&gt;# update the parameters&lt;/span&gt;
  &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;no_grad&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt;
    &lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;learning_rate&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;grad&lt;/span&gt;

&lt;span class="n"&gt;loss&lt;/span&gt;
&lt;span class="c1"&gt;# tensor(1329.7212, grad_fn=&amp;lt;MeanBackward0&amp;gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three details that matter:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;with torch.no_grad()&lt;/code&gt;&lt;/strong&gt;: without it, the update fails with &lt;em&gt;"a leaf Variable that requires grad is being used in an in-place operation"&lt;/em&gt;. PyTorch would be tracking the update itself, so we turn tracking off for it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;w.grad = None&lt;/code&gt;&lt;/strong&gt;: PyTorch &lt;em&gt;adds&lt;/em&gt; new gradients to old ones. We reset them in every step, so each new loss gets its own fresh gradients.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;loss.item()&lt;/code&gt;&lt;/strong&gt;: &lt;code&gt;loss&lt;/code&gt; is a tensor. &lt;code&gt;.item()&lt;/code&gt; gives a plain number, so &lt;code&gt;lossi&lt;/code&gt; is a list of numbers.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Plot the losses to see how the model learns:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;plt&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;plot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;lossi&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Keep running until the curve goes flat. Then the model has converged, and more steps change nothing. Here the loss fell from 4,059 to 1,329.7.&lt;/p&gt;

&lt;h3&gt;
  
  
  Predict a new house
&lt;/h3&gt;

&lt;p&gt;We use the same scaled values from before, 2.5002 and 2.1985, as one row:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mf"&gt;2.5002&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;2.1985&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; @ &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
&lt;span class="c1"&gt;# tensor([714.4709], grad_fn=&amp;lt;AddBackward0&amp;gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;About 714 for a house of 4,000 sq ft with 5 bedrooms.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Hypothesis:&lt;/strong&gt; the model, &lt;code&gt;hx = X @ w + b&lt;/code&gt;, makes a prediction from the features.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Loss:&lt;/strong&gt; the average squared error between the prediction and the real price.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Gradient:&lt;/strong&gt; the derivatives of the loss, found with the chain rule (&lt;code&gt;loss.backward()&lt;/code&gt;), tell us the direction to move each weight.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Update:&lt;/strong&gt; move a small step in that direction. The step size is the learning rate.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Repeat&lt;/strong&gt; until the loss stops going down. The loss curve shows how well the model is learning.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This model is also a &lt;strong&gt;single-layer neural network&lt;/strong&gt;, so it opens two paths: classical machine learning, and deep learning.&lt;/p&gt;

&lt;h2&gt;
  
  
  Exercise
&lt;/h2&gt;

&lt;p&gt;Turn this into a Python class using OOP, with a &lt;code&gt;train&lt;/code&gt; method and a &lt;code&gt;predict&lt;/code&gt; method. Store the training mean and std inside the class, so &lt;code&gt;predict&lt;/code&gt; can scale new houses itself. Then try it on a different dataset.&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>python</category>
      <category>pytorch</category>
      <category>beginners</category>
    </item>
    <item>
      <title>RAG from Zero to Hero: Building Naive, Advanced and Modular RAG from Scratch with Python</title>
      <dc:creator>Lochan Jangid</dc:creator>
      <pubDate>Fri, 06 Nov 2026 20:04:48 +0000</pubDate>
      <link>https://dev.to/lochanjangid/rag-from-zero-to-hero-building-naive-advanced-and-modular-rag-from-scratch-with-python-3k7m</link>
      <guid>https://dev.to/lochanjangid/rag-from-zero-to-hero-building-naive-advanced-and-modular-rag-from-scratch-with-python-3k7m</guid>
      <description>&lt;h1&gt;
  
  
  RAG from Zero to Hero: Building Naive, Advanced and Modular RAG from Scratch with Python
&lt;/h1&gt;

&lt;p&gt;🎥 Watch the complete video tutorial: &lt;a href="https://www.youtube.com/watch?v=aenpTk8blIs" rel="noopener noreferrer"&gt;https://www.youtube.com/watch?v=aenpTk8blIs&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fb09pb0bb2b6lorl9zmfa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fb09pb0bb2b6lorl9zmfa.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this hands-on tutorial, we'll build Naive RAG, Advanced RAG and Modular RAG step by step.&lt;/p&gt;

&lt;p&gt;I wanted to learn Retrieval-Augmented Generation (RAG) the way Andrej Karpathy teaches machine learning: understanding every concept from first principles, building things from scratch, and knowing what actually happens under the hood.&lt;/p&gt;

&lt;p&gt;But I struggled to find a single resource that covered the complete journey, from understanding the fundamentals to implementing more advanced RAG architectures.&lt;/p&gt;

&lt;p&gt;After learning it myself, I thought other developers might face the same problem. So I decided to create this walkthrough.&lt;/p&gt;

&lt;p&gt;In this article, we'll explore RAG, understand why we need it, and progressively build three types of RAG systems using Python:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Naive RAG&lt;/li&gt;
&lt;li&gt;Advanced RAG&lt;/li&gt;
&lt;li&gt;Modular RAG&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We'll also understand document chunking, vectorization, indexing, retrieval, query rewriting, reranking, routing and query fusion.&lt;/p&gt;

&lt;p&gt;The goal isn't just to make RAG work. It's to understand why each component exists.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. Why Do We Need RAG?
&lt;/h2&gt;

&lt;p&gt;Large Language Models (LLMs) are impressive. They can understand questions, generate explanations, write code and perform complex reasoning.&lt;/p&gt;

&lt;p&gt;However, they have some important limitations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Hallucinations&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;LLMs can generate answers that sound convincing but aren't factually correct.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Outdated knowledge&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;An LLM's knowledge comes primarily from its training data. It doesn't automatically know about events, documents or information created after its training cutoff.&lt;/p&gt;

&lt;p&gt;Consider a simple example:&lt;/p&gt;

&lt;p&gt;If you ask an LLM:&lt;/p&gt;

&lt;p&gt;"What happened in the latest news three days ago?"&lt;/p&gt;

&lt;p&gt;A model without access to that information cannot reliably answer.&lt;/p&gt;

&lt;p&gt;This is where Retrieval-Augmented Generation comes in.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is RAG?
&lt;/h3&gt;

&lt;p&gt;RAG stands for Retrieval-Augmented Generation.&lt;/p&gt;

&lt;p&gt;The central idea is simple:&lt;/p&gt;

&lt;p&gt;Instead of asking an LLM to answer a question using only its internal knowledge, we first retrieve relevant information from external documents and provide that information as context.&lt;/p&gt;

&lt;p&gt;The LLM then generates an answer based on the retrieved context.&lt;/p&gt;

&lt;p&gt;The basic workflow looks like this:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Load external documents.&lt;/li&gt;
&lt;li&gt;Split documents into smaller chunks.&lt;/li&gt;
&lt;li&gt;Convert chunks into numerical vectors.&lt;/li&gt;
&lt;li&gt;Store and index those vectors.&lt;/li&gt;
&lt;li&gt;Convert the user's query into a vector.&lt;/li&gt;
&lt;li&gt;Retrieve relevant chunks.&lt;/li&gt;
&lt;li&gt;Combine the retrieved context with the user's question.&lt;/li&gt;
&lt;li&gt;Send the prompt to an LLM.&lt;/li&gt;
&lt;li&gt;Generate an answer.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That's the fundamental idea behind RAG.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. Understanding the RAG Architecture
&lt;/h2&gt;

&lt;p&gt;Before writing code, let's understand the two main parts of a RAG system.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Indexing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Indexing happens before the user asks a question.&lt;/p&gt;

&lt;p&gt;We load documents, split them into chunks, transform those chunks into vectors and store them in an index.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Retrieval and Generation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When a user asks a question, we transform the query into a vector, search for relevant chunks, construct a prompt and send it to the LLM.&lt;/p&gt;

&lt;p&gt;The overall architecture:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Documents → Chunking → Vectorization → Indexing&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;User Query → Vectorization → Retrieval → Context + Query → LLM → Answer&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This is the foundation we'll use throughout the implementation.&lt;/p&gt;




&lt;h2&gt;
  
  
  3. Building Our First RAG System: Naive RAG
&lt;/h2&gt;

&lt;p&gt;Let's implement everything ourselves.&lt;/p&gt;

&lt;p&gt;For this walkthrough, I'll use a document containing the story of The Amazing Spider-Man.&lt;/p&gt;

&lt;p&gt;Why Spider-Man? Because it's an easy example to understand, and we can ask questions about its characters and story.&lt;/p&gt;

&lt;p&gt;Our goal is to answer questions using information from this document.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 1: Load the document
&lt;/h3&gt;

&lt;p&gt;First, we load our text document using Python.&lt;/p&gt;

&lt;p&gt;We can inspect its contents and calculate its length.&lt;/p&gt;

&lt;p&gt;Imagine the document contains around 12,000 characters.&lt;/p&gt;

&lt;p&gt;One approach would be to send the entire document directly to an LLM along with every question.&lt;/p&gt;

&lt;p&gt;But that's inefficient.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We waste tokens on irrelevant information.&lt;/li&gt;
&lt;li&gt;Long documents increase the prompt size.&lt;/li&gt;
&lt;li&gt;The model receives more information than it needs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Instead, we need to divide the document into smaller pieces.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 2: Document chunking
&lt;/h3&gt;

&lt;p&gt;Chunking means splitting a document into smaller sections.&lt;/p&gt;

&lt;p&gt;For example, we might initially choose a chunk size of 200 characters.&lt;/p&gt;

&lt;p&gt;Each chunk becomes a smaller unit that can be independently retrieved.&lt;/p&gt;

&lt;p&gt;However, simple character-based chunking creates a problem.&lt;/p&gt;

&lt;p&gt;Consider this sentence:&lt;/p&gt;

&lt;p&gt;"Peter Parker grows up with questions about his family when they disappear under mysterious circumstances."&lt;/p&gt;

&lt;p&gt;If we split this sentence at an arbitrary character position, we might get:&lt;/p&gt;

&lt;p&gt;Chunk 1: "Peter Parker grows up with questions about his family when they disappear under myster..."&lt;/p&gt;

&lt;p&gt;Chunk 2: "...ious circumstances."&lt;/p&gt;

&lt;p&gt;Now the second chunk has lost important context.&lt;/p&gt;

&lt;p&gt;This is a problem because retrieval might return incomplete information.&lt;/p&gt;

&lt;h3&gt;
  
  
  Improving chunking with paragraphs and overlap
&lt;/h3&gt;

&lt;p&gt;Instead of blindly splitting the document every 200 characters, we can first divide it into paragraphs.&lt;/p&gt;

&lt;p&gt;Then we combine paragraphs until we approach our desired chunk size.&lt;/p&gt;

&lt;p&gt;We also introduce &lt;strong&gt;overlapping chunks&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Overlap means carrying a small portion of the previous chunk into the next chunk.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Chunk size: 200 characters&lt;/li&gt;
&lt;li&gt;Overlap: 50 characters&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This preserves some surrounding context between chunks.&lt;/p&gt;

&lt;p&gt;We also need to avoid cutting words in the middle. If a chunk boundary falls inside a word, we can move the boundary to a nearby whitespace character.&lt;/p&gt;

&lt;p&gt;This gives us more meaningful chunks.&lt;/p&gt;

&lt;p&gt;Our initial implementation produces around 61 chunks, while the improved chunking approach produces around 63 chunks.&lt;/p&gt;

&lt;p&gt;The exact number depends on the document and chunking configuration.&lt;/p&gt;

&lt;p&gt;The important lesson is that chunking is not just about dividing text. It's about preserving meaning.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. Vectorization: Converting Text into Numbers
&lt;/h2&gt;

&lt;p&gt;Computers cannot directly perform mathematical similarity searches on ordinary text.&lt;/p&gt;

&lt;p&gt;We need to represent our chunks numerically.&lt;/p&gt;

&lt;p&gt;This is where vectorization comes in.&lt;/p&gt;

&lt;p&gt;In this implementation, we'll use TF-IDF.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is TF-IDF?
&lt;/h3&gt;

&lt;p&gt;TF-IDF stands for Term Frequency-Inverse Document Frequency.&lt;/p&gt;

&lt;p&gt;It combines two ideas:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TF: Term Frequency&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;How frequently does a word appear in a document?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IDF: Inverse Document Frequency&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;How uncommon is that word across the collection of documents?&lt;/p&gt;

&lt;p&gt;Words that appear frequently in a particular document but are relatively uncommon across other documents can receive higher importance.&lt;/p&gt;

&lt;p&gt;Common words such as "the", "is" and "and" generally provide less useful information for distinguishing documents.&lt;/p&gt;

&lt;p&gt;TF-IDF converts text into numerical feature vectors based on these word statistics.&lt;/p&gt;

&lt;p&gt;We'll use Scikit-learn:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;sklearn.feature_extraction.text&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;TfidfVectorizer&lt;/span&gt;

&lt;span class="n"&gt;vectorizer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;TfidfVectorizer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;stop_words&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;english&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;vectors&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;vectorizer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fit_transform&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result is a sparse matrix.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is a sparse matrix?
&lt;/h3&gt;

&lt;p&gt;A sparse matrix is a matrix in which most elements are zero.&lt;/p&gt;

&lt;p&gt;Instead of storing every zero value, sparse representations efficiently store the non-zero values.&lt;/p&gt;

&lt;p&gt;This saves memory when working with high-dimensional text vectors.&lt;/p&gt;

&lt;p&gt;For our implementation, we'll convert the vectors into dense NumPy arrays before passing them to FAISS.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important distinction:&lt;/strong&gt; TF-IDF is a lexical vectorization technique. It represents word importance, not deep semantic meaning. Modern production RAG systems commonly use dense embedding models for semantic retrieval.&lt;/p&gt;




&lt;h2&gt;
  
  
  5. Indexing with FAISS
&lt;/h2&gt;

&lt;p&gt;Now we have vectors representing our document chunks.&lt;/p&gt;

&lt;p&gt;But how do we efficiently search through them?&lt;/p&gt;

&lt;p&gt;Imagine having thousands or millions of chunks. Searching through every document manually would be inefficient.&lt;/p&gt;

&lt;p&gt;We need an index.&lt;/p&gt;

&lt;p&gt;We'll use FAISS (Facebook AI Similarity Search).&lt;/p&gt;

&lt;p&gt;FAISS is a library designed for efficient similarity search over vectors.&lt;/p&gt;

&lt;p&gt;Think of our vectors as points in a high-dimensional mathematical space.&lt;/p&gt;

&lt;p&gt;When a query arrives, we convert it into a vector and search for nearby vectors.&lt;/p&gt;

&lt;p&gt;The nearest vectors represent our candidate chunks.&lt;/p&gt;

&lt;h3&gt;
  
  
  Normalization and cosine similarity
&lt;/h3&gt;

&lt;p&gt;We also need to understand cosine similarity.&lt;/p&gt;

&lt;p&gt;Cosine similarity measures the angle between two vectors.&lt;/p&gt;

&lt;p&gt;A higher cosine similarity generally indicates that two vectors point in a more similar direction.&lt;/p&gt;

&lt;p&gt;Mathematically:&lt;/p&gt;

&lt;p&gt;[&lt;/p&gt;

&lt;h1&gt;
  
  
  \text{Cosine Similarity}(A,B)
&lt;/h1&gt;

&lt;p&gt;\frac{A \cdot B}{|A||B|}&lt;br&gt;
]&lt;/p&gt;

&lt;p&gt;We normalize our vectors so their lengths become 1.&lt;/p&gt;

&lt;p&gt;After normalization, the inner product between two vectors is equivalent to cosine similarity.&lt;/p&gt;

&lt;p&gt;We'll use FAISS to create an index and add our vectors to it.&lt;/p&gt;

&lt;p&gt;With an inner-product index and normalized vectors, we can retrieve the nearest neighbors efficiently.&lt;/p&gt;


&lt;h2&gt;
  
  
  6. Retrieval: Finding Relevant Chunks
&lt;/h2&gt;

&lt;p&gt;Now comes the interesting part.&lt;/p&gt;

&lt;p&gt;Let's ask:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;"Who is Spider-Man?"&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, we transform the user's query using the same TF-IDF vectorizer.&lt;/p&gt;

&lt;p&gt;Then we search the FAISS index.&lt;/p&gt;

&lt;p&gt;We can request the top 3 nearest neighbors by setting:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;k = 3&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;FAISS returns similarity scores and the indices of the nearest chunks.&lt;/p&gt;

&lt;p&gt;Using those indices, we retrieve the original text chunks.&lt;/p&gt;

&lt;p&gt;These chunks become our context.&lt;/p&gt;

&lt;p&gt;Now we have:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The user's question.&lt;/li&gt;
&lt;li&gt;The relevant document chunks.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We're almost ready to connect our LLM.&lt;/p&gt;


&lt;h2&gt;
  
  
  7. Connecting the LLM
&lt;/h2&gt;

&lt;p&gt;We need an LLM to generate an answer using our retrieved context.&lt;/p&gt;

&lt;p&gt;For this implementation, I use Groq through an OpenAI-compatible client.&lt;/p&gt;

&lt;p&gt;The important part isn't the provider. It's how we construct the prompt.&lt;/p&gt;

&lt;p&gt;A basic prompt might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Answer using only the provided context.

If the answer is not present in the context,
respond with "I don't know".

Context:
{retrieved_context}

Question:
{user_question}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We combine our retrieved chunks into a single context string and send the prompt to the LLM.&lt;/p&gt;

&lt;p&gt;Now the model has access to information from our document.&lt;/p&gt;

&lt;p&gt;This completes our first Naive RAG implementation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Testing our first RAG system
&lt;/h3&gt;

&lt;p&gt;Let's ask:&lt;/p&gt;

&lt;p&gt;"Who is Spider-Man?"&lt;/p&gt;

&lt;p&gt;Our system retrieves relevant chunks and sends them to the LLM.&lt;/p&gt;

&lt;p&gt;The model can now answer using the information provided in the document.&lt;/p&gt;

&lt;p&gt;However, our initial implementation also reveals some problems.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Some chunks contain incomplete sentences.&lt;/li&gt;
&lt;li&gt;Retrieval can return irrelevant information.&lt;/li&gt;
&lt;li&gt;A user's query might not match the wording used in the document.&lt;/li&gt;
&lt;li&gt;The retrieved context may contain unnecessary information.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is why we need to improve our architecture.&lt;/p&gt;




&lt;h2&gt;
  
  
  8. Advanced RAG: Improving Retrieval
&lt;/h2&gt;

&lt;p&gt;Naive RAG follows a straightforward pipeline:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Query → Retrieval → Context → LLM → Answer&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Advanced RAG introduces additional processing before and after retrieval.&lt;/p&gt;

&lt;p&gt;These are commonly called:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Pre-retrieval optimization&lt;/li&gt;
&lt;li&gt;Post-retrieval optimization&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The objective is to improve the quality of retrieved information before generating the final answer.&lt;/p&gt;

&lt;h3&gt;
  
  
  A. Pre-retrieval: Query Rewriting
&lt;/h3&gt;

&lt;p&gt;Imagine a user asks:&lt;/p&gt;

&lt;p&gt;"Who is Spider-Man?"&lt;/p&gt;

&lt;p&gt;The query is understandable, but it might not contain all the information needed for effective retrieval.&lt;/p&gt;

&lt;p&gt;We can send the query to an LLM and ask it to rewrite the query for retrieval.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;p&gt;Original query:&lt;/p&gt;

&lt;p&gt;"Who is Spider-Man?"&lt;/p&gt;

&lt;p&gt;Rewritten query:&lt;/p&gt;

&lt;p&gt;"Find details about Spider-Man, Peter Parker, including his identity, powers, creators and origin story."&lt;/p&gt;

&lt;p&gt;The rewritten query provides additional search terms and context.&lt;/p&gt;

&lt;p&gt;We then convert this new query into a vector and search our existing index.&lt;/p&gt;

&lt;p&gt;The goal is to retrieve more relevant chunks.&lt;/p&gt;

&lt;p&gt;This process is called query rewriting.&lt;/p&gt;

&lt;h3&gt;
  
  
  B. Post-retrieval: Reranking
&lt;/h3&gt;

&lt;p&gt;Retrieval gives us candidate chunks, but not every retrieved chunk is equally useful.&lt;/p&gt;

&lt;p&gt;Some chunks might be relevant, while others might contain unnecessary information.&lt;/p&gt;

&lt;p&gt;Reranking helps us improve the order and relevance of the retrieved results.&lt;/p&gt;

&lt;p&gt;In our implementation, we send the retrieved chunks to an LLM and ask it to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Identify relevant information.&lt;/li&gt;
&lt;li&gt;Rank the chunks according to relevance.&lt;/li&gt;
&lt;li&gt;Ignore irrelevant information.&lt;/li&gt;
&lt;li&gt;Preserve useful facts for answering the question.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example, if we ask:&lt;/p&gt;

&lt;p&gt;"Who is Spider-Man?"&lt;/p&gt;

&lt;p&gt;A chunk explaining that Peter Parker is Spider-Man is much more useful than a chunk describing an unrelated event.&lt;/p&gt;

&lt;p&gt;The reranked context is then passed to the LLM.&lt;/p&gt;

&lt;h3&gt;
  
  
  Advanced RAG architecture
&lt;/h3&gt;

&lt;p&gt;Our improved pipeline now looks like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;User Query → Query Rewriting → Retrieval → Reranking → Context → LLM → Answer&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We've introduced two important improvements without changing the fundamental idea of RAG.&lt;/p&gt;

&lt;p&gt;Query rewriting improves what we search for.&lt;/p&gt;

&lt;p&gt;Reranking improves what we use after searching.&lt;/p&gt;




&lt;h2&gt;
  
  
  9. Modular RAG: Combining Different Retrieval Strategies
&lt;/h2&gt;

&lt;p&gt;Now we move to Modular RAG.&lt;/p&gt;

&lt;p&gt;This is where things become more interesting.&lt;/p&gt;

&lt;p&gt;Instead of treating RAG as one fixed pipeline, we treat different operations as independent modules.&lt;/p&gt;

&lt;p&gt;We can combine them depending on the problem.&lt;/p&gt;

&lt;p&gt;In this implementation, we'll explore three important techniques:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Routing&lt;/li&gt;
&lt;li&gt;Query Fusion&lt;/li&gt;
&lt;li&gt;Reciprocal Rank Fusion&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  A. Routing
&lt;/h3&gt;

&lt;p&gt;Does every question need document retrieval?&lt;/p&gt;

&lt;p&gt;Not necessarily.&lt;/p&gt;

&lt;p&gt;Imagine asking:&lt;/p&gt;

&lt;p&gt;"Who is Spider-Man?"&lt;/p&gt;

&lt;p&gt;An LLM already has general knowledge about Spider-Man.&lt;/p&gt;

&lt;p&gt;But what if we ask:&lt;/p&gt;

&lt;p&gt;"What happened to Spider-Man yesterday in my document?"&lt;/p&gt;

&lt;p&gt;Now we need to search our external document.&lt;/p&gt;

&lt;p&gt;Routing allows the system to decide whether it should answer directly or retrieve information from an external knowledge source.&lt;/p&gt;

&lt;p&gt;We can ask an LLM to classify a question:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Chat: The question can be answered using the model's existing knowledge.&lt;/li&gt;
&lt;li&gt;Document: The question requires external document retrieval.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The system then follows the appropriate path.&lt;/p&gt;

&lt;p&gt;This avoids unnecessary retrieval operations for questions that don't need them.&lt;/p&gt;

&lt;h3&gt;
  
  
  B. Query Fusion
&lt;/h3&gt;

&lt;p&gt;Traditional retrieval often searches using one query.&lt;/p&gt;

&lt;p&gt;But a single query may not capture every possible interpretation of the user's question.&lt;/p&gt;

&lt;p&gt;Consider:&lt;/p&gt;

&lt;p&gt;"Who is Spider-Man?"&lt;/p&gt;

&lt;p&gt;We can generate multiple related queries:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Who is Spider-Man?&lt;/li&gt;
&lt;li&gt;What is Spider-Man's real name?&lt;/li&gt;
&lt;li&gt;Which comic book character is known as Spider-Man?&lt;/li&gt;
&lt;li&gt;What is Spider-Man's origin story?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now we have several search queries instead of one.&lt;/p&gt;

&lt;p&gt;We perform retrieval for each query.&lt;/p&gt;

&lt;p&gt;Each query can discover different relevant chunks.&lt;/p&gt;

&lt;p&gt;However, this introduces another problem: duplicate results and different rankings across queries.&lt;/p&gt;

&lt;p&gt;We need a way to combine them.&lt;/p&gt;

&lt;h3&gt;
  
  
  C. Reciprocal Rank Fusion (RRF)
&lt;/h3&gt;

&lt;p&gt;Reciprocal Rank Fusion is a ranking technique used to combine results from multiple ranked lists.&lt;/p&gt;

&lt;p&gt;Instead of relying only on raw similarity scores, it considers the position of each result in different rankings.&lt;/p&gt;

&lt;p&gt;The general formula is:&lt;/p&gt;

&lt;p&gt;[&lt;br&gt;
RRF(d)=\sum_{r \in R}\frac{1}{k+r(d)}&lt;br&gt;
]&lt;/p&gt;

&lt;p&gt;Where:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;(d) is a document or chunk.&lt;/li&gt;
&lt;li&gt;(R) represents the different ranked result lists.&lt;/li&gt;
&lt;li&gt;(r(d)) is the rank of the document in a particular list.&lt;/li&gt;
&lt;li&gt;(k) is a smoothing constant.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Chunks that consistently appear near the top of multiple result lists receive higher combined scores.&lt;/p&gt;

&lt;p&gt;We can then sort the chunks and select the most relevant results.&lt;/p&gt;

&lt;p&gt;This helps us combine information retrieved through multiple query perspectives.&lt;/p&gt;

&lt;h3&gt;
  
  
  Modular RAG architecture
&lt;/h3&gt;

&lt;p&gt;Our modular pipeline can now include:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;User Query → Routing → Query Generation → Multiple Retrieval Operations → RRF → Context → LLM → Answer&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We can also combine the techniques from Advanced RAG:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Query rewriting&lt;/li&gt;
&lt;li&gt;Reranking&lt;/li&gt;
&lt;li&gt;Retrieval&lt;/li&gt;
&lt;li&gt;Query fusion&lt;/li&gt;
&lt;li&gt;Routing&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The important idea is that these components are modules. We can add, remove or combine them depending on the application.&lt;/p&gt;




&lt;h2&gt;
  
  
  10. Putting Everything Together
&lt;/h2&gt;

&lt;p&gt;We've now explored three different RAG architectures.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Naive RAG&lt;/th&gt;
&lt;th&gt;Advanced RAG&lt;/th&gt;
&lt;th&gt;Modular RAG&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Document chunking&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Vectorization&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Indexing&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Retrieval&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Query rewriting&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Can be included&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Reranking&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Can be included&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Routing&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Not in our basic implementation&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Query fusion&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Not in our basic implementation&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Flexible modules&lt;/td&gt;
&lt;td&gt;Limited&lt;/td&gt;
&lt;td&gt;Somewhat&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The progression is straightforward:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Naive RAG:&lt;/strong&gt; Retrieve relevant chunks and generate an answer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advanced RAG:&lt;/strong&gt; Improve retrieval using query optimization and post-retrieval processing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Modular RAG:&lt;/strong&gt; Combine multiple independent techniques to create a more flexible retrieval system.&lt;/p&gt;

&lt;p&gt;These aren't rigid definitions or mandatory stages. Real-world RAG architectures can combine techniques from different approaches.&lt;/p&gt;




&lt;h2&gt;
  
  
  11. What Comes After Modular RAG?
&lt;/h2&gt;

&lt;p&gt;Building a basic RAG system is only the beginning.&lt;/p&gt;

&lt;p&gt;There are several other directions worth exploring.&lt;/p&gt;

&lt;p&gt;Some important challenges include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Retrieval quality&lt;/li&gt;
&lt;li&gt;Generation quality&lt;/li&gt;
&lt;li&gt;Chunking strategies&lt;/li&gt;
&lt;li&gt;Context relevance&lt;/li&gt;
&lt;li&gt;Query understanding&lt;/li&gt;
&lt;li&gt;Latency and cost&lt;/li&gt;
&lt;li&gt;Evaluation and reliability&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We can also explore different optimization strategies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iterative RAG&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The system retrieves information, generates an answer and repeats retrieval when more information is needed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Recursive RAG&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The system can break complex questions into smaller questions and retrieve information recursively.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Adaptive RAG&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The system adapts its retrieval strategy depending on the query and task.&lt;/p&gt;

&lt;p&gt;Beyond these approaches, we can explore:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Dense embeddings&lt;/li&gt;
&lt;li&gt;Hybrid search&lt;/li&gt;
&lt;li&gt;Metadata filtering&lt;/li&gt;
&lt;li&gt;RAG evaluation&lt;/li&gt;
&lt;li&gt;Fine-tuning retrievers&lt;/li&gt;
&lt;li&gt;Context compression&lt;/li&gt;
&lt;li&gt;More advanced retrieval architectures&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;RAG is not a single algorithm. It's a collection of techniques that can be combined to build better knowledge-grounded applications.&lt;/p&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;We started with a simple question:&lt;/p&gt;

&lt;p&gt;Why do we need RAG when we already have powerful LLMs?&lt;/p&gt;

&lt;p&gt;Then we built a complete progression:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Naive RAG from scratch.&lt;/li&gt;
&lt;li&gt;Advanced RAG with query rewriting and reranking.&lt;/li&gt;
&lt;li&gt;Modular RAG with routing, query fusion and Reciprocal Rank Fusion.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Along the way, we explored chunking, TF-IDF, vectorization, sparse matrices, FAISS, normalization, cosine similarity and prompt construction.&lt;/p&gt;

&lt;p&gt;My biggest takeaway is that understanding the individual components is much more valuable than simply knowing how to call a RAG framework.&lt;/p&gt;

&lt;p&gt;Once you understand the fundamentals, frameworks become tools rather than black boxes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keep building, keep experimenting, and understand what's happening under the hood.&lt;/strong&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Watch the Complete Video Walkthrough
&lt;/h2&gt;

&lt;p&gt;I also recorded the complete implementation, explaining the concepts and building the different RAG architectures step by step using Python.&lt;/p&gt;

&lt;p&gt;🎥 &lt;strong&gt;RAG: Zero to Hero&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.youtube.com/watch?v=aenpTk8blIs" rel="noopener noreferrer"&gt;https://www.youtube.com/watch?v=aenpTk8blIs&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you're learning LLMs, Generative AI or AI engineering, I hope this resource helps you understand RAG from the ground up.&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;

</description>
      <category>ai</category>
      <category>python</category>
      <category>rag</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
