Make predictions from a dataset.

@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException
@throws \RuntimeException
@return array
170842
public function predict(Dataset $dataset) : array
    {
        if (!$this->medians or !$this->mads) {
            throw new RuntimeException('The learner has not'
                . ' been trained.');
        }

        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $p = $dataset->numColumns();

        $predictions = [];

        foreach ($dataset as $sample) {
            $score = 0.;

            foreach ($sample as $column => $feature) {
                $median = $this->medians[$column];
                $mad = $this->mads[$column];

                $z = abs((self::LAMBDA * ($feature - $median)) / $mad);

                if ($z > $this->threshold) {
                    $predictions[] = 1;

                    continue 2;
                }

                $score += $z;
            }

            $predictions[] = ($score / $p) > $this->tolerance ? 1 : 0;
        }

        return $predictions;
    }
1014918
public function seed(Dataset $dataset, int $k) : array
    {
        return $dataset->randomize()->head($k)->samples();
    }
1344603
public static function split(Labeled $dataset) : self
    {
        $columns = $dataset->columns();

        $variances = array_map([Stats::class, 'variance'], $columns);

        $column = argmax($variances);

        $value = Stats::median($columns[$column]);

        $groups = $dataset->partition($column, $value);

        $min = $max = [];

        foreach ($columns as $values) {
            $min[] = min($values);
            $max[] = max($values);
        }

        return new self($column, $value, $groups, $min, $max);
    }
1217596
public function rank(Dataset $dataset) : array
    {
        if (!$this->r or !$this->histograms) {
            throw new RuntimeException('The learner has not'
                . ' been trained.');
        }

        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $z = Matrix::quick($dataset->samples())
            ->matmul($this->r)
            ->transpose();

        return $this->logLikelihood($z);
    }
1157145
public function train(Dataset $dataset) : void
    {
        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $n = $dataset->numRows();
        
        $maxDepth = (int) ceil(log(max($n, 2), 2));

        $p = (int) round($this->ratio * $n);

        $this->forest = [];

        for ($epoch = 1; $epoch <= $this->estimators; $epoch++) {
            $tree = new ITree($maxDepth);

            $subset = $dataset->randomize()->head($p);

            $tree->grow($subset);

            $this->forest[] = $tree;
        }

        $this->pHat = $this->c($p);

        $scores = $this->rank($dataset);

        $p = 100. - (100. * $this->contamination);

        $shift = Stats::percentile($scores, $p);

        $this->offset = $shift;
    }
253570
protected function processDataSet(DataSet $dataSet)
    {
        if ($dataSet->getPattern() === File::HEADER_PATTERN) {
            $this->processHeader($dataSet);
        } else {
            $this->processBrowserData($dataSet);
        }
    }
1137591
public function seed(Dataset $dataset, int $k) : array
    {
        $centroids = $dataset->randomSubsetWithReplacement(1)->samples();

        for ($i = 1; $i < $k; $i++) {
            $weights = [];

            foreach ($dataset as $sample) {
                $closest = INF;

                foreach ($centroids as $centroid) {
                    $distance = $this->kernel->compute($sample, $centroid);

                    if ($distance < $closest) {
                        $closest = $distance;
                    }
                }

                $weights[] = $closest ** 2;
            }

            $subset = $dataset->randomWeightedSubsetWithReplacement(1, $weights);

            $centroids[] = $subset[0];
        }

        return $centroids;
    }
521517
public function train(Dataset $dataset) : void
    {
        if (!$dataset instanceof Labeled) {
            throw new InvalidArgumentException('This Estimator requires a'
                . ' Labeled training set.');
        }

        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $classes = $dataset->possibleOutcomes();

        $this->classes = $classes;
        $this->weights = array_fill_keys($classes, 0);

        $this->means = $this->variances = array_fill_keys($classes, []);

        foreach ($dataset->stratify() as $class => $stratum) {
            $means = $variances = [];

            foreach ($stratum->columns() as $values) {
                [$mean, $variance] = Stats::meanVar($values);

                $means[] = $mean;
                $variances[] = $variance ?: EPSILON;
            }

            $this->means[$class] = $means;
            $this->variances[$class] = $variances;

            $this->weights[$class] += $stratum->numRows();
        }

        if ($this->fitPriors) {
            $this->priors = [];

            $total = array_sum($this->weights) ?: EPSILON;

            foreach ($this->weights as $class => $weight) {
                $this->priors[$class] = log($weight / $total);
            }
        }
    }
1366403
public function partial(Dataset $dataset) : void
    {
        if (empty($this->weights) or empty($this->means) or empty($this->variances)) {
            $this->train($dataset);

            return;
        }

        if (!$dataset instanceof Labeled) {
            throw new InvalidArgumentException('This Estimator requires a'
                . ' Labeled training set.');
        }

        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        foreach ($dataset->stratify() as $class => $stratum) {
            $means = $this->means[$class];
            $variances = $this->variances[$class];

            $oldWeight = $this->weights[$class];
            $oldMeans = $this->means[$class];
            $oldVariances = $this->variances[$class];

            $n = $stratum->numRows();

            foreach ($stratum->columns() as $column => $values) {
                [$mean, $variance] = Stats::meanVar($values);

                $means[$column] = (($n * $mean)
                    + ($oldWeight * $oldMeans[$column]))
                    / ($oldWeight + $n);

                $vHat = ($oldWeight
                    * $oldVariances[$column] + ($n * $variance)
                    + ($oldWeight / ($n * ($oldWeight + $n)))
                    * ($n * $oldMeans[$column] - $n * $mean) ** 2)
                    / ($oldWeight + $n);

                $variances[$column] = $vHat ?: EPSILON;
            }

            $this->means[$class] = $means;
            $this->variances[$class] = $variances;
            
            $this->weights[$class] += $n;
        }

        if ($this->fitPriors) {
            $total = array_sum($this->weights) ?: EPSILON;

            foreach ($this->weights as $class => $weight) {
                $this->priors[$class] = log($weight / $total);
            }
        }
    }
778881
protected function getDatasets($dataset = false)
    {
        $source_packages = config('datasets.source', []);

        $result = [];

        foreach ($source_packages as $folder) {

            // Get folder contents of datasets
            $datasets = new Filesystem(new Adapter(base_path('vendor/'.$folder.'/datasets/')));

            try {
                $files = $datasets->listContents();
            } catch (\Exception $exception) {
            }

            foreach ($files as $file) {
                $result[$file['filename']] = base_path('vendor/'.$folder.'/datasets/'.$file['basename']);
            }
        }

        if ($dataset !== false) {
            if (!isset($result[$dataset])) {
                $this->error(sprintf("Requested dataset '%s' could not be found.", $dataset));

                exit(1);
            }

            // Supplied dataset config file does not exist.
            if (!file_exists($result[$dataset])) {
                $this->error(sprintf('\'%s\' dataset does not exist.', $this->argument('dataset')));
                $this->line('');

                exit(1);
            }

            return $result[$dataset];
        }

        return $result;
    }
135859
public function bind($dataset)
    {
        if ($dataset === null) {
            return $this;
        }

        if ($dataset instanceof \Traversable) {
            $dataset = iterator_to_array($dataset);
        } elseif (is_object($dataset)) {
            $dataset = [$dataset];
        } elseif (!is_array($dataset)) {
            throw new \InvalidArgumentException('Need an array or object');
        }

        foreach ($dataset as $k => $data) {
            $this[$k] = $data;
        }

        return $this;
    }
583652
public function partial(Dataset $dataset) : void
    {
        if (!$dataset instanceof Labeled) {
            throw new InvalidArgumentException('This estimator requires a'
                . ' labeled training set.');
        }

        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $this->classes = array_unique(array_merge($this->classes, $dataset->possibleOutcomes()));
        $this->samples = array_merge($this->samples, $dataset->samples());
        $this->labels = array_merge($this->labels, $dataset->labels());
    }
40553
public function train(Dataset $dataset) : void
    {
        if (!$dataset instanceof Labeled) {
            throw new InvalidArgumentException('This estimator requires a'
                . ' labeled training set.');
        }

        $this->network = new FeedForward(
            new Placeholder1D($dataset->numColumns()),
            [],
            new Continuous($this->alpha, $this->costFn),
            $this->optimizer
        );

        $this->steps = [];

        $this->partial($dataset);
    }
977529
public function prepend(Dataset $dataset) : self
    {
        if (!$dataset instanceof Labeled) {
            throw new InvalidArgumentException('Can only merge with a labeled'
                . 'dataset.');
        }

        $samples = array_merge($dataset->samples(), $this->samples);
        $labels = array_merge($dataset->labels(), $this->labels);

        return self::quick($samples, $labels);
    }
736016
public function predict(Dataset $dataset) : array
    {
        if (empty($this->ensemble)) {
            throw new RuntimeException('Estimator has not been trained.');
        }

        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $predictions = $this->base->predict($dataset);

        foreach ($this->ensemble as $estimator) {
            foreach ($estimator->predict($dataset) as $j => $prediction) {
                $predictions[$j] += $this->rate * $prediction;
            }
        }

        return $predictions;
    }
338376
public function predict(Dataset $dataset) : array
    {
        if (empty($this->samples) or empty($this->labels)) {
            throw new RuntimeException('Estimator has not been trained.');
        }

        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $predictions = [];

        foreach ($dataset as $sample) {
            [$labels, $distances] = $this->nearest($sample);

            if ($this->weighted) {
                $weights = [];

                foreach ($distances as $i => $distance) {
                    $weights[] = 1. / (1. + $distance);
                }

                $outcome = Stats::weightedMean($labels, $weights);
            } else {
                $outcome = Stats::mean($labels);
            }

            $predictions[] = $outcome;
        }

        return $predictions;
    }
1197360
private function buildMin(Dataset $dataset): self
    {
        $this->min = new Quartile(min(...$dataset->ordinates()));

        return $this;
    }