You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让PHP LeastSquares回归与Excel REGLINW函数结果一致?

问题

我希望在PHP代码中用Excel的REGLINW函数逻辑做外推计算,尝试用php-ml库的LeastSquares函数,但因为Excel的REGLINW会处理日期维度,导致计算结果不一致,怎么实现和该Excel函数完全一致的结果?

我当前的代码:

$x[] = [$extrapolatedPeriod];
$y[] = [$extrapolatedData['billable_connections'] ?? 0];

$regression = new LeastSquares();
$regression->train($x, $y);

$extrapolatedResults[$extrapolatedPeriod] = intval($regression->predict([$numbersOfPeriod]));
解决方案

要和Excel的REGLINW结果对齐,关键要统一日期的数值转换规则和回归训练的数据格式,具体操作如下:

1. 将PHP日期转换为Excel日期序列号

Excel把日期存储为「序列号」:以1900年1月1日为起始点(值为1),每过一天数值加1。PHP里需要把日期转成对应的序列号,而不是用时间戳或其他格式,这是结果差异的核心原因。

可以用这个函数实现转换:

function dateToExcelSerial(string $date): float
{
    $excelEpoch = new DateTime('1899-12-30'); // 兼容Excel 1900年闰年bug的基准日期
    $targetDate = new DateTime($date);
    $interval = $excelEpoch->diff($targetDate);
    
    $days = $interval->days;
    $hours = $interval->h / 24;
    $minutes = $interval->i / (24 * 60);
    $seconds = $interval->s / (24 * 60 * 60);
    
    return $days + $hours + $minutes + $seconds;
}

2. 修正训练数据的格式

php-ml的LeastSquares::train()要求:

  • 第一个参数$samples是二维数组,每个元素是单个样本的特征数组(这里就是日期序列号)
  • 第二个参数$targets是一维数组,对应每个样本的目标值(这里是billable_connections)

你原来的代码里$y是二维数组,这会导致训练逻辑错误,需要调整。

3. 修正后的完整代码

// 预处理所有数据:日期转Excel序列号,整理成训练格式
$samples = [];
$targets = [];
foreach ($extrapolatedDataList as $data) {
    $excelDate = dateToExcelSerial($data['period']);
    $samples[] = [$excelDate];
    $targets[] = $data['billable_connections'] ?? 0;
}

// 训练线性回归模型
$regression = new \Phpml\Regression\LeastSquares();
$regression->train($samples, $targets);

// 预测时,目标日期也要转成Excel序列号
$targetPeriodSerial = dateToExcelSerial($numbersOfPeriod);
$extrapolatedResults[$numbersOfPeriod] = intval($regression->predict([$targetPeriodSerial]));

4. 额外验证点

  • Excel的REGLINW默认会计算截距(对应LINEST的const参数为TRUE),php-ml的LeastSquares默认也是计算截距的,无需额外调整;如果你的Excel公式里强制截距为0,需要在php-ml里调用$regression->setForceIntercept(true);
  • 确保所有日期都使用统一时区,避免转换偏差

内容的提问来源于stack exchange,提问作者Dariusz Rup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 01:37:24