Linear Regression with PHP

Simple Linear Regression with Rubix

Used when there is only one independent variable. For this example, let’s use a small dataset with square footage and price. This is the simplest form of linear regression, and it involves only one independent variable and one dependent variable. The equation for simple linear regression is: $y=\beta_{0} +\beta _{1} * x$

size,price
800,168400
900,172300
1000,185600
1100,178900
1200,195400
1300,188900
1400,215600
1480,255600
1500,198400
1600,228900
1700,235400
1800,225800
1790,210800
1900,242300
2000,238900
2100,265400
2200,248900
2300,272300
2400,285600
2500,278900
2600,295400
2700,282300
2720,272300
2800,308900
2900,298400
3000,325600

Example of use:

 
<?php

use Rubix\ML\Datasets\Labeled;
use 
Rubix\ML\Datasets\Unlabeled;
use 
Rubix\ML\Extractors\CSV;
use 
Rubix\ML\Regressors\Ridge;
use 
Rubix\ML\CrossValidation\Metrics\MeanSquaredError;
use 
Rubix\ML\Transformers\MissingDataImputer;
use 
Rubix\ML\Transformers\NumericStringConverter;


// Load the raw data from CSV
$dataset Labeled::fromIterator(new CSV(dirname(__FILE__) . '/data/houses1.csv'true));

// For PHP 8.2
// Convert samples and labels to float
$samples array_map(fn($sample) => array_map('floatval'$sample), $dataset->samples());
$labels array_map('floatval'$dataset->labels());
// Create new dataset with float values
$dataset = new Labeled($samples$labels);

// For PHP 8.3
// Convert samples and labels to their equivalent integer and floating point types
//$dataset->apply(new NumericStringConverter())
//    ->apply(new MissingDataImputer())
//    ->transformLabels('intval');

// Create and train Ridge regression model
// 1.0 controls how much we prevent overfitting
$estimator = new Ridge(1.0);
$estimator->train($dataset);

// Predict price for a 2250 sq ft house
$newSample = [2250];
$newDataset = new Unlabeled([$newSample]);
$prediction $estimator->predict($newDataset);

// Show results
echo 'Sample size: 2250 sq.ft';
echo 
"\nPredicted Price for: $" number_format($prediction[0], decimals2);

// Calculate MSE - check how accurate our model is using Mean Squared Error
// Lower number = better predictions
$mse = new MeanSquaredError();

// Get predictions and labels, ensure they're floats
$predictions array_map('floatval'$estimator->predict($dataset));
$actuals array_map('floatval'$dataset->labels());

// Scale down by 1000
$scaledPredictions array_map(function($val) { return $val 1000; }, $predictions);
$scaledActuals array_map(function($val) { return $val 1000; }, $actuals);

$score $mse->score($scaledPredictions$scaledActuals);

echo 
"\n\nMean Squared Error (scaled): $" number_format(abs($score), 3) . "k²";
echo 
"\nRoot Mean Squared Error (scaled): $" number_format(sqrt(abs($score)), decimals2) . "k";