zoukankan      html  css  js  c++  java
  • [Algorithms] Classify Mystery Items with the K-Nearest Neighbors Algorithm in JavaScript

    The k-nearest neighbors algorithm is used for classification of unknown items and involves calculating the distance of the unknown item's neighbors. We'll use Euclidean distance to determine the closest neighbor and make our best guess on what the mystery fruit is.

    Just a Euclidean distance, that's all...

    function determineFruit({ size, redness }) {
      const fruit = [
        { name: "grape", size: 1, redness: 0 },
        { name: "orange", size: 2, redness: 1 },
        { name: "grapefruit", size: 3, redness: 2 }
      ];
    
      const { name } = fruit.reduce(
        (prev, cur) => {
          let curCalc = calcDistance([[size, cur.size], [redness, cur.redness]]);
          console.log(curCalc);
          return prev.dist < curCalc ? prev : { name: cur.name, dist: curCalc };
        },
        {
          name: fruit[0].name,
          dist: calcDistance([[size, fruit[0].size], [redness, fruit[0].redness]])
        }
      );
      return `This is most likely a ${name}`;
    }
    
    function calcDistance(data) {
      return Math.sqrt(
        data.reduce((acc, curr) => console.log(curr) && acc + Math.pow(curr[0] - curr[1], 2), 0)
      );
    }
    
    console.log(determineFruit({ size: 2, redness: 2 }));
    
  • 相关阅读:
    swift NSComparator
    Java mac 上编写Java代码
    四舍五入、上取整、下取整
    数组排序
    删除xcode 里的多余证书
    启动画面 设置
    CGFloat Float 互转
    navigationController pop的几种方法
    iOS 获取键盘相关信息
    eclipse代码格式化
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10192558.html
Copyright © 2011-2022 走看看