Perform a partial train on the learner.

@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException
967256
public function partial(Dataset $dataset) : void
    {
        if (!$this->r or !$this->histograms or !$this->n) {
            $this->train($dataset);

            return;
        }

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

        $this->n += $dataset->numRows();

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

        foreach ($z as $i => $values) {
            [$edges, $counts, $densities] = $this->histograms[$i];

            $interior = array_slice($edges, 1, $this->bins);

            foreach ($values as $value) {
                foreach ($interior as $k => $edge) {
                    if ($value < $edge) {
                        $counts[$k]++;

                        continue 2;
                    }
                }

                $counts[$this->bins]++;
            }

            foreach ($counts as $j => $count) {
                $densities[$j] = $count > 0
                    ? -log($count / $this->n)
                    : -LOG_EPSILON;
            }

            $this->histograms[$i] = [$edges, $counts, $densities];
        }
    }
1217154
public function train(Dataset $dataset) : void
    {
        if ($this->type === self::CLASSIFIER or $this->type === self::REGRESSOR) {
            if (!$dataset instanceof Labeled) {
                throw new InvalidArgumentException('This estimator requires a'
                    . ' labeled training set.');
            }
        }

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

        if ($this->logger) {
            $this->logger->info('Learner init ' . Params::stringify([
                'experts' => $this->experts,
                'influences' => $this->influences,
                'workers' => $this->workers,
            ]));
        }

        Loop::run(function () use ($dataset) {
            $pool = new DefaultPool($this->workers);

            $coroutines = [];

            foreach ($this->experts as $index => $estimator) {
                $task = new CallableTask(
                    [$this, '_train'],
                    [$estimator, $dataset]
                );

                $coroutines[] = call(function () use ($pool, $task, $index) {
                    $estimator = yield $pool->enqueue($task);

                    if ($this->logger) {
                        $this->logger->info(Params::stringify([
                            $index => $estimator,
                        ]) . ' finished training');
                    }

                    return $estimator;
                });
            }

            $this->experts = yield all($coroutines);
            
            return yield $pool->shutdown();
        });

        if ($this->type === self::CLASSIFIER and $dataset instanceof Labeled) {
            $this->classes = $dataset->possibleOutcomes();
        }

        if ($this->logger) {
            $this->logger->info('Training complete');
        }
    }
1303127
public function predict(Dataset $dataset) : array
    {
        if (empty($this->weights) or empty($this->probs)) {
            throw new RuntimeException('The learner has not'
                . ' been trained.');
        }

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

        $predictions = [];

        foreach ($dataset as $sample) {
            $jll = $this->jointLogLikelihood($sample);

            $predictions[] = argmax($jll);
        }

        return $predictions;
    }
959146
public function train(Dataset $dataset) : void
    {
        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $this->centroids = $this->seeder->seed($dataset, $this->k);

        $sizes = array_fill(1, $this->k, 0);
        $sizes[0] = $dataset->numRows();

        $this->sizes = $sizes;

        $this->steps = [];

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

        $this->strategy->fit($dataset->labels());

        $this->trained = true;
    }
662742
protected function preparePriceDataKeysCache(DataSetInterface $dataSet): void
    {
        if ($this->isDataKeysCachePrepared) {
            return;
        }
        foreach ($dataSet as $key => $value) {
            if (!$this->isPriceDataKey($key)) {
                continue;
            }
            $this->priceDataKeysCache[$key] = $this->getPriceDataKey($key);
        }
        $this->isDataKeysCachePrepared = true;
    }
1197360
private function buildMin(Dataset $dataset): self
    {
        $this->min = new Quartile(min(...$dataset->ordinates()));

        return $this;
    }
628397
public function execute(DataSetInterface $dataSet): void
    {
        $this->validateDataSet($dataSet);

        $merchantEntity = SpyMerchantQuery::create()
            ->filterByMerchantKey($dataSet[MerchantDataSetInterface::MERCHANT_KEY])
            ->findOneOrCreate();

        $merchantEntity
            ->setName($dataSet[MerchantDataSetInterface::NAME])
            ->save();
    }
1310688
public function execute(DataSetInterface $dataSet): void
    {
        $this->assertHaveProductMeasurementSalesUnit($dataSet[ProductPackagingUnitDataSetInterface::COLUMN_CONCRETE_SKU]);
        $dataSet = $this->normalizeDataSet($dataSet);
        $productPackagingUnitTypeId = $this->getIdProductPackagingUnitTypeByName($dataSet[ProductPackagingUnitDataSetInterface::COLUMN_TYPE_NAME]);
        $productConcreteId = $this->getIdProductBySku($dataSet[ProductPackagingUnitDataSetInterface::COLUMN_CONCRETE_SKU]);

        $productPackagingUnitEntity = $this->getProductPackagingUnitQuery()
            ->filterByFkProduct($productConcreteId)
            ->findOneOrCreate();

        $this->persistLeadProduct($dataSet, $productConcreteId);

        $productPackagingUnitEntity
            ->setHasLeadProduct($dataSet[ProductPackagingUnitDataSetInterface::COLUMN_HAS_LEAD_PRODUCT])
            ->setFkProductPackagingUnitType($productPackagingUnitTypeId);

        $productPackagingUnitEntity->save();

        if ($this->hasAmount($dataSet)) {
            $this->persistAmount($dataSet, $productPackagingUnitEntity);
        }

        $this->addPublishEvents(ProductPackagingUnitEvents::PRODUCT_ABSTRACT_PACKAGING_PUBLISH, $this->getIdProductAbstractByProductSku($dataSet[ProductPackagingUnitDataSetInterface::COLUMN_CONCRETE_SKU]));
    }
284653
public function execute(DataSetInterface $dataSet): void
    {
        $companyBusinessUnitKey = $dataSet[MerchantRelationshipDataSetInterface::COMPANY_BUSINESS_UNIT_OWNER_KEY];
        if (!$companyBusinessUnitKey) {
            throw new InvalidDataException('"' . MerchantRelationshipDataSetInterface::COMPANY_BUSINESS_UNIT_OWNER_KEY . '" is required.');
        }

        if (!isset($this->idCompanyBusinessUnitCache[$companyBusinessUnitKey])) {
            $idCompanyBusinessUnit = SpyCompanyBusinessUnitQuery::create()
                ->select(SpyCompanyBusinessUnitTableMap::COL_ID_COMPANY_BUSINESS_UNIT)
                ->findOneByKey($companyBusinessUnitKey);

            if (!$idCompanyBusinessUnit) {
                throw new EntityNotFoundException(sprintf('Could not find Company Business Unit by key "%s"', $companyBusinessUnitKey));
            }

            $this->idCompanyBusinessUnitCache[$companyBusinessUnitKey] = $idCompanyBusinessUnit;
        }

        $dataSet[MerchantRelationshipDataSetInterface::ID_COMPANY_BUSINESS_UNIT] = $this->idCompanyBusinessUnitCache[$companyBusinessUnitKey];
    }
248708
public function predict(Dataset $dataset) : array
    {
        if ($this->tree->bare()) {
            throw new RuntimeException('The learner has not'
                . ' been trained.');
        }

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

        $predictions = [];

        foreach ($dataset as $sample) {
            [$samples, $labels, $distances] = $this->tree->range($sample, $this->radius);

            if (empty($labels)) {
                $predictions[] = self::OUTLIER;

                continue 1;
            }

            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);
            }

            $predictions[] = argmax($weights);
        }

        return $predictions;
    }
141583
public function execute(DataSetInterface $dataSet): void
    {
        if (!$dataSet[MerchantRelationshipDataSetInterface::COMPANY_BUSINESS_UNIT_ASSIGNEE_KEYS]) {
            $dataSet[MerchantRelationshipDataSetInterface::ID_COMPANY_BUSINESS_UNIT_ASSIGNEE_COLLECTION] = [];

            return;
        }

        $companyBusinessUnitKeys = explode(
            $this->getAssigneeDelimiter(),
            $dataSet[MerchantRelationshipDataSetInterface::COMPANY_BUSINESS_UNIT_ASSIGNEE_KEYS]
        );

        $companyBusinessUnitAssignee = [];
        foreach ($companyBusinessUnitKeys as $companyBusinessUnitKey) {
            $companyBusinessUnitAssignee[] = $this->findIdCompanyBusinessUnit($companyBusinessUnitKey);
        }

        $dataSet[MerchantRelationshipDataSetInterface::ID_COMPANY_BUSINESS_UNIT_ASSIGNEE_COLLECTION] = $companyBusinessUnitAssignee;
    }
677582
public function partial(Dataset $dataset) : void
    {
        if (!$this->network) {
            $this->train($dataset);

            return;
        }

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

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

        if ($this->logger) {
            $this->logger->info('Learner init ' . Params::stringify([
                'batch_size' => $this->batchSize,
                'optimizer' => $this->optimizer,
                'alpha' => $this->alpha,
                'epochs' => $this->epochs,
                'min_change' => $this->minChange,
                'cost_fn' => $this->costFn,
            ]));
        }

        $n = $dataset->numRows();

        [$testing, $training] = $dataset->stratifiedSplit($this->holdout);

        [$min, $max] = $this->metric->range();

        $randomize = $n > $this->batchSize ? true : false;

        $bestScore = $min;
        $bestSnapshot = null;
        $previous = INF;

        for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
            if ($randomize) {
                $training->randomize();
            }

            $batches = $training->batch($this->batchSize);

            $loss = 0.;

            foreach ($batches as $batch) {
                $loss += $this->network->roundtrip($batch);
            }

            $loss /= $n;

            $predictions = $this->predict($testing);

            $score = $this->metric->score($predictions, $testing->labels());

            $this->steps[] = $loss;
            $this->scores[] = $score;

            if ($score > $bestScore) {
                $bestScore = $score;
                $bestSnapshot = new Snapshot($this->network);
            }

            if ($this->logger) {
                $this->logger->info("Epoch $epoch complete,"
                    . " score=$score loss=$loss");
            }

            if (is_nan($loss) or is_nan($score)) {
                break 1;
            }

            if (abs($previous - $loss) < $this->minChange) {
                break 1;
            }

            if ($loss < EPSILON or $score >= $max) {
                break 1;
            }

            if ($epoch > $this->window) {
                $window = array_slice($this->scores, -$this->window);

                $worst = $window;
                rsort($worst);

                if ($window === $worst) {
                    break 1;
                }
            }
        }

        if (end($this->scores) < $bestScore) {
            if ($bestSnapshot) {
                $this->network->restore($bestSnapshot);

                if ($this->logger) {
                    $this->logger->info('Network restored'
                        . ' from previous snapshot');
                }
            }
        }

        if ($this->logger) {
            $this->logger->info('Training complete');
            $this->logger->info("Best validation score=$bestScore");
        }
    }
1080487
public function fit(Dataset $dataset) : void
    {
        $this->minimums = $this->maximums = $this->scales = $this->mins = [];

        foreach ($dataset->types() as $column => $type) {
            if ($type === DataType::CONTINUOUS) {
                $this->minimums[$column] = INF;
                $this->maximums[$column] = -INF;
            }
        }

        $this->update($dataset);
    }
859036
public function execute(DataSetInterface $dataSet): void
    {
        $productAlternativeQuery = SpyProductAlternativeQuery::create()
            ->filterByFkProduct($dataSet[ProductAlternativeDataSetInterface::FK_PRODUCT]);

        if ($dataSet[ProductAlternativeDataSetInterface::KEY_COLUMN_ALTERNATIVE_PRODUCT_CONCRETE_SKU]) {
            $this->saveConcreteAlternative($dataSet, $productAlternativeQuery);
        }

        if ($dataSet[ProductAlternativeDataSetInterface::KEY_COLUMN_ALTERNATIVE_PRODUCT_ABSTRACT_SKU]) {
            $this->saveAbstractAlternative($dataSet, $productAlternativeQuery);
        }
    }
380019
public function train(Dataset $dataset) : void
    {
        if (!$dataset instanceof Labeled) {
            throw new InvalidArgumentException('This estimator requires a'
                . ' labeled training set.');
        }

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

        $this->classes = $dataset->possibleOutcomes();

        $mapping = array_flip($this->classes);

        $labels = $dataset->labels();

        $data = [];

        foreach ($dataset as $i => $sample) {
            $data[] = array_merge([$mapping[$labels[$i]]], $sample);
        }

        $this->model = $this->svm->train($data);
    }
1262051
public function execute(DataSetInterface $dataSet): void
    {
        $categoryKey = $dataSet[ProductListDataSetInterface::CATEGORY_KEY];
        if (!$categoryKey) {
            throw new InvalidDataException(sprintf('"%s" is required.', ProductListDataSetInterface::CATEGORY_KEY));
        }

        $dataSet[ProductListDataSetInterface::ID_CATEGORY] = $this->getIdCategoryByKey($categoryKey);
    }