相比 Perl (PDL)、Python (NumPy/SciPy/StatsModels)、R、Julia,PHP 社群長期缺乏標準化、高效能的數學統計庫。原因包括:
exec()/API 呼叫。但出於教學、輕量部署、避免外部依賴,純 PHP 實現基礎統計模型仍有價值。
SimpleLinearRegression、MultipleRegression、ANOVA 各自封裝。getXxx() 方法,便於外部存取與單元測試。getSumSquaredError() 而非 getSSE(),降低認知負荷。<?php
class SimpleLinearRegression {
// --- 輸入資料 ---
private $X = []; // 自變量陣列
private $Y = []; // 應變量陣列
private $n = 0; // 樣本數
// --- 中間統計量 ---
private $XMean = 0;
private $YMean = 0;
private $SumXX = 0; // Σ(x - x̄)²
private $SumXY = 0; // Σ(x - x̄)(y - ȳ)
private $SumYY = 0; // Σ(y - ȳ)²
// --- 模型參數 ---
private $Slope = 0; // 斜率 β₁
private $YInt = 0; // 截距 β₀
// --- 殘差分析 ---
private $PredictedY = []; // 預測值 ŷ
private $Error = []; // 殘差 e = y - ŷ
private $SquaredError = []; // 殘差平方
private $SumSquaredError = 0; // SSE
private $ErrorVariance = 0; // MSE
private $StdErr = 0; // 殘差標準誤
// --- 推論統計 ---
private $SlopeStdErr = 0;
private $SlopeTVal = 0;
private $SlopeProb = 0; // 斜率 P 值
private $YIntStdErr = 0;
private $YIntTVal = 0;
private $YIntProb = 0;
private $Alpha = 0.025; // 95% 信賴水準 α/2
private $AlphaTVal = 0; // t 分布臨界值
private $ConfIntOfSlope = []; // 斜率信賴區間
// --- 模型優度 ---
private $R = 0; // 相關係數
private $RSquared = 0; // 決定係數 R²
private $DF = 0; // 自由度 n-2
// --- 外部工具路徑 ---
private $RPath = '/usr/local/bin/R'; // 可選:呼叫 R 計算精確 P 值
public function __construct(array $X, array $Y, $confidence = 95) {
// 1. 驗證輸入
if (count($X) !== count($Y)) throw new InvalidArgumentException('X,Y 長度必須相等');
if (($this->n = count($X)) < 2) throw new InvalidArgumentException('樣本數至少 2');
$this->X = $X; $this->Y = $Y;
$this->Alpha = (1 + $confidence/100) / 2; // 0.975
// 2. 計算鏈 (逆向鏈接順序)
$this->calculateMeans();
$this->calculateSumsOfSquares();
$this->calculateCoefficients();
$this->calculatePredictionsAndResiduals();
$this->calculateErrorStatistics();
$this->calculateInferenceStatistics();
$this->calculateConfidenceIntervals();
}
private function calculateMeans() {
$this->XMean = array_sum($this->X) / $this->n;
$this->YMean = array_sum($this->Y) / $this->n;
}
private function calculateSumsOfSquares() {
for ($i=0; $i<$this->n; $i++) {
$dx = $this->X[$i] - $this->XMean;
$dy = $this->Y[$i] - $this->YMean;
$this->SumXX += $dx * $dx;
$this->SumXY += $dx * $dy;
$this->SumYY += $dy * $dy;
}
}
private function calculateCoefficients() {
$this->Slope = $this->SumXY / $this->SumXX;
$this->YInt = $this->YMean - $this->Slope * $this->XMean;
}
private function calculatePredictionsAndResiduals() {
for ($i=0; $i<$this->n; $i++) {
$pred = $this->YInt + $this->Slope * $this->X[$i];
$this->PredictedY[] = $pred;
$err = $this->Y[$i] - $pred;
$this->Error[] = $err;
$this->SquaredError[] = $err * $err;
$this->SumSquaredError += $err * $err;
}
}
private function calculateErrorStatistics() {
$this->DF = $this->n - 2;
$this->ErrorVariance = $this->SumSquaredError / $this->DF; // MSE
$this->StdErr = sqrt($this->ErrorVariance); // 殘差標準誤
$this->SlopeStdErr = $this->StdErr / sqrt($this->SumXX); // 斜率標準誤
}
private function calculateInferenceStatistics() {
// t 統計量
$this->SlopeTVal = $this->Slope / $this->SlopeStdErr;
$this->YIntStdErr = $this->StdErr * sqrt(1/$this->n + $this->XMean*$this->XMean/$this->SumXX);
$this->YIntTVal = $this->YInt / $this->YIntStdErr;
// P 值:雙尾 t 檢定
// 純 PHP 近似:使用不完全 Beta 函數或查表;生產建議呼叫 R/stats_t_dist
$this->SlopeProb = $this->studentTProb(abs($this->SlopeTVal), $this->DF);
$this->YIntProb = $this->studentTProb(abs($this->YIntTVal), $this->DF);
// 相關係數
$this->R = $this->SumXY / sqrt($this->SumXX * $this->SumYY);
$this->RSquared = $this->R * $this->R;
}
private function studentTProb($t, $df) {
// 簡易近似:僅示意,生產必須用精確算法或外部庫
if ($df <= 0) return 1;
// 此處應實現正則化不完全 Beta 函數 I_x(a,b)
// 參考:https://en.wikipedia.org/wiki/Student%27s_t-distribution#Cumulative_distribution_function
return 0.05; // 佔位
}
private function calculateConfidenceIntervals() {
// 獲取 t 臨界值 (雙尾 α/2)
// 生產環境應從 t 分布表查詢或使用 stats_t_quantile()
$this->AlphaTVal = 2.0; // 佔位,實際隨 DF 變化
$margin = $this->AlphaTVal * $this->SlopeStdErr;
$this->ConfIntOfSlope = [$this->Slope - $margin, $this->Slope + $margin];
}
// --- 公共 Getter ---
public function getSlope() { return $this->Slope; }
public function getIntercept() { return $this->YInt; }
public function getRSquared() { return $this->RSquared; }
public function getSlopePValue() { return $this->SlopeProb; }
public function getConfidenceIntervalSlope() { return $this->ConfIntOfSlope; }
public function getPredictedY() { return $this->PredictedY; }
public function getResiduals() { return $this->Error; }
public function getSummary() {
return [
'equation' => sprintf('y = %.4f + %.4fx', $this->YInt, $this->Slope),
'r_squared' => $this->RSquared,
'slope_p_value' => $this->SlopeProb,
'slope_ci_95' => $this->ConfIntOfSlope,
'std_error' => $this->StdErr,
'n' => $this->n,
];
}
}
<?php
require 'SimpleLinearRegression.php';
// 範例資料:房屋面積(坪) vs 價格(萬)
$X = [10, 15, 20, 25, 30, 35, 40, 45, 50];
$Y = [320, 450, 580, 720, 850, 980, 1150, 1300, 1450];
$model = new SimpleLinearRegression($X, $Y, 95);
$summary = $model->getSummary();
echo "迴歸方程式: {$summary['equation']}\n";
echo "R² = {$summary['r_squared']}\n";
echo "斜率 P值: {$summary['slope_p_value']}\n";
echo "斜率 95% CI: [" . implode(', ', $summary['slope_ci_95']) . "]\n";
echo "殘差標準誤: {$summary['std_error']}\n";
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| PHP 純實現 (本文) | 零依賴、教學價值、輕量部署 | 精度有限、大數據慢、缺乏進階模型 | 教學、極簡專案、嵌入式 |
| 呼叫 R (exec/Rserve) | 統計功能最完整、學術標準 | 部署複雜、進程開銷大、安全風險 | 報表系統、專業分析 |
| Python 微服務 (FastAPI + scikit-learn/statsmodels) | 生態豐富、效能好、API 化 | 需維護額外服務 | 現代架構首選 |
| PHP FFI 綁定 C 庫 (GSL/BLAS) | 高效能、原生調用 | PHP 7.4+、編譯複雜、平台相關 | 高效能計算密集型 |