DAY 6
0
AI & Data

## PHP-ML KNearestNeighbors (KNN) 範例實作

KNN的流程可以分成三個部分，資料﹑訓練﹑預測。

## 資料

``````\$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
\$labels = ['a', 'a', 'a', 'b', 'b', 'b'];
``````

## 訓練

``````\$classifier = new KNearestNeighbors(\$k=3, new Minkowski(\$lambda=4));
``````

1. 直線距離：兩個質點p﹑q的最點距離c
2. 曼哈頓距離：為每個維度(x軸﹑y軸)的距離總和(a+b)
3. 切比雪夫距離：為每個維度的最大距離(b)

``````\$classifier->train(\$samples, \$labels);
``````

## 預測

``````\$classifier->predict([3, 2]);
``````

``````<?php
require_once __DIR__ . '/vendor/autoload.php';

use Phpml\Classification\KNearestNeighbors;
use Phpml\Math\Distance\Minkowski;

\$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
\$labels = ['a', 'a', 'a', 'b', 'b', 'b'];

\$classifier = new KNearestNeighbors(\$k=3, new Minkowski(\$lambda=4));
\$classifier->train(\$samples, \$labels);

echo \$classifier->predict([3, 2]);
// return 'b'

echo "<br>";

var_dump(\$classifier->predict([[3, 2], [1, 5]]));
// return ['b', 'a']
?>
``````

(參考來源：PHP ML)