Calculate the joint log likelihood of a sample being a member of each class.

@param array $sample
@return array
190543
protected function jointLogLikelihood(array $sample) : array
    {
        $likelihoods = [];

        foreach ($this->probs as $class => $probs) {
            $likelihood = $this->priors[$class] ?? LOG_EPSILON;

            foreach ($sample as $column => $feature) {
                $likelihood += $probs[$column][$feature] ?? LOG_EPSILON;
            }

            $likelihoods[$class] = $likelihood;
        }

        return $likelihoods;
    }
549409
public static function population(array $a, $sample = true)
    {
        if (empty($a)) {
            throw InvalidArgumentException::arrayCantBeEmpty();
        }

        $n = count($a);

        if ($sample && $n === 1) {
            throw InvalidArgumentException::arraySizeToSmall(2);
        }

        $mean = Mean::arithmetic($a);
        $carry = 0.0;
        foreach ($a as $val) {
            $d = $val - $mean;
            $carry += $d * $d;
        }

        if ($sample) {
            --$n;
        }

        return sqrt((float) ($carry / $n));
    }
1118471
public function predict(Dataset $dataset) : array
    {
        if (empty($this->ensemble)) {
            throw new RuntimeException('Estimator has not been trained.');
        }

        $aggregate = [];

        foreach ($this->ensemble as $estimator) {
            foreach ($estimator->predict($dataset) as $i => $prediction) {
                $aggregate[$i][] = $prediction;
            }
        }
        
        switch ($this->type()) {
            case self::CLASSIFIER:
                return array_map([self::class, 'decideClass'], $aggregate);

            case self::REGRESSOR:
                return array_map([Stats::class, 'mean'], $aggregate);

            case self::ANOMALY_DETECTOR:
                return array_map([self::class, 'decideAnomaly'], $aggregate);

        }
    }
52290
public function predict(\CArray $X)
    {
        $predicted_classes = [];
        $jll = $this->_joint_log_likelihood($X);
        $predictions = CArray::toArray(CArray::argmax($jll, 1));
        foreach($predictions as $pred) {
            $predicted_classes[] = $this->classes_[[(int)$pred]];
        }
        return $predicted_classes;
    }
996116
public function columns() : array
    {
        if ($this->numRows() > 1) {
            return array_map(null, ...$this->samples);
        }

        $n = $this->numColumns();

        $columns = [];

        for ($i = 0; $i < $n; $i++) {
            $columns[] = array_column($this->samples, $i);
        }

        return $columns;
    }
834811
protected function membership(array $sample) : array
    {
        $membership = $distances = [];

        foreach ($this->centroids as $centroid) {
            $distances[] = $this->kernel->compute($sample, $centroid);
        }

        $total = array_sum($distances) ?: EPSILON;

        foreach ($distances as $distance) {
            $membership[] = $distance / $total;
        }

        return $membership;
    }
182451
private function antecedents(array $sample): array
    {
        $cardinality = count($sample);
        $antecedents = $this->powerSet($sample);

        return array_filter($antecedents, function ($antecedent) use ($cardinality) {
            return (count($antecedent) != $cardinality) && ($antecedent != []);
        });
    }
1360176
protected function predictProbability(array $sample, $label): float
    {
        $predicted = $this->predictSampleBinary($sample);

        if ((string) $predicted == (string) $label) {
            $sample = $this->checkNormalizedSample($sample);

            return (float) abs($this->output($sample));
        }

        return 0.0;
    }
291264
protected function getDistancePairs(array $sample)
    {
        $kernel = $this->getKernel();

        $pairs = [];
        foreach ($this->data as $row) {
            $pairs[] = $kernel($row, $sample);
        }

        return $pairs;
    }
254638
protected function calc()
    {
        if (!file_exists($this->track)) throw new \Exception("File '{$this->track}' doesn't exist");

        $length = $this->track->getLength();
        $rate = null;
        $sample_count = $this->track->getSampleCount();

        $trim = null;
        if ($this->offset || $this->duration) {
            $offset = $this->offset >= 0 ? $this->offset : $length + $this->offset;
            $trim = $offset . ($this->duration ? " " . (float)$this->duration : '');
            
            $newlength = $this->duration ?: $length - $offset;
            $sample_count = floor(($newlength / $length) * $sample_count);
            $length = $newlength;
        }
        
        // Downsample to max 500 samples per pixel with a minimum sample rate of 4k/s
        if ($sample_count / $this->width > 500) {
            $rate = max(($this->width / $length) * 500, 4000);
            $sample_count = $rate * $length;
        }
        
        $this->length = $length;
        
        $this->samples = $this->calcExecute($sample_count, $trim, $rate);
        
        if (!isset($this->level)) {
            $this->level = max(-1 * min($this->samples), max($this->samples));
        }
    }
239795
def log_likelihoods(text, classnames=nil)
      classnames ||= @classnames
      result = Hash.new 0

      TextHash.new(text).each { |word, count|
        probs = get_word_probs(word, classnames)
        classnames.each { |k|
          # Choose a really small probability if the word has never been seen before in class k
          result[k] += Math.log(probs[k] > 0 ? (probs[k] * count) : Float::EPSILON)
        }
      }

      # add the prior
      doc_counts = doc_count_totals.select { |k,v| classnames.include? k }.map { |k,v| v }

      doc_count_total = (doc_counts.inject(0){ |x,y| x+y } + classnames.length).to_f

      classnames.each { |k|
        result[k] += Math.log((@storage.get_doc_count(k) + 1).to_f / doc_count_total)
      }

      result
    end
952709
public function proba(Dataset $dataset) : array
    {
        if (empty($this->samples) or empty($this->labels)) {
            throw new RuntimeException('The learner has not'
                . ' been trained.');
        }

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

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

        $probabilities = [];

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

            if ($this->weighted) {
                $weights = array_fill_keys($labels, 0.);

                foreach ($labels as $i => $label) {
                    $weights[$label] += 1. / (1. + $distances[$i]);
                }
            } else {
                $weights = array_count_values($labels);
            }

            $total = array_sum($weights) ?: EPSILON;

            $dist = $template;

            foreach ($weights as $class => $weight) {
                $dist[$class] = $weight / $total;
            }

            $probabilities[] = $dist;
        }

        return $probabilities;
    }
1011635
@Override
    public double[] sample(long sampleSize) {
        if (sampleSize <= 0) {
            throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES, sampleSize);
        }
        // FIXME: int cast
        double[] out = new double[(int) sampleSize];
        for (int i = 0; i < sampleSize; i++) {
            out[i] = sample();
        }
        return out;
    }
500545
public function proba(Dataset $dataset) : array
    {
        if (!$this->network or !$this->classes) {
            throw new RuntimeException('The learner has not'
                . ' been trained.');
        }

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

        $xT = Matrix::quick($dataset->samples())->transpose();

        $yT = $this->network->infer($xT)->transpose();

        $probabilities = [];

        foreach ($yT as $activations) {
            $probabilities[] = array_combine($this->classes, $activations);
        }

        return $probabilities;
    }
12713
private function frequent(array $samples): array
    {
        return array_values(array_filter($samples, function ($entry) {
            return $this->support($entry) >= $this->support;
        }));
    }
118263
protected function inertia(array $samples) : float
    {
        $inertia = 0.;

        foreach ($samples as $sample) {
            foreach ($this->centroids as $centroid) {
                $inertia += $this->kernel->compute($sample, $centroid);
            }
        }

        return $inertia;
    }
424986
protected function nearest(array $sample) : array
    {
        $distances = [];

        foreach ($this->samples as $neighbor) {
            $distances[] = $this->kernel->compute($sample, $neighbor);
        }

        asort($distances);

        $distances = array_slice($distances, 0, $this->k, true);

        $labels = array_intersect_key($this->labels, $distances);

        return [$labels, $distances];
    }