使用 javascript 实现最小二乘算法,要有可视化界面
时间: 2023-06-11 14:10:13 浏览: 161
最小二乘算法设计实现
4星 · 用户满意度95%
最小二乘算法是一种用于拟合数据的方法,可以通过最小化误差平方和来找到最佳拟合曲线。
以下是一个使用 JavaScript 和 D3.js 库实现最小二乘算法的示例代码,包含了可视化界面:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Least Squares Regression</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
.chart {
width: 100%;
height: 500px;
margin: 0 auto;
position: relative;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
.point {
fill: blue;
stroke: blue;
stroke-width: 2px;
cursor: pointer;
}
.line {
fill: none;
stroke: red;
stroke-width: 2px;
}
</style>
</head>
<body>
<h1>Least Squares Regression</h1>
<div class="chart"></div>
<script>
// 数据
var data = [
{ x: 1, y: 2 },
{ x: 2, y: 4 },
{ x: 3, y: 5 },
{ x: 4, y: 7 },
{ x: 5, y: 8 },
{ x: 6, y: 10 }
];
// 创建 SVG 元素
var svg = d3.select(".chart")
.append("svg")
.attr("width", "100%")
.attr("height", "100%");
// 设置坐标轴范围和比例尺
var xScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.x)])
.range([50, 550]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.y)])
.range([450, 50]);
// 创建 x 轴和 y 轴
var xAxis = d3.axisBottom(xScale);
var yAxis = d3.axisLeft(yScale);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0, 450)")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(50, 0)")
.call(yAxis);
// 创建点
var points = svg.selectAll(".point")
.data(data)
.enter()
.append("circle")
.attr("class", "point")
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("r", 5);
// 计算最小二乘法拟合线的参数
var n = data.length;
var xSum = d3.sum(data, d => d.x);
var ySum = d3.sum(data, d => d.y);
var xySum = d3.sum(data, d => d.x * d.y);
var xSquareSum = d3.sum(data, d => d.x * d.x);
var slope = (n * xySum - xSum * ySum) / (n * xSquareSum - xSum * xSum);
var intercept = (ySum - slope * xSum) / n;
// 创建最小二乘法拟合线
var lineData = [
{ x: 1, y: slope * 1 + intercept },
{ x: 6, y: slope * 6 + intercept }
];
var line = d3.line()
.x(d => xScale(d.x))
.y(d => yScale(d.y));
svg.append("path")
.datum(lineData)
.attr("class", "line")
.attr("d", line);
// 更新点的颜色
points.each(function(d) {
if (d.y > slope * d.x + intercept) {
d3.select(this).attr("fill", "green").attr("stroke", "green");
}
});
</script>
</body>
</html>
```
这段代码会生成一个包含点和最小二乘法拟合线的散点图,并将点按照它们是否在拟合线上方着色为蓝色或绿色。可以将数据替换为自己的数据并运行代码。
阅读全文