Fit a linear model and predict
On this page
Fit fuel economy from weight and number of cylinders, then predict two cars with 95% prediction intervals.
The data are mtcars: fuel consumption and design of 32 cars (1973–74 models) from Motor Trend. mpg is miles per US gallon, wt is weight in 1,000 lb, and cyl is the number of cylinders. The example reads the file by URL with phibble (composer require phpstats/phibble) and runs with the phit extension or the plain-PHP polyfill (Extension or polyfill).
Code
use Phibble\DataFrame;use function Phit\{fit_ols, predict};$cars = DataFrame::fromCsv( 'https://raw.githubusercontent.com/phpstats/datasets/main/csv/mtcars.csv',);$fit = fit_ols('mpg ~ wt + factor(cyl)', $cars);echo $fit, "\n";$new = ['wt' => [2.5, 3.5], 'cyl' => [4, 8]];$p = predict($fit, $new, interval: 'prediction');echo DataFrame::fromColumns([ 'wt' => $new['wt'], 'cyl' => $new['cyl'], 'mpg' => $p['fit'], 'lower' => $p['lower'], 'upper' => $p['upper'],]), "\n";Output
Linear model fit by least squares
Formula: mpg ~ wt + factor(cyl)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 33.9908 1.8878 18.006 < 2e-16
wt -3.2056 0.7539 -4.252 0.000213
factor(cyl)6 -4.2556 1.3861 -3.070 0.004718
factor(cyl)8 -6.0709 1.6523 -3.674 0.000999
Residual standard error: 2.557 on 28 degrees of freedom
Multiple R-squared: 0.8374, Adjusted R-squared: 0.82
F-statistic: 48.08 on 3 and 28 DF, p-value: 3.594e-11
# A tibble: 2 × 5
wt cyl mpg lower upper
<dbl> <int> <dbl> <dbl> <dbl>
1 2.5 4 26.0 20.5 31.5
2 3.5 8 16.7 11.2 22.2
Interpretation
factor(cyl)treats the number of cylinders as categories. Four cylinders is the reference, andfactor(cyl)6andfactor(cyl)8compare six and eight cylinders with four for cars of the same weight.- The
wtcoefficient is the difference in miles per gallon associated with 1,000 lb more weight among cars with the same number of cylinders. It describes these 32 cars, not the effect of adding weight to a car. - With 32 cars and correlated predictors, the standard errors are large relative to the estimates.
- A prediction interval covers one new car’s mileage. A confidence interval (
interval: 'confidence') covers the mean mileage of such cars and is narrower.
See also: A first model · Linear and generalized linear models · Model formulas