使用js实现最小二乘算法,要有可视化界面,使用html封装完整代码
时间: 2023-06-14 12:02:54 浏览: 166
最小二乘算法设计实现
4星 · 用户满意度95%
以下是一个使用JavaScript实现最小二乘算法并带有可视化界面的代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>最小二乘法可视化</title>
<meta charset="utf-8">
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<h2>最小二乘法可视化</h2>
<p>点击画布添加数据点,拖动数据点更新位置</p>
<canvas id="canvas" width="500" height="500"></canvas>
<div>
<button onclick="reset()">重置</button>
<button onclick="fit()">拟合</button>
</div>
<script>
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let points = [];
// 画布点击事件
canvas.addEventListener('click', function(event) {
let rect = canvas.getBoundingClientRect();
let x = event.clientX - rect.left;
let y = event.clientY - rect.top;
points.push({x: x, y: y});
drawPoints();
});
// 画布拖动事件
canvas.addEventListener('mousedown', function(event) {
let rect = canvas.getBoundingClientRect();
let x = event.clientX - rect.left;
let y = event.clientY - rect.top;
for (let i = 0; i < points.length; i++) {
let p = points[i];
if (Math.abs(x - p.x) < 5 && Math.abs(y - p.y) < 5) {
let startX = p.x, startY = p.y;
canvas.addEventListener('mousemove', function(event) {
let rect = canvas.getBoundingClientRect();
let newX = event.clientX - rect.left;
let newY = event.clientY - rect.top;
p.x = newX;
p.y = newY;
drawPoints();
});
canvas.addEventListener('mouseup', function(event) {
canvas.removeEventListener('mousemove', null);
canvas.removeEventListener('mouseup', null);
drawPoints();
fit();
});
break;
}
}
});
// 重置按钮事件
function reset() {
points = [];
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
// 拟合按钮事件
function fit() {
if (points.length < 2) {
alert('需要至少两个数据点');
return;
}
let xSum = 0, ySum = 0, xySum = 0, x2Sum = 0;
for (let i = 0; i < points.length; i++) {
let p = points[i];
xSum += p.x;
ySum += p.y;
xySum += p.x * p.y;
x2Sum += p.x * p.x;
}
let n = points.length;
let a = (n * xySum - xSum * ySum) / (n * x2Sum - xSum * xSum);
let b = (ySum - a * xSum) / n;
drawLine(a, b);
}
// 画数据点
function drawPoints() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < points.length; i++) {
let p = points[i];
ctx.beginPath();
ctx.arc(p.x, p.y, 5, 0, Math.PI * 2);
ctx.fill();
}
}
// 画拟合线
function drawLine(a, b) {
let x1 = 0, y1 = a * x1 + b;
let x2 = canvas.width, y2 = a * x2 + b;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
</script>
</body>
</html>
```
在页面上,你可以点击鼠标来添加数据点,也可以拖动数据点来更新位置。点击“拟合”按钮会进行最小二乘拟合,并在画布上画出拟合直线。点击“重置”按钮会清除所有数据点和拟合直线。注意,这个可视化界面只是为了演示最小二乘算法的过程,实际应用中可能需要更复杂的界面和交互方式。
阅读全文