如何用PHP實作K近鄰演算法
K近鄰演算法是一種簡單且常用的機器學習演算法,廣泛應用於分類與迴歸問題。它的基本原理是透過計算待分類樣本與已知樣本之間的距離,將待分類樣本歸類為距離最近的K個已知樣本所屬的類別。在本文中,我們將介紹如何用PHP實作K近鄰演算法,並提供程式碼範例。
已知樣本資料:
$knownSamples = array(
array('class' => 'A', 'features' => array(2, 3)), array('class' => 'A', 'features' => array(4, 5)), array('class' => 'B', 'features' => array(1, 1)), array('class' => 'B', 'features' => array(3, 2)),
);
待分類樣本資料:
$unknownSample = array('features' => array(2, 2));
function euclideanDistance($sample1, $sample2) {
$sum = 0; for ($i = 0; $i < count($sample1); $i++) { $sum += pow($sample1[$i] - $sample2[$i], 2); } return sqrt($sum);
}
function findNeighbors($knownSamples, $unknownSample, $k) {
$distances = array(); foreach ($knownSamples as $knownSample) { $distance = euclideanDistance($knownSample['features'], $unknownSample['features']); $distances[] = array('class' => $knownSample['class'], 'distance' => $distance); } usort($distances, function ($a, $b) { return $a['distance'] - $b['distance']; }); return array_slice($distances, 0, $k);
}
function classify($neighbors) {
$classes = array(); foreach ($neighbors as $neighbor) { $classes[] = $neighbor['class']; } $classCounts = array_count_values($classes); arsort($classCounts); return key($classCounts);
}
function euclideanDistance($sample1, $sample2) { $sum = 0; for ($i = 0; $i < count($sample1); $i++) { $sum += pow($sample1[$i] - $sample2[$i], 2); } return sqrt($sum); } function findNeighbors($knownSamples, $unknownSample, $k) { $distances = array(); foreach ($knownSamples as $knownSample) { $distance = euclideanDistance($knownSample['features'], $unknownSample['features']); $distances[] = array('class' => $knownSample['class'], 'distance' => $distance); } usort($distances, function ($a, $b) { return $a['distance'] - $b['distance']; }); return array_slice($distances, 0, $k); } function classify($neighbors) { $classes = array(); foreach ($neighbors as $neighbor) { $classes[] = $neighbor['class']; } $classCounts = array_count_values($classes); arsort($classCounts); return key($classCounts); } $knownSamples = array( array('class' => 'A', 'features' => array(2, 3)), array('class' => 'A', 'features' => array(4, 5)), array('class' => 'B', 'features' => array(1, 1)), array('class' => 'B', 'features' => array(3, 2)), ); $unknownSample = array('features' => array(2, 2)); $neighbors = findNeighbors($knownSamples, $unknownSample, 3); $class = classify($neighbors); echo "待分类样本的类别为:" . $class;
本文介紹如何用PHP實作K近鄰演算法。透過計算待分類樣本與已知樣本之間的距離,找到K個最近鄰居,然後根據這些最近鄰居的類別進行分類。 K近鄰演算法是一種簡單且常用的演算法,適用於許多分類和迴歸問題。使用PHP實作K近鄰演算法相對簡單,只需寫幾個函數即可完成。希望本文能幫助讀者理解並應用K近鄰演算法。
以上是如何用PHP實作K近鄰演算法的詳細內容。更多資訊請關注PHP中文網其他相關文章!