k = $k; $this->weighted = $weighted; $this->tree = $tree ?? new KDTree(); } /** * Return the estimator type. * * @internal * * @return EstimatorType */ public function type() : EstimatorType { return EstimatorType::regressor(); } /** * Return the data types that the estimator is compatible with. * * @internal * * @return list<\Rubix\ML\DataType> */ public function compatibility() : array { return $this->tree->kernel()->compatibility(); } /** * Return the settings of the hyper-parameters in an associative array. * * @internal * * @return mixed[] */ public function params() : array { return [ 'k' => $this->k, 'weighted' => $this->weighted, 'tree' => $this->tree, ]; } /** * Has the learner been trained? * * @return bool */ public function trained() : bool { return !$this->tree->bare(); } /** * Return the base k-d tree instance. * * @return Spatial */ public function tree() : Spatial { return $this->tree; } /** * @param \Rubix\ML\Datasets\Labeled $dataset */ public function train(Dataset $dataset) : void { SpecificationChain::with([ new DatasetIsLabeled($dataset), new DatasetIsNotEmpty($dataset), new SamplesAreCompatibleWithEstimator($dataset, $this), new LabelsAreCompatibleWithLearner($dataset, $this), ])->check(); $this->featureCount = $dataset->numFeatures(); $this->tree->grow($dataset); } /** * Make a prediction based on the nearest neighbors. * * @param Dataset $dataset * @throws RuntimeException * @return list */ public function predict(Dataset $dataset) : array { if ($this->tree->bare() or !$this->featureCount) { throw new RuntimeException('Estimator has not been trained.'); } DatasetHasDimensionality::with($dataset, $this->featureCount)->check(); return array_map([$this, 'predictSample'], $dataset->samples()); } /** * Predict a single sample and return the result. * * @internal * * @param list $sample * @return int|float */ public function predictSample(array $sample) { [$samples, $labels, $distances] = $this->tree->nearest($sample, $this->k); if ($this->weighted) { $weights = []; foreach ($distances as $distance) { $weights[] = 1.0 / (1.0 + $distance); } return Stats::weightedMean($labels, $weights); } return Stats::mean($labels); } /** * Return the string representation of the object. * * @internal * * @return string */ public function __toString() : string { return 'K-d Neighbors Regressor (' . Params::stringify($this->params()) . ')'; } }