js 最小二乘法代码实现
时间: 2024-12-19 10:12:26 浏览: 6
最小二乘法在JavaScript中主要用于拟合线性模型,找到一组数据点的最佳直线拟合。下面是一个简单的线性回归(一次方程)最小二乘法实现示例:
```javascript
function linearRegression(x, y) {
// 计算均值
const meanX = x.reduce((a, b) => a + b, 0) / x.length;
const meanY = y.reduce((a, b) => a + b, 0) / y.length;
// 计算斜率和截距
let slope = 0, intercept = 0;
const numerator = x.map(xi => (xi - meanX) * (y[i] - meanY)).reduce((sum, val) => sum + val, 0);
const denominator = x.map(xi => Math.pow(xi - meanX, 2)).reduce((sum, val) => sum + val, 0);
if (denominator !== 0) {
slope = numerator / denominator;
intercept = meanY - slope * meanX;
}
return { slope, intercept };
}
// 使用示例
const data = [[1, 1], [2, 3], [3, 5], [4, 7]];
const [slope, intercept] = linearRegression(data.map(([x]) => x), data.map(([y]) => y));
console.log(`Slope: ${slope}, Intercept: ${intercept}`);
```
这个函数接受输入的一组二维数组(每个元素表示一个数据点,包含x坐标和y坐标),然后计算出最佳的斜率和截距,即最小化所有数据点到直线距离平方的总和。
阅读全文