纯js实现线性回归模型

代码语言:html

所属分类:布局界面

代码描述:纯js实现线性回归模型

代码标签: 线性 回归 模型

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

<style>
body {
  width: 100%;
  height: 100%;
  margin: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #333333;
  font-family: Yu Gothic,sans-serif;
}

canvas {
  box-shadow: 8px 8px 16px black;
}

#title {
  position: absolute;
  top: 0;
}

#coordinateInfo {
  width: 80vh;
  position: absolute;
  bottom: -10px;
}

#modelInfo {
  position: absolute;
  width: 20vw;
  height: 40vh;
  top: 30vh;
  left: calc(53vw + 35vh);
  font-size: 1.2em;
}
</style>

</head>
<body translate="no">
<h3 id="title">Click to start plotting</h3>
<p id="coordinateInfo"></p>
<p id="modelInfo"></p>

<script>
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let cInfo, mInfo, title;

class LinReg {
  
  constructor() {
    this.w      = 0;
    this.b      = 0;
    this.meanX  = 0;
    this.meanY  = 0;
    this.points = []
  }
  
  addPoint( x, y ) {
    this.points.push({ x, y })
  }
  
  train() {
    let xSum = this.points.reduce( (t, p) => (t + p.x), 0 );
    let ySum = this.points.reduce( (t, p) => (t + p.y), 0 );
    this.meanX = xSum / this.points.length;
    this.meanY = ySum / this.points.length;
    
    let numerator = 0;
    let denominator = 0;
    
    this.points.forEach(({ x, y }) => {
      numerator += (x - this.meanX) * (y - this.meanY);
      denominator += (x - this.meanX) ** 2;
    });
    
    this.b = numerator / denominator;
    this.w = this.meanY - (this.b * this.meanX);
  }
  
  run( X ) {
    return ( this.b * X ) + this.w;
  }
  
}

const model = new LinReg();

function onMouseMove({ clientX, clientY }) {
  let rect = canvas.getBoundingClientRect();
  let x = Math.floor(clientX - rect.left);
  let y = Math.floor(canvas.height - (clientY - rect.top));
  cInfo.innerHTML = `x = ${x}, y = ${y}`;
}

function onClick({ clientX, clientY }) {
  title.remove();
  let rect = canvas.getBoundingClientRect();
  // Because the Y axis star.........完整代码请登录后点击上方下载按钮下载查看

网友评论0