k = $k; $this->samples = []; $this->targets = []; $this->distanceMetric = $distanceMetric; } /** * @param array $sample * * @return mixed */ protected function predictSample(array $sample) { $distances = $this->kNeighborsDistances($sample); $predictions = array_combine(array_values($this->targets), array_fill(0, count($this->targets), 0)); foreach ($distances as $index => $distance) { ++$predictions[$this->targets[$index]]; } arsort($predictions); reset($predictions); return key($predictions); } /** * @param array $sample * * @return array * * @throws \Phpml\Exception\InvalidArgumentException */ private function kNeighborsDistances(array $sample): array { $distances = []; foreach ($this->samples as $index => $neighbor) { $distances[$index] = $this->distanceMetric->distance($sample, $neighbor); } asort($distances); return array_slice($distances, 0, $this->k, true); } }