Result Size: 300 x 150
x
 
<!DOCTYPE html>
<html>
<script src="../scripts/myplotlib.js"></script>
<body>
<canvas id="myCanvas" width="400px" height="400px" style="width:100%;max-width:400px;border:1px solid black"></canvas>
<script>
// Ініціалізація значень
const numPoints = 500;
const learningRate = 0.00001;
// Створити плотер
const plotter = new XYPlotter("myCanvas");
plotter.transformXY();
const xMax = plotter.xMax;
const yMax = plotter.yMax;
const xMin = plotter.xMin;
const yMin = plotter.yMin;
// Створити рандомні XY точки
const xPoints = [];
const yPoints = [];
for (let i = 0; i < numPoints; i++) {
  xPoints[i] = Math.random() * xMax;
  yPoints[i] = Math.random() * yMax;
}
// Лінійна функція
function f(x) {
  return x * 1.2 + 50;
}
// Накреслити лінію
plotter.plotLine(xMin, f(xMin), xMax, f(xMax), "black");
// Обчислити бажані відповіді
const desired = [];
for (let i = 0; i < numPoints; i++) {
  desired[i] = 0;
  if (yPoints[i] > f(xPoints[i])) {desired[i] = 1}
}
// Створити перцептрон
const ptron = new Perceptron(2, learningRate);
// Тренувати перцептрон
for (let j = 0; j <= 10000; j++) {
  for (let i = 0; i < numPoints; i++) {
    ptron.train([xPoints[i], yPoints[i]], desired[i]);
  }
}
// Показати результат
for (let i = 0; i < numPoints; i++) {
  const x = xPoints[i];
  const y = yPoints[i];
  let guess = ptron.activate([x, y, ptron.bias]);
  let color = "black";
  if (guess == 0) color = "blue";
  plotter.plotPoint(x, y, color);
}
// Об’єкт Perceptron ---------------------
function Perceptron(no, learningRate = 0.00001) {
// Встановити початкові значення
this.learnc = learningRate;
this.bias = 1;
// Обчислити випадкові ваги
this.weights = [];
for (let i = 0; i <= no; i++) {
  this.weights[i] = Math.random() * 2 - 1;
}
// Активувати функцію
this.activate = function(inputs) {
  let sum = 0;
  for (let i = 0; i < inputs.length; i++) {
    sum += inputs[i] * this.weights[i];
  }
  if (sum > 0) {return 1} else {return 0}
}
// Тренувати функцію
this.train = function(inputs, desired) {
  inputs.push(this.bias);
  let guess = this.activate(inputs);
  let error = desired - guess;
  if (error != 0) {
    for (let i = 0; i < inputs.length; i++) {
      this.weights[i] += this.learnc * error * inputs[i];
    }
  }
}
// Кінець об’єкта Perceptron
}
</script>
</body>
</html>