Linear regression as a basic model

Case 1. Apartment valuation based on parameters


Implementation in pure PHP

(analytical solution – via normal equations)

Now we will solve the same task without iterative training — analytically, using normal equations. This approach gives us the model weights directly from the formula $w^* = (X^T X)^{-1} X^T y$. The idea is simple: build the feature matrix $X$, transpose it, multiply it by itself, invert $X^T X$, and obtain the final weights directly.

 
<?php

include('formula-code.php');

use 
app\classes\Matrix;

// Normal equation formula: w* = (X^T X)^-1 X^T y
// Prepare data
$X = new Matrix([
    [
5035101],
    [
8012231],
    [
4557201],
    [
6084151],
    [
30110401],
]);

$y = new Matrix([
    [
60_000],
    [
120_000],
    [
55_000],
    [
80_000],
    [
30_000],
]);

// Compute weights
$Xt $X->transpose();                          // X^T
$XtX $Xt->multiply($X);                       // X^T * X
$XtX_inv $XtX->regularizedInverse(0.014);   // (X^T * X + λI)^-1
$Xt_y $Xt->multiply($y);                      // X^T y
$w $XtX_inv->multiply($Xt_y);                 // final weights

function predict(array $xMatrix $w): float {
    
$sum 0.0;

    foreach (
$x as $i => $value) {
        
$sum += $value $w->data[$i][0];
    }

    return 
$sum;
}

$newApartment = [6054121];
$price predict($newApartment$w);

$bias array_pop($w->data);
$weights $w->data;

echo 
'Apartment valuation: $' number_format($price) . PHP_EOL PHP_EOL;

echo 
'Weights: ' implode(', 'array_map(fn ($weight) => number_format($weight[0], 2'.'''), $weights)) . PHP_EOL;
echo 
'Bias: ' number_format(array_pop($bias), 2'.''') . PHP_EOL;

Charts:

Chart Type:

Result: Memory: 0.034 Mb Time running: 0.001 sec.
Apartment valuation: $80,003

Weights: 2326.89, 6.71, 3286.87, 3.65
Bias: -72834.76

The block above shows the result of the script: the computed weights and the predicted apartment price for the following features:

  • Apartment area: 60 m²
  • Number of rooms: 5
  • Number of bathrooms: 4
  • Number of floors: 12