萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 實現簡單線性回歸:數學庫缺失下的自建統計模型實戰

背景:PHP 缺乏成熟數學庫的現狀

相比 Perl (PDL)、Python (NumPy/SciPy/StatsModels)、R、Julia,PHP 社群長期缺乏標準化、高效能的數學統計庫。原因包括:

  • Web 開發多為商業邏輯,非科學計算。
  • 既有成熟工具 (R、Python) 可透過 exec()/API 呼叫。
  • PHP 型別系統、記憶體模型不利大規模數值計算。

但出於教學、輕量部署、避免外部依賴,純 PHP 實現基礎統計模型仍有價值。

設計原則:構建可維護的統計類別

  1. 單一模型一個類:SimpleLinearRegression、MultipleRegression、ANOVA 各自封裝。
  2. 逆向鏈接設計:從期望輸出 (係數、R²、P值、信賴區間) 反推所需中間量 (均值、協方差、殘差平方和)。
  3. 大量 Getter:每個中間/匯總統計量對應一個 getXxx() 方法,便於外部存取與單元測試。
  4. 儲存中間結果:實例屬性保存計算結果,避免重複計算,支援鏈式依賴。
  5. 語義化命名:getSumSquaredError() 而非 getSSE(),降低認知負荷。
  6. 務實不求完美:優先正確性與可讀性,非極致效能;大規模計算應外包給專用引擎。

SimpleLinearRegression 類別核心實作 (節錄)

<?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 中實現線性回歸,核心在於「逆向鏈接設計統計量計算鏈」與「中間結果緩存」。雖 PHP 非數值計算主戰場,但理解統計模型內部運作,能讓你在呼叫外部專業工具時,更懂參數含義、更能驗證結果合理性。

copyright © 萬盛學電腦網 all rights reserved
方案優點缺點適用場景
PHP 純實現 (本文)零依賴、教學價值、輕量部署精度有限、大數據慢、缺乏進階模型教學、極簡專案、嵌入式
呼叫 R (exec/Rserve)統計功能最完整、學術標準部署複雜、進程開銷大、安全風險報表系統、專業分析
Python 微服務 (FastAPI + scikit-learn/statsmodels)生態豐富、效能好、API 化需維護額外服務現代架構首選
PHP FFI 綁定 C 庫 (GSL/BLAS)高效能、原生調用PHP 7.4+、編譯複雜、平台相關高效能計算密集型