执行PHP-ML最小二乘法回归时遇非数值错误,请求排查
错误原因与修复方案
1. 触发警告的直接原因:预测样本传入非数值类型
代码中$newSample = [date('yyyy-mm-dd'), 1];存在错误:
- PHP的
date()函数没有yyyy格式参数,正确的四位年份格式是Y,因此date('yyyy-mm-dd')会直接返回字符串yyyy-mm-dd,而非预期的日期字符串,更不是数值类型的时间戳。 - 当这个非数值的字符串传入
LeastSquares::predict()时,模型内部进行数值计算就会触发non-numeric value encountered警告。
修复:
将$newSample的生成代码改为:
// 生成当前日期的时间戳,保证是数值类型 $currentTimestamp = strtotime(date('Y-m-d')); $newSample = [$currentTimestamp, 1];
2. 模型评估逻辑错误:用分类指标评估回归任务
Accuracy是分类任务的评估指标,用于判断预测类别与真实类别的匹配度,完全不适用于回归任务的连续数值预测,这就是为什么运行结果中Accuracy: 0的原因。
修复:
替换为回归任务专用的评估指标,比如PhpML提供的MeanSquaredError:
use Phpml\Metric\MeanSquaredError; // ... 其他代码 ... // 替换原有的Accuracy评估逻辑 $metric = new MeanSquaredError(); $mse = $metric->score($testingLabels, $predictions); // 可同时计算MAE(平均绝对误差)辅助评估 use Phpml\Metric\MeanAbsoluteError; $maeMetric = new MeanAbsoluteError(); $mae = $maeMetric->score($testingLabels, $predictions);
3. 数值精度问题:时间戳过大导致系数被稀释
运行结果中Confidence: 1.1612428352237E-8(极小值)是因为时间戳数值过大(通常是10位以上的整数),在最小二乘法计算时,特征值的数量级会导致回归系数被稀释,影响模型的可解释性。
优化方案:
将时间戳转换为相对天数,比如以数据集的第一个日期为基准日,后续日期转换为相对基准日的天数,缩小特征数值的数量级:
// 在处理samples时,先获取基准时间戳 $baseTimestamp = strtotime($data['samples'][0][0]); $samples = array_map(function($sample) use ($baseTimestamp) { if (!is_array($sample) || count($sample) != 2) { throw new InvalidArgumentException('Each sample in the "samples" array must be an array with 2 values'); } $timestamp = strtotime($sample[0]); if ($timestamp === false) { throw new InvalidArgumentException('Invalid timestamp: ' . $sample[0] . '. Timestamp should be in the format yyyy-mm-dd'); } // 计算相对天数 $relativeDays = floor(($timestamp - $baseTimestamp) / (60*60*24)); return [$relativeDays, $sample[1]]; }, $data['samples']); // 生成新样本时也用相对天数 $currentTimestamp = strtotime(date('Y-m-d')); $relativeDays = floor(($currentTimestamp - $baseTimestamp) / (60*60*24)); $newSample = [$relativeDays, 1];
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

