repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 39
1.84M
| func_code_tokens
sequencelengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
eyecatchup/SEOstats | SEOstats/Services/SemRush.php | SemRush.getDomainRank | public static function getDomainRank($url = false, $db = false)
{
$data = self::getBackendData($url, $db, 'domain_rank');
return is_array($data) ? $data['rank']['data'][0] : $data;
} | php | public static function getDomainRank($url = false, $db = false)
{
$data = self::getBackendData($url, $db, 'domain_rank');
return is_array($data) ? $data['rank']['data'][0] : $data;
} | [
"public",
"static",
"function",
"getDomainRank",
"(",
"$",
"url",
"=",
"false",
",",
"$",
"db",
"=",
"false",
")",
"{",
"$",
"data",
"=",
"self",
"::",
"getBackendData",
"(",
"$",
"url",
",",
"$",
"db",
",",
"'domain_rank'",
")",
";",
"return",
"is_array",
"(",
"$",
"data",
")",
"?",
"$",
"data",
"[",
"'rank'",
"]",
"[",
"'data'",
"]",
"[",
"0",
"]",
":",
"$",
"data",
";",
"}"
] | Returns the SEMRush main report data.
(Only main report is public available.)
@access public
@param url string Domain name only, eg. "ebay.com" (/wo quotes).
@param db string Optional: The database to use. Valid values are:
au, br, ca, de, es, fr, it, ru, uk, us, us.bing (us is default)
@return array Returns an array containing the main report data.
@link http://www.semrush.com/api.html | [
"Returns",
"the",
"SEMRush",
"main",
"report",
"data",
".",
"(",
"Only",
"main",
"report",
"is",
"public",
"available",
".",
")"
] | train | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Services/SemRush.php#L81-L86 |
RubixML/RubixML | src/Clusterers/GaussianMixture.php | GaussianMixture.priors | public function priors() : array
{
$priors = [];
if (is_array($this->priors)) {
$total = logsumexp($this->priors);
foreach ($this->priors as $class => $probability) {
$priors[$class] = exp($probability - $total);
}
}
return $priors;
} | php | public function priors() : array
{
$priors = [];
if (is_array($this->priors)) {
$total = logsumexp($this->priors);
foreach ($this->priors as $class => $probability) {
$priors[$class] = exp($probability - $total);
}
}
return $priors;
} | [
"public",
"function",
"priors",
"(",
")",
":",
"array",
"{",
"$",
"priors",
"=",
"[",
"]",
";",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"priors",
")",
")",
"{",
"$",
"total",
"=",
"logsumexp",
"(",
"$",
"this",
"->",
"priors",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"priors",
"as",
"$",
"class",
"=>",
"$",
"probability",
")",
"{",
"$",
"priors",
"[",
"$",
"class",
"]",
"=",
"exp",
"(",
"$",
"probability",
"-",
"$",
"total",
")",
";",
"}",
"}",
"return",
"$",
"priors",
";",
"}"
] | Return the cluster prior probabilities.
@return float[] | [
"Return",
"the",
"cluster",
"prior",
"probabilities",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/GaussianMixture.php#L187-L200 |
RubixML/RubixML | src/Clusterers/GaussianMixture.php | GaussianMixture.train | public function train(Dataset $dataset) : void
{
DatasetIsCompatibleWithEstimator::check($dataset, $this);
if ($this->logger) {
$this->logger->info('Learner init ' . Params::stringify([
'k' => $this->k,
'epochs' => $this->epochs,
'min_change' => $this->minChange,
'seeder' => $this->seeder,
]));
}
$samples = $dataset->samples();
$rotated = $dataset->columns();
$n = $dataset->numRows();
$this->priors = array_fill(0, $this->k, log(1. / $this->k));
[$this->means, $this->variances] = $this->initialize($dataset);
$this->steps = [];
$prevLoss = INF;
for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
$memberships = [];
foreach ($dataset as $sample) {
$jll = $this->jointLogLikelihood($sample);
$memberships[] = array_map('exp', $jll);
}
$loss = 0.;
for ($cluster = 0; $cluster < $this->k; $cluster++) {
$mHat = array_column($memberships, $cluster);
$means = $variances = [];
foreach ($rotated as $values) {
$a = $b = $total = 0.;
foreach ($values as $i => $value) {
$membership = $mHat[$i];
$a += $membership * $value;
$total += $membership;
}
$total = $total ?: EPSILON;
$mean = $a / $total;
foreach ($values as $i => $value) {
$b += $mHat[$i] * ($value - $mean) ** 2;
}
$variance = $b / $total;
$means[] = $mean;
$variances[] = $variance ?: EPSILON;
$loss += $total;
}
$prior = array_sum($mHat) / $n;
$this->means[$cluster] = $means;
$this->variances[$cluster] = $variances;
$this->priors[$cluster] = log($prior);
}
$this->steps[] = $loss;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete, loss=$loss");
}
if (is_nan($loss)) {
break 1;
}
if (abs($loss - $prevLoss) < $this->minChange) {
break 1;
}
$prevLoss = $loss;
}
if ($this->logger) {
$this->logger->info('Training complete');
}
} | php | public function train(Dataset $dataset) : void
{
DatasetIsCompatibleWithEstimator::check($dataset, $this);
if ($this->logger) {
$this->logger->info('Learner init ' . Params::stringify([
'k' => $this->k,
'epochs' => $this->epochs,
'min_change' => $this->minChange,
'seeder' => $this->seeder,
]));
}
$samples = $dataset->samples();
$rotated = $dataset->columns();
$n = $dataset->numRows();
$this->priors = array_fill(0, $this->k, log(1. / $this->k));
[$this->means, $this->variances] = $this->initialize($dataset);
$this->steps = [];
$prevLoss = INF;
for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
$memberships = [];
foreach ($dataset as $sample) {
$jll = $this->jointLogLikelihood($sample);
$memberships[] = array_map('exp', $jll);
}
$loss = 0.;
for ($cluster = 0; $cluster < $this->k; $cluster++) {
$mHat = array_column($memberships, $cluster);
$means = $variances = [];
foreach ($rotated as $values) {
$a = $b = $total = 0.;
foreach ($values as $i => $value) {
$membership = $mHat[$i];
$a += $membership * $value;
$total += $membership;
}
$total = $total ?: EPSILON;
$mean = $a / $total;
foreach ($values as $i => $value) {
$b += $mHat[$i] * ($value - $mean) ** 2;
}
$variance = $b / $total;
$means[] = $mean;
$variances[] = $variance ?: EPSILON;
$loss += $total;
}
$prior = array_sum($mHat) / $n;
$this->means[$cluster] = $means;
$this->variances[$cluster] = $variances;
$this->priors[$cluster] = log($prior);
}
$this->steps[] = $loss;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete, loss=$loss");
}
if (is_nan($loss)) {
break 1;
}
if (abs($loss - $prevLoss) < $this->minChange) {
break 1;
}
$prevLoss = $loss;
}
if ($this->logger) {
$this->logger->info('Training complete');
}
} | [
"public",
"function",
"train",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Learner init '",
".",
"Params",
"::",
"stringify",
"(",
"[",
"'k'",
"=>",
"$",
"this",
"->",
"k",
",",
"'epochs'",
"=>",
"$",
"this",
"->",
"epochs",
",",
"'min_change'",
"=>",
"$",
"this",
"->",
"minChange",
",",
"'seeder'",
"=>",
"$",
"this",
"->",
"seeder",
",",
"]",
")",
")",
";",
"}",
"$",
"samples",
"=",
"$",
"dataset",
"->",
"samples",
"(",
")",
";",
"$",
"rotated",
"=",
"$",
"dataset",
"->",
"columns",
"(",
")",
";",
"$",
"n",
"=",
"$",
"dataset",
"->",
"numRows",
"(",
")",
";",
"$",
"this",
"->",
"priors",
"=",
"array_fill",
"(",
"0",
",",
"$",
"this",
"->",
"k",
",",
"log",
"(",
"1.",
"/",
"$",
"this",
"->",
"k",
")",
")",
";",
"[",
"$",
"this",
"->",
"means",
",",
"$",
"this",
"->",
"variances",
"]",
"=",
"$",
"this",
"->",
"initialize",
"(",
"$",
"dataset",
")",
";",
"$",
"this",
"->",
"steps",
"=",
"[",
"]",
";",
"$",
"prevLoss",
"=",
"INF",
";",
"for",
"(",
"$",
"epoch",
"=",
"1",
";",
"$",
"epoch",
"<=",
"$",
"this",
"->",
"epochs",
";",
"$",
"epoch",
"++",
")",
"{",
"$",
"memberships",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"dataset",
"as",
"$",
"sample",
")",
"{",
"$",
"jll",
"=",
"$",
"this",
"->",
"jointLogLikelihood",
"(",
"$",
"sample",
")",
";",
"$",
"memberships",
"[",
"]",
"=",
"array_map",
"(",
"'exp'",
",",
"$",
"jll",
")",
";",
"}",
"$",
"loss",
"=",
"0.",
";",
"for",
"(",
"$",
"cluster",
"=",
"0",
";",
"$",
"cluster",
"<",
"$",
"this",
"->",
"k",
";",
"$",
"cluster",
"++",
")",
"{",
"$",
"mHat",
"=",
"array_column",
"(",
"$",
"memberships",
",",
"$",
"cluster",
")",
";",
"$",
"means",
"=",
"$",
"variances",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"rotated",
"as",
"$",
"values",
")",
"{",
"$",
"a",
"=",
"$",
"b",
"=",
"$",
"total",
"=",
"0.",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"i",
"=>",
"$",
"value",
")",
"{",
"$",
"membership",
"=",
"$",
"mHat",
"[",
"$",
"i",
"]",
";",
"$",
"a",
"+=",
"$",
"membership",
"*",
"$",
"value",
";",
"$",
"total",
"+=",
"$",
"membership",
";",
"}",
"$",
"total",
"=",
"$",
"total",
"?",
":",
"EPSILON",
";",
"$",
"mean",
"=",
"$",
"a",
"/",
"$",
"total",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"i",
"=>",
"$",
"value",
")",
"{",
"$",
"b",
"+=",
"$",
"mHat",
"[",
"$",
"i",
"]",
"*",
"(",
"$",
"value",
"-",
"$",
"mean",
")",
"**",
"2",
";",
"}",
"$",
"variance",
"=",
"$",
"b",
"/",
"$",
"total",
";",
"$",
"means",
"[",
"]",
"=",
"$",
"mean",
";",
"$",
"variances",
"[",
"]",
"=",
"$",
"variance",
"?",
":",
"EPSILON",
";",
"$",
"loss",
"+=",
"$",
"total",
";",
"}",
"$",
"prior",
"=",
"array_sum",
"(",
"$",
"mHat",
")",
"/",
"$",
"n",
";",
"$",
"this",
"->",
"means",
"[",
"$",
"cluster",
"]",
"=",
"$",
"means",
";",
"$",
"this",
"->",
"variances",
"[",
"$",
"cluster",
"]",
"=",
"$",
"variances",
";",
"$",
"this",
"->",
"priors",
"[",
"$",
"cluster",
"]",
"=",
"log",
"(",
"$",
"prior",
")",
";",
"}",
"$",
"this",
"->",
"steps",
"[",
"]",
"=",
"$",
"loss",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"\"Epoch $epoch complete, loss=$loss\"",
")",
";",
"}",
"if",
"(",
"is_nan",
"(",
"$",
"loss",
")",
")",
"{",
"break",
"1",
";",
"}",
"if",
"(",
"abs",
"(",
"$",
"loss",
"-",
"$",
"prevLoss",
")",
"<",
"$",
"this",
"->",
"minChange",
")",
"{",
"break",
"1",
";",
"}",
"$",
"prevLoss",
"=",
"$",
"loss",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Training complete'",
")",
";",
"}",
"}"
] | Train the learner with a dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Train",
"the",
"learner",
"with",
"a",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/GaussianMixture.php#L238-L333 |
RubixML/RubixML | src/Clusterers/GaussianMixture.php | GaussianMixture.proba | public function proba(Dataset $dataset) : array
{
if (empty($this->priors)) {
throw new RuntimeException('Estimator has not been trained.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$probabilities = [];
foreach ($dataset as $sample) {
$jll = $this->jointLogLikelihood($sample);
$total = logsumexp($jll);
$dist = [];
foreach ($jll as $cluster => $likelihood) {
$dist[$cluster] = exp($likelihood - $total);
}
$probabilities[] = $dist;
}
return $probabilities;
} | php | public function proba(Dataset $dataset) : array
{
if (empty($this->priors)) {
throw new RuntimeException('Estimator has not been trained.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$probabilities = [];
foreach ($dataset as $sample) {
$jll = $this->jointLogLikelihood($sample);
$total = logsumexp($jll);
$dist = [];
foreach ($jll as $cluster => $likelihood) {
$dist[$cluster] = exp($likelihood - $total);
}
$probabilities[] = $dist;
}
return $probabilities;
} | [
"public",
"function",
"proba",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"array",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"priors",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Estimator has not been trained.'",
")",
";",
"}",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"$",
"probabilities",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"dataset",
"as",
"$",
"sample",
")",
"{",
"$",
"jll",
"=",
"$",
"this",
"->",
"jointLogLikelihood",
"(",
"$",
"sample",
")",
";",
"$",
"total",
"=",
"logsumexp",
"(",
"$",
"jll",
")",
";",
"$",
"dist",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"jll",
"as",
"$",
"cluster",
"=>",
"$",
"likelihood",
")",
"{",
"$",
"dist",
"[",
"$",
"cluster",
"]",
"=",
"exp",
"(",
"$",
"likelihood",
"-",
"$",
"total",
")",
";",
"}",
"$",
"probabilities",
"[",
"]",
"=",
"$",
"dist",
";",
"}",
"return",
"$",
"probabilities",
";",
"}"
] | Estimate probabilities for each possible outcome.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException
@throws \RuntimeException
@return array | [
"Estimate",
"probabilities",
"for",
"each",
"possible",
"outcome",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/GaussianMixture.php#L370-L395 |
RubixML/RubixML | src/Clusterers/GaussianMixture.php | GaussianMixture.initialize | protected function initialize(Dataset $dataset) : array
{
$centroids = $this->seeder->seed($dataset, $this->k);
$kernel = new Euclidean();
$clusters = array_fill(0, $this->k, []);
foreach ($dataset as $sample) {
$bestDistance = INF;
$bestCluster = -1;
foreach ($centroids as $cluster => $centroid) {
$distance = $kernel->compute($sample, $centroid);
if ($distance < $bestDistance) {
$bestDistance = $distance;
$bestCluster = $cluster;
}
}
$clusters[$bestCluster][] = $sample;
}
$means = $variances = [];
foreach ($clusters as $cluster => $samples) {
$mHat = $vHat = [];
$columns = array_map(null, ...$samples);
foreach ($columns as $values) {
[$mean, $variance] = Stats::meanVar($values);
$mHat[] = $mean;
$vHat[] = $variance;
}
$means[$cluster] = $mHat;
$variances[$cluster] = $vHat;
}
return [$means, $variances];
} | php | protected function initialize(Dataset $dataset) : array
{
$centroids = $this->seeder->seed($dataset, $this->k);
$kernel = new Euclidean();
$clusters = array_fill(0, $this->k, []);
foreach ($dataset as $sample) {
$bestDistance = INF;
$bestCluster = -1;
foreach ($centroids as $cluster => $centroid) {
$distance = $kernel->compute($sample, $centroid);
if ($distance < $bestDistance) {
$bestDistance = $distance;
$bestCluster = $cluster;
}
}
$clusters[$bestCluster][] = $sample;
}
$means = $variances = [];
foreach ($clusters as $cluster => $samples) {
$mHat = $vHat = [];
$columns = array_map(null, ...$samples);
foreach ($columns as $values) {
[$mean, $variance] = Stats::meanVar($values);
$mHat[] = $mean;
$vHat[] = $variance;
}
$means[$cluster] = $mHat;
$variances[$cluster] = $vHat;
}
return [$means, $variances];
} | [
"protected",
"function",
"initialize",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"array",
"{",
"$",
"centroids",
"=",
"$",
"this",
"->",
"seeder",
"->",
"seed",
"(",
"$",
"dataset",
",",
"$",
"this",
"->",
"k",
")",
";",
"$",
"kernel",
"=",
"new",
"Euclidean",
"(",
")",
";",
"$",
"clusters",
"=",
"array_fill",
"(",
"0",
",",
"$",
"this",
"->",
"k",
",",
"[",
"]",
")",
";",
"foreach",
"(",
"$",
"dataset",
"as",
"$",
"sample",
")",
"{",
"$",
"bestDistance",
"=",
"INF",
";",
"$",
"bestCluster",
"=",
"-",
"1",
";",
"foreach",
"(",
"$",
"centroids",
"as",
"$",
"cluster",
"=>",
"$",
"centroid",
")",
"{",
"$",
"distance",
"=",
"$",
"kernel",
"->",
"compute",
"(",
"$",
"sample",
",",
"$",
"centroid",
")",
";",
"if",
"(",
"$",
"distance",
"<",
"$",
"bestDistance",
")",
"{",
"$",
"bestDistance",
"=",
"$",
"distance",
";",
"$",
"bestCluster",
"=",
"$",
"cluster",
";",
"}",
"}",
"$",
"clusters",
"[",
"$",
"bestCluster",
"]",
"[",
"]",
"=",
"$",
"sample",
";",
"}",
"$",
"means",
"=",
"$",
"variances",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"clusters",
"as",
"$",
"cluster",
"=>",
"$",
"samples",
")",
"{",
"$",
"mHat",
"=",
"$",
"vHat",
"=",
"[",
"]",
";",
"$",
"columns",
"=",
"array_map",
"(",
"null",
",",
"...",
"$",
"samples",
")",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"values",
")",
"{",
"[",
"$",
"mean",
",",
"$",
"variance",
"]",
"=",
"Stats",
"::",
"meanVar",
"(",
"$",
"values",
")",
";",
"$",
"mHat",
"[",
"]",
"=",
"$",
"mean",
";",
"$",
"vHat",
"[",
"]",
"=",
"$",
"variance",
";",
"}",
"$",
"means",
"[",
"$",
"cluster",
"]",
"=",
"$",
"mHat",
";",
"$",
"variances",
"[",
"$",
"cluster",
"]",
"=",
"$",
"vHat",
";",
"}",
"return",
"[",
"$",
"means",
",",
"$",
"variances",
"]",
";",
"}"
] | Initialize the gaussian components by calculating the means and
variances of k initial cluster centroids generated by the seeder.
@param \Rubix\ML\Datasets\Dataset $dataset
@return array[] | [
"Initialize",
"the",
"gaussian",
"components",
"by",
"calculating",
"the",
"means",
"and",
"variances",
"of",
"k",
"initial",
"cluster",
"centroids",
"generated",
"by",
"the",
"seeder",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/GaussianMixture.php#L437-L480 |
RubixML/RubixML | src/NeuralNet/Layers/PReLU.php | PReLU.initialize | public function initialize(int $fanIn) : int
{
$fanOut = $fanIn;
$alpha = $this->initializer->initialize(1, $fanOut)->columnAsVector(0);
$this->alpha = new VectorParam($alpha);
$this->width = $fanOut;
return $fanOut;
} | php | public function initialize(int $fanIn) : int
{
$fanOut = $fanIn;
$alpha = $this->initializer->initialize(1, $fanOut)->columnAsVector(0);
$this->alpha = new VectorParam($alpha);
$this->width = $fanOut;
return $fanOut;
} | [
"public",
"function",
"initialize",
"(",
"int",
"$",
"fanIn",
")",
":",
"int",
"{",
"$",
"fanOut",
"=",
"$",
"fanIn",
";",
"$",
"alpha",
"=",
"$",
"this",
"->",
"initializer",
"->",
"initialize",
"(",
"1",
",",
"$",
"fanOut",
")",
"->",
"columnAsVector",
"(",
"0",
")",
";",
"$",
"this",
"->",
"alpha",
"=",
"new",
"VectorParam",
"(",
"$",
"alpha",
")",
";",
"$",
"this",
"->",
"width",
"=",
"$",
"fanOut",
";",
"return",
"$",
"fanOut",
";",
"}"
] | Initialize the layer with the fan in from the previous layer and return
the fan out for this layer.
@param int $fanIn
@return int | [
"Initialize",
"the",
"layer",
"with",
"the",
"fan",
"in",
"from",
"the",
"previous",
"layer",
"and",
"return",
"the",
"fan",
"out",
"for",
"this",
"layer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/PReLU.php#L105-L116 |
RubixML/RubixML | src/NeuralNet/Layers/PReLU.php | PReLU.forward | public function forward(Matrix $input) : Matrix
{
$this->input = $input;
return $this->compute($input);
} | php | public function forward(Matrix $input) : Matrix
{
$this->input = $input;
return $this->compute($input);
} | [
"public",
"function",
"forward",
"(",
"Matrix",
"$",
"input",
")",
":",
"Matrix",
"{",
"$",
"this",
"->",
"input",
"=",
"$",
"input",
";",
"return",
"$",
"this",
"->",
"compute",
"(",
"$",
"input",
")",
";",
"}"
] | Compute a forward pass through the layer.
@param \Rubix\Tensor\Matrix $input
@return \Rubix\Tensor\Matrix | [
"Compute",
"a",
"forward",
"pass",
"through",
"the",
"layer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/PReLU.php#L124-L129 |
RubixML/RubixML | src/NeuralNet/Layers/PReLU.php | PReLU.back | public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred
{
if (!$this->alpha) {
throw new RuntimeException('Layer has not been initlaized.');
}
if (!$this->input) {
throw new RuntimeException('Must perform a forward pass before'
. ' backpropagating.');
}
$dOut = $prevGradient->result();
$dIn = $this->input->clipUpper(0.);
$dAlpha = $dOut->multiply($dIn)->sum();
$optimizer->step($this->alpha, $dAlpha);
$z = $this->input;
unset($this->input);
return new Deferred(function () use ($z, $dOut) {
return $this->differentiate($z)->multiply($dOut);
});
} | php | public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred
{
if (!$this->alpha) {
throw new RuntimeException('Layer has not been initlaized.');
}
if (!$this->input) {
throw new RuntimeException('Must perform a forward pass before'
. ' backpropagating.');
}
$dOut = $prevGradient->result();
$dIn = $this->input->clipUpper(0.);
$dAlpha = $dOut->multiply($dIn)->sum();
$optimizer->step($this->alpha, $dAlpha);
$z = $this->input;
unset($this->input);
return new Deferred(function () use ($z, $dOut) {
return $this->differentiate($z)->multiply($dOut);
});
} | [
"public",
"function",
"back",
"(",
"Deferred",
"$",
"prevGradient",
",",
"Optimizer",
"$",
"optimizer",
")",
":",
"Deferred",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"alpha",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer has not been initlaized.'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"input",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Must perform a forward pass before'",
".",
"' backpropagating.'",
")",
";",
"}",
"$",
"dOut",
"=",
"$",
"prevGradient",
"->",
"result",
"(",
")",
";",
"$",
"dIn",
"=",
"$",
"this",
"->",
"input",
"->",
"clipUpper",
"(",
"0.",
")",
";",
"$",
"dAlpha",
"=",
"$",
"dOut",
"->",
"multiply",
"(",
"$",
"dIn",
")",
"->",
"sum",
"(",
")",
";",
"$",
"optimizer",
"->",
"step",
"(",
"$",
"this",
"->",
"alpha",
",",
"$",
"dAlpha",
")",
";",
"$",
"z",
"=",
"$",
"this",
"->",
"input",
";",
"unset",
"(",
"$",
"this",
"->",
"input",
")",
";",
"return",
"new",
"Deferred",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"z",
",",
"$",
"dOut",
")",
"{",
"return",
"$",
"this",
"->",
"differentiate",
"(",
"$",
"z",
")",
"->",
"multiply",
"(",
"$",
"dOut",
")",
";",
"}",
")",
";",
"}"
] | Calculate the gradient and update the parameters of the layer.
@param \Rubix\ML\NeuralNet\Deferred $prevGradient
@param \Rubix\ML\NeuralNet\Optimizers\Optimizer $optimizer
@throws \RuntimeException
@return \Rubix\ML\NeuralNet\Deferred | [
"Calculate",
"the",
"gradient",
"and",
"update",
"the",
"parameters",
"of",
"the",
"layer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/PReLU.php#L150-L176 |
RubixML/RubixML | src/NeuralNet/Layers/PReLU.php | PReLU.compute | protected function compute(Matrix $z) : Matrix
{
if (!$this->alpha) {
throw new RuntimeException('Layer is not initialized.');
}
$alphas = $this->alpha->w();
$computed = [];
foreach ($z as $i => $row) {
$alpha = $alphas[$i];
$activations = [];
foreach ($row as $value) {
$activations[] = $value > 0.
? $value
: $alpha * $value;
}
$computed[] = $activations;
}
return Matrix::quick($computed);
} | php | protected function compute(Matrix $z) : Matrix
{
if (!$this->alpha) {
throw new RuntimeException('Layer is not initialized.');
}
$alphas = $this->alpha->w();
$computed = [];
foreach ($z as $i => $row) {
$alpha = $alphas[$i];
$activations = [];
foreach ($row as $value) {
$activations[] = $value > 0.
? $value
: $alpha * $value;
}
$computed[] = $activations;
}
return Matrix::quick($computed);
} | [
"protected",
"function",
"compute",
"(",
"Matrix",
"$",
"z",
")",
":",
"Matrix",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"alpha",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer is not initialized.'",
")",
";",
"}",
"$",
"alphas",
"=",
"$",
"this",
"->",
"alpha",
"->",
"w",
"(",
")",
";",
"$",
"computed",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"z",
"as",
"$",
"i",
"=>",
"$",
"row",
")",
"{",
"$",
"alpha",
"=",
"$",
"alphas",
"[",
"$",
"i",
"]",
";",
"$",
"activations",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"row",
"as",
"$",
"value",
")",
"{",
"$",
"activations",
"[",
"]",
"=",
"$",
"value",
">",
"0.",
"?",
"$",
"value",
":",
"$",
"alpha",
"*",
"$",
"value",
";",
"}",
"$",
"computed",
"[",
"]",
"=",
"$",
"activations",
";",
"}",
"return",
"Matrix",
"::",
"quick",
"(",
"$",
"computed",
")",
";",
"}"
] | Compute the leaky ReLU activation function and return a matrix.
@param \Rubix\Tensor\Matrix $z
@throws \RuntimeException
@return \Rubix\Tensor\Matrix | [
"Compute",
"the",
"leaky",
"ReLU",
"activation",
"function",
"and",
"return",
"a",
"matrix",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/PReLU.php#L185-L210 |
RubixML/RubixML | src/NeuralNet/Layers/PReLU.php | PReLU.differentiate | protected function differentiate(Matrix $z) : Matrix
{
if (!$this->alpha) {
throw new RuntimeException('Layer has not been initlaized.');
}
$alphas = $this->alpha->w();
$gradient = [];
foreach ($z as $i => $row) {
$alpha = $alphas[$i];
$temp = [];
foreach ($row as $value) {
$temp[] = $value > 0. ? 1. : $alpha;
}
$gradient[] = $temp;
}
return Matrix::quick($gradient);
} | php | protected function differentiate(Matrix $z) : Matrix
{
if (!$this->alpha) {
throw new RuntimeException('Layer has not been initlaized.');
}
$alphas = $this->alpha->w();
$gradient = [];
foreach ($z as $i => $row) {
$alpha = $alphas[$i];
$temp = [];
foreach ($row as $value) {
$temp[] = $value > 0. ? 1. : $alpha;
}
$gradient[] = $temp;
}
return Matrix::quick($gradient);
} | [
"protected",
"function",
"differentiate",
"(",
"Matrix",
"$",
"z",
")",
":",
"Matrix",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"alpha",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer has not been initlaized.'",
")",
";",
"}",
"$",
"alphas",
"=",
"$",
"this",
"->",
"alpha",
"->",
"w",
"(",
")",
";",
"$",
"gradient",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"z",
"as",
"$",
"i",
"=>",
"$",
"row",
")",
"{",
"$",
"alpha",
"=",
"$",
"alphas",
"[",
"$",
"i",
"]",
";",
"$",
"temp",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"row",
"as",
"$",
"value",
")",
"{",
"$",
"temp",
"[",
"]",
"=",
"$",
"value",
">",
"0.",
"?",
"1.",
":",
"$",
"alpha",
";",
"}",
"$",
"gradient",
"[",
"]",
"=",
"$",
"temp",
";",
"}",
"return",
"Matrix",
"::",
"quick",
"(",
"$",
"gradient",
")",
";",
"}"
] | Calculate the partial derivatives of the activation function.
@param \Rubix\Tensor\Matrix $z
@throws \RuntimeException
@return \Rubix\Tensor\Matrix | [
"Calculate",
"the",
"partial",
"derivatives",
"of",
"the",
"activation",
"function",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/PReLU.php#L219-L242 |
RubixML/RubixML | src/Other/Traits/LoggerAware.php | LoggerAware.setLogger | public function setLogger(LoggerInterface $logger) : void
{
if ($this instanceof Wrapper) {
$estimator = $this->base();
if ($estimator instanceof Verbose) {
$estimator->setLogger($logger);
}
}
$this->logger = $logger;
} | php | public function setLogger(LoggerInterface $logger) : void
{
if ($this instanceof Wrapper) {
$estimator = $this->base();
if ($estimator instanceof Verbose) {
$estimator->setLogger($logger);
}
}
$this->logger = $logger;
} | [
"public",
"function",
"setLogger",
"(",
"LoggerInterface",
"$",
"logger",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"instanceof",
"Wrapper",
")",
"{",
"$",
"estimator",
"=",
"$",
"this",
"->",
"base",
"(",
")",
";",
"if",
"(",
"$",
"estimator",
"instanceof",
"Verbose",
")",
"{",
"$",
"estimator",
"->",
"setLogger",
"(",
"$",
"logger",
")",
";",
"}",
"}",
"$",
"this",
"->",
"logger",
"=",
"$",
"logger",
";",
"}"
] | Sets a logger instance on the object.
@param \Psr\Log\LoggerInterface $logger | [
"Sets",
"a",
"logger",
"instance",
"on",
"the",
"object",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Traits/LoggerAware.php#L34-L45 |
RubixML/RubixML | src/Transformers/ZScaleStandardizer.php | ZScaleStandardizer.fit | public function fit(Dataset $dataset) : void
{
$columns = $dataset->columnsByType(DataType::CONTINUOUS);
$this->means = $this->variances = $this->stddevs = [];
foreach ($columns as $column => $values) {
[$mean, $variance] = Stats::meanVar($values);
$this->means[$column] = $mean;
$this->variances[$column] = $variance;
$this->stddevs[$column] = sqrt($variance ?: EPSILON);
}
$this->n = $dataset->numRows();
} | php | public function fit(Dataset $dataset) : void
{
$columns = $dataset->columnsByType(DataType::CONTINUOUS);
$this->means = $this->variances = $this->stddevs = [];
foreach ($columns as $column => $values) {
[$mean, $variance] = Stats::meanVar($values);
$this->means[$column] = $mean;
$this->variances[$column] = $variance;
$this->stddevs[$column] = sqrt($variance ?: EPSILON);
}
$this->n = $dataset->numRows();
} | [
"public",
"function",
"fit",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"$",
"columns",
"=",
"$",
"dataset",
"->",
"columnsByType",
"(",
"DataType",
"::",
"CONTINUOUS",
")",
";",
"$",
"this",
"->",
"means",
"=",
"$",
"this",
"->",
"variances",
"=",
"$",
"this",
"->",
"stddevs",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"column",
"=>",
"$",
"values",
")",
"{",
"[",
"$",
"mean",
",",
"$",
"variance",
"]",
"=",
"Stats",
"::",
"meanVar",
"(",
"$",
"values",
")",
";",
"$",
"this",
"->",
"means",
"[",
"$",
"column",
"]",
"=",
"$",
"mean",
";",
"$",
"this",
"->",
"variances",
"[",
"$",
"column",
"]",
"=",
"$",
"variance",
";",
"$",
"this",
"->",
"stddevs",
"[",
"$",
"column",
"]",
"=",
"sqrt",
"(",
"$",
"variance",
"?",
":",
"EPSILON",
")",
";",
"}",
"$",
"this",
"->",
"n",
"=",
"$",
"dataset",
"->",
"numRows",
"(",
")",
";",
"}"
] | Fit the transformer to the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset | [
"Fit",
"the",
"transformer",
"to",
"the",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/ZScaleStandardizer.php#L116-L131 |
RubixML/RubixML | src/Transformers/ZScaleStandardizer.php | ZScaleStandardizer.update | public function update(Dataset $dataset) : void
{
if ($this->means === null or $this->variances === null) {
$this->fit($dataset);
return;
}
$n = $dataset->numRows();
foreach ($this->means as $column => $oldMean) {
$oldVariance = $this->variances[$column];
$values = $dataset->column($column);
[$mean, $variance] = Stats::meanVar($values);
$this->means[$column] = (($n * $mean)
+ ($this->n * $oldMean))
/ ($this->n + $n);
$varNew = ($this->n
* $oldVariance + ($n * $variance)
+ ($this->n / ($n * ($this->n + $n)))
* ($n * $oldMean - $n * $mean) ** 2)
/ ($this->n + $n);
$this->variances[$column] = $varNew;
$this->stddevs[$column] = sqrt($varNew ?: EPSILON);
}
$this->n += $n;
} | php | public function update(Dataset $dataset) : void
{
if ($this->means === null or $this->variances === null) {
$this->fit($dataset);
return;
}
$n = $dataset->numRows();
foreach ($this->means as $column => $oldMean) {
$oldVariance = $this->variances[$column];
$values = $dataset->column($column);
[$mean, $variance] = Stats::meanVar($values);
$this->means[$column] = (($n * $mean)
+ ($this->n * $oldMean))
/ ($this->n + $n);
$varNew = ($this->n
* $oldVariance + ($n * $variance)
+ ($this->n / ($n * ($this->n + $n)))
* ($n * $oldMean - $n * $mean) ** 2)
/ ($this->n + $n);
$this->variances[$column] = $varNew;
$this->stddevs[$column] = sqrt($varNew ?: EPSILON);
}
$this->n += $n;
} | [
"public",
"function",
"update",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"means",
"===",
"null",
"or",
"$",
"this",
"->",
"variances",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"fit",
"(",
"$",
"dataset",
")",
";",
"return",
";",
"}",
"$",
"n",
"=",
"$",
"dataset",
"->",
"numRows",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"means",
"as",
"$",
"column",
"=>",
"$",
"oldMean",
")",
"{",
"$",
"oldVariance",
"=",
"$",
"this",
"->",
"variances",
"[",
"$",
"column",
"]",
";",
"$",
"values",
"=",
"$",
"dataset",
"->",
"column",
"(",
"$",
"column",
")",
";",
"[",
"$",
"mean",
",",
"$",
"variance",
"]",
"=",
"Stats",
"::",
"meanVar",
"(",
"$",
"values",
")",
";",
"$",
"this",
"->",
"means",
"[",
"$",
"column",
"]",
"=",
"(",
"(",
"$",
"n",
"*",
"$",
"mean",
")",
"+",
"(",
"$",
"this",
"->",
"n",
"*",
"$",
"oldMean",
")",
")",
"/",
"(",
"$",
"this",
"->",
"n",
"+",
"$",
"n",
")",
";",
"$",
"varNew",
"=",
"(",
"$",
"this",
"->",
"n",
"*",
"$",
"oldVariance",
"+",
"(",
"$",
"n",
"*",
"$",
"variance",
")",
"+",
"(",
"$",
"this",
"->",
"n",
"/",
"(",
"$",
"n",
"*",
"(",
"$",
"this",
"->",
"n",
"+",
"$",
"n",
")",
")",
")",
"*",
"(",
"$",
"n",
"*",
"$",
"oldMean",
"-",
"$",
"n",
"*",
"$",
"mean",
")",
"**",
"2",
")",
"/",
"(",
"$",
"this",
"->",
"n",
"+",
"$",
"n",
")",
";",
"$",
"this",
"->",
"variances",
"[",
"$",
"column",
"]",
"=",
"$",
"varNew",
";",
"$",
"this",
"->",
"stddevs",
"[",
"$",
"column",
"]",
"=",
"sqrt",
"(",
"$",
"varNew",
"?",
":",
"EPSILON",
")",
";",
"}",
"$",
"this",
"->",
"n",
"+=",
"$",
"n",
";",
"}"
] | Update the fitting of the transformer.
@param \Rubix\ML\Datasets\Dataset $dataset | [
"Update",
"the",
"fitting",
"of",
"the",
"transformer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/ZScaleStandardizer.php#L138-L170 |
RubixML/RubixML | src/Transformers/ZScaleStandardizer.php | ZScaleStandardizer.transform | public function transform(array &$samples) : void
{
if ($this->means === null or $this->stddevs === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
foreach ($this->stddevs as $column => $stddev) {
$feature = $sample[$column];
if ($this->center) {
$feature -= $this->means[$column];
}
$sample[$column] = $feature / $stddev;
}
}
} | php | public function transform(array &$samples) : void
{
if ($this->means === null or $this->stddevs === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
foreach ($this->stddevs as $column => $stddev) {
$feature = $sample[$column];
if ($this->center) {
$feature -= $this->means[$column];
}
$sample[$column] = $feature / $stddev;
}
}
} | [
"public",
"function",
"transform",
"(",
"array",
"&",
"$",
"samples",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"means",
"===",
"null",
"or",
"$",
"this",
"->",
"stddevs",
"===",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Transformer has not been fitted.'",
")",
";",
"}",
"foreach",
"(",
"$",
"samples",
"as",
"&",
"$",
"sample",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"stddevs",
"as",
"$",
"column",
"=>",
"$",
"stddev",
")",
"{",
"$",
"feature",
"=",
"$",
"sample",
"[",
"$",
"column",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"center",
")",
"{",
"$",
"feature",
"-=",
"$",
"this",
"->",
"means",
"[",
"$",
"column",
"]",
";",
"}",
"$",
"sample",
"[",
"$",
"column",
"]",
"=",
"$",
"feature",
"/",
"$",
"stddev",
";",
"}",
"}",
"}"
] | Transform the dataset in place.
@param array $samples
@throws \RuntimeException | [
"Transform",
"the",
"dataset",
"in",
"place",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/ZScaleStandardizer.php#L178-L195 |
RubixML/RubixML | src/CrossValidation/Metrics/VMeasure.php | VMeasure.score | public function score(array $predictions, array $labels) : float
{
if (empty($predictions)) {
return 0.;
}
$homogeneity = (new Homogeneity())->score($predictions, $labels);
$completeness = (new Completeness())->score($predictions, $labels);
return 2. * ($homogeneity * $completeness)
/ ($homogeneity + $completeness);
} | php | public function score(array $predictions, array $labels) : float
{
if (empty($predictions)) {
return 0.;
}
$homogeneity = (new Homogeneity())->score($predictions, $labels);
$completeness = (new Completeness())->score($predictions, $labels);
return 2. * ($homogeneity * $completeness)
/ ($homogeneity + $completeness);
} | [
"public",
"function",
"score",
"(",
"array",
"$",
"predictions",
",",
"array",
"$",
"labels",
")",
":",
"float",
"{",
"if",
"(",
"empty",
"(",
"$",
"predictions",
")",
")",
"{",
"return",
"0.",
";",
"}",
"$",
"homogeneity",
"=",
"(",
"new",
"Homogeneity",
"(",
")",
")",
"->",
"score",
"(",
"$",
"predictions",
",",
"$",
"labels",
")",
";",
"$",
"completeness",
"=",
"(",
"new",
"Completeness",
"(",
")",
")",
"->",
"score",
"(",
"$",
"predictions",
",",
"$",
"labels",
")",
";",
"return",
"2.",
"*",
"(",
"$",
"homogeneity",
"*",
"$",
"completeness",
")",
"/",
"(",
"$",
"homogeneity",
"+",
"$",
"completeness",
")",
";",
"}"
] | Score a set of predictions.
@param array $predictions
@param array $labels
@return float | [
"Score",
"a",
"set",
"of",
"predictions",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CrossValidation/Metrics/VMeasure.php#L52-L63 |
RubixML/RubixML | src/CrossValidation/Metrics/RandIndex.php | RandIndex.comb | public static function comb(int $n, int $k = 2) : int
{
return $k === 0 ? 1 : (int) (($n * self::comb($n - 1, $k - 1)) / $k);
} | php | public static function comb(int $n, int $k = 2) : int
{
return $k === 0 ? 1 : (int) (($n * self::comb($n - 1, $k - 1)) / $k);
} | [
"public",
"static",
"function",
"comb",
"(",
"int",
"$",
"n",
",",
"int",
"$",
"k",
"=",
"2",
")",
":",
"int",
"{",
"return",
"$",
"k",
"===",
"0",
"?",
"1",
":",
"(",
"int",
")",
"(",
"(",
"$",
"n",
"*",
"self",
"::",
"comb",
"(",
"$",
"n",
"-",
"1",
",",
"$",
"k",
"-",
"1",
")",
")",
"/",
"$",
"k",
")",
";",
"}"
] | Compute n choose k.
@param int $n
@param int $k
@return int | [
"Compute",
"n",
"choose",
"k",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CrossValidation/Metrics/RandIndex.php#L36-L39 |
RubixML/RubixML | src/CrossValidation/Metrics/RandIndex.php | RandIndex.score | public function score(array $predictions, array $labels) : float
{
if (empty($predictions)) {
return 0.;
}
$n = count($predictions);
if ($n !== count($labels)) {
throw new InvalidArgumentException('The number of labels'
. ' must equal the number of predictions.');
}
$table = Matrix::build((new ContingencyTable())->generate($predictions, $labels));
$sigma = $table->map([self::class, 'comb'])->sum()->sum();
$alpha = $table->sum()->map([self::class, 'comb'])->sum();
$beta = $table->transpose()->sum()->map([self::class, 'comb'])->sum();
$pHat = ($alpha * $beta) / self::comb($n);
$mean = ($alpha + $beta) / 2.;
return ($sigma - $pHat) / ($mean - $pHat);
} | php | public function score(array $predictions, array $labels) : float
{
if (empty($predictions)) {
return 0.;
}
$n = count($predictions);
if ($n !== count($labels)) {
throw new InvalidArgumentException('The number of labels'
. ' must equal the number of predictions.');
}
$table = Matrix::build((new ContingencyTable())->generate($predictions, $labels));
$sigma = $table->map([self::class, 'comb'])->sum()->sum();
$alpha = $table->sum()->map([self::class, 'comb'])->sum();
$beta = $table->transpose()->sum()->map([self::class, 'comb'])->sum();
$pHat = ($alpha * $beta) / self::comb($n);
$mean = ($alpha + $beta) / 2.;
return ($sigma - $pHat) / ($mean - $pHat);
} | [
"public",
"function",
"score",
"(",
"array",
"$",
"predictions",
",",
"array",
"$",
"labels",
")",
":",
"float",
"{",
"if",
"(",
"empty",
"(",
"$",
"predictions",
")",
")",
"{",
"return",
"0.",
";",
"}",
"$",
"n",
"=",
"count",
"(",
"$",
"predictions",
")",
";",
"if",
"(",
"$",
"n",
"!==",
"count",
"(",
"$",
"labels",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'The number of labels'",
".",
"' must equal the number of predictions.'",
")",
";",
"}",
"$",
"table",
"=",
"Matrix",
"::",
"build",
"(",
"(",
"new",
"ContingencyTable",
"(",
")",
")",
"->",
"generate",
"(",
"$",
"predictions",
",",
"$",
"labels",
")",
")",
";",
"$",
"sigma",
"=",
"$",
"table",
"->",
"map",
"(",
"[",
"self",
"::",
"class",
",",
"'comb'",
"]",
")",
"->",
"sum",
"(",
")",
"->",
"sum",
"(",
")",
";",
"$",
"alpha",
"=",
"$",
"table",
"->",
"sum",
"(",
")",
"->",
"map",
"(",
"[",
"self",
"::",
"class",
",",
"'comb'",
"]",
")",
"->",
"sum",
"(",
")",
";",
"$",
"beta",
"=",
"$",
"table",
"->",
"transpose",
"(",
")",
"->",
"sum",
"(",
")",
"->",
"map",
"(",
"[",
"self",
"::",
"class",
",",
"'comb'",
"]",
")",
"->",
"sum",
"(",
")",
";",
"$",
"pHat",
"=",
"(",
"$",
"alpha",
"*",
"$",
"beta",
")",
"/",
"self",
"::",
"comb",
"(",
"$",
"n",
")",
";",
"$",
"mean",
"=",
"(",
"$",
"alpha",
"+",
"$",
"beta",
")",
"/",
"2.",
";",
"return",
"(",
"$",
"sigma",
"-",
"$",
"pHat",
")",
"/",
"(",
"$",
"mean",
"-",
"$",
"pHat",
")",
";",
"}"
] | Score a set of predictions.
@param array $predictions
@param array $labels
@throws \InvalidArgumentException
@return float | [
"Score",
"a",
"set",
"of",
"predictions",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CrossValidation/Metrics/RandIndex.php#L71-L95 |
RubixML/RubixML | src/Clusterers/Seeders/KMC2.php | KMC2.seed | public function seed(Dataset $dataset, int $k) : array
{
$centroids = $dataset->randomSubsetWithReplacement(1)->samples();
for ($i = 1; $i < $k; $i++) {
$candidates = $dataset->randomSubsetWithReplacement($this->m)->samples();
$x = array_pop($candidates);
$target = end($centroids);
$xDistance = $this->kernel->compute($x, $target) ?: EPSILON;
foreach ($candidates as $y) {
$yDistance = $this->kernel->compute($y, $target);
$probability = min(1., $yDistance / $xDistance);
if ($probability === 1.) {
$xDistance = $yDistance;
$x = $y;
continue 1;
}
$threshold = rand(0, self::PHI) / self::PHI;
if ($probability > $threshold) {
$xDistance = $yDistance;
$x = $y;
}
}
$centroids[] = $x;
}
return $centroids;
} | php | public function seed(Dataset $dataset, int $k) : array
{
$centroids = $dataset->randomSubsetWithReplacement(1)->samples();
for ($i = 1; $i < $k; $i++) {
$candidates = $dataset->randomSubsetWithReplacement($this->m)->samples();
$x = array_pop($candidates);
$target = end($centroids);
$xDistance = $this->kernel->compute($x, $target) ?: EPSILON;
foreach ($candidates as $y) {
$yDistance = $this->kernel->compute($y, $target);
$probability = min(1., $yDistance / $xDistance);
if ($probability === 1.) {
$xDistance = $yDistance;
$x = $y;
continue 1;
}
$threshold = rand(0, self::PHI) / self::PHI;
if ($probability > $threshold) {
$xDistance = $yDistance;
$x = $y;
}
}
$centroids[] = $x;
}
return $centroids;
} | [
"public",
"function",
"seed",
"(",
"Dataset",
"$",
"dataset",
",",
"int",
"$",
"k",
")",
":",
"array",
"{",
"$",
"centroids",
"=",
"$",
"dataset",
"->",
"randomSubsetWithReplacement",
"(",
"1",
")",
"->",
"samples",
"(",
")",
";",
"for",
"(",
"$",
"i",
"=",
"1",
";",
"$",
"i",
"<",
"$",
"k",
";",
"$",
"i",
"++",
")",
"{",
"$",
"candidates",
"=",
"$",
"dataset",
"->",
"randomSubsetWithReplacement",
"(",
"$",
"this",
"->",
"m",
")",
"->",
"samples",
"(",
")",
";",
"$",
"x",
"=",
"array_pop",
"(",
"$",
"candidates",
")",
";",
"$",
"target",
"=",
"end",
"(",
"$",
"centroids",
")",
";",
"$",
"xDistance",
"=",
"$",
"this",
"->",
"kernel",
"->",
"compute",
"(",
"$",
"x",
",",
"$",
"target",
")",
"?",
":",
"EPSILON",
";",
"foreach",
"(",
"$",
"candidates",
"as",
"$",
"y",
")",
"{",
"$",
"yDistance",
"=",
"$",
"this",
"->",
"kernel",
"->",
"compute",
"(",
"$",
"y",
",",
"$",
"target",
")",
";",
"$",
"probability",
"=",
"min",
"(",
"1.",
",",
"$",
"yDistance",
"/",
"$",
"xDistance",
")",
";",
"if",
"(",
"$",
"probability",
"===",
"1.",
")",
"{",
"$",
"xDistance",
"=",
"$",
"yDistance",
";",
"$",
"x",
"=",
"$",
"y",
";",
"continue",
"1",
";",
"}",
"$",
"threshold",
"=",
"rand",
"(",
"0",
",",
"self",
"::",
"PHI",
")",
"/",
"self",
"::",
"PHI",
";",
"if",
"(",
"$",
"probability",
">",
"$",
"threshold",
")",
"{",
"$",
"xDistance",
"=",
"$",
"yDistance",
";",
"$",
"x",
"=",
"$",
"y",
";",
"}",
"}",
"$",
"centroids",
"[",
"]",
"=",
"$",
"x",
";",
"}",
"return",
"$",
"centroids",
";",
"}"
] | Seed k cluster centroids from a dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@param int $k
@throws \RuntimeException
@return array | [
"Seed",
"k",
"cluster",
"centroids",
"from",
"a",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/Seeders/KMC2.php#L68-L105 |
RubixML/RubixML | src/AnomalyDetectors/OneClassSVM.php | OneClassSVM.train | public function train(Dataset $dataset) : void
{
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$this->model = $this->svm->train($dataset->samples());
} | php | public function train(Dataset $dataset) : void
{
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$this->model = $this->svm->train($dataset->samples());
} | [
"public",
"function",
"train",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"$",
"this",
"->",
"model",
"=",
"$",
"this",
"->",
"svm",
"->",
"train",
"(",
"$",
"dataset",
"->",
"samples",
"(",
")",
")",
";",
"}"
] | Train the learner with a dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Train",
"the",
"learner",
"with",
"a",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/AnomalyDetectors/OneClassSVM.php#L142-L147 |
RubixML/RubixML | src/AnomalyDetectors/OneClassSVM.php | OneClassSVM.predict | public function predict(Dataset $dataset) : array
{
if (!$this->model) {
throw new RuntimeException('The learner has not'
. ' been trained.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$predictions = [];
foreach ($dataset as $sample) {
$predictions[] = $this->model->predict($sample) !== 1. ? 0 : 1;
}
return $predictions;
} | php | public function predict(Dataset $dataset) : array
{
if (!$this->model) {
throw new RuntimeException('The learner has not'
. ' been trained.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$predictions = [];
foreach ($dataset as $sample) {
$predictions[] = $this->model->predict($sample) !== 1. ? 0 : 1;
}
return $predictions;
} | [
"public",
"function",
"predict",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"model",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'The learner has not'",
".",
"' been trained.'",
")",
";",
"}",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"$",
"predictions",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"dataset",
"as",
"$",
"sample",
")",
"{",
"$",
"predictions",
"[",
"]",
"=",
"$",
"this",
"->",
"model",
"->",
"predict",
"(",
"$",
"sample",
")",
"!==",
"1.",
"?",
"0",
":",
"1",
";",
"}",
"return",
"$",
"predictions",
";",
"}"
] | Make predictions from a dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException
@throws \RuntimeException
@return array | [
"Make",
"predictions",
"from",
"a",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/AnomalyDetectors/OneClassSVM.php#L157-L173 |
RubixML/RubixML | src/Other/Helpers/Params.php | Params.ints | public static function ints(int $min, int $max, int $n = 10) : array
{
if (($max - $min) < 0) {
throw new InvalidArgumentException('Maximum cannot be'
. ' less than minimum.');
}
if ($n < 1) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 1 parameter.');
}
if ($n > ($max - $min + 1)) {
throw new InvalidArgumentException('Cannot generate more'
. ' unique integers than in range.');
}
$distribution = [];
while (count($distribution) < $n) {
$r = rand($min, $max);
if (!in_array($r, $distribution)) {
$distribution[] = $r;
}
}
return $distribution;
} | php | public static function ints(int $min, int $max, int $n = 10) : array
{
if (($max - $min) < 0) {
throw new InvalidArgumentException('Maximum cannot be'
. ' less than minimum.');
}
if ($n < 1) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 1 parameter.');
}
if ($n > ($max - $min + 1)) {
throw new InvalidArgumentException('Cannot generate more'
. ' unique integers than in range.');
}
$distribution = [];
while (count($distribution) < $n) {
$r = rand($min, $max);
if (!in_array($r, $distribution)) {
$distribution[] = $r;
}
}
return $distribution;
} | [
"public",
"static",
"function",
"ints",
"(",
"int",
"$",
"min",
",",
"int",
"$",
"max",
",",
"int",
"$",
"n",
"=",
"10",
")",
":",
"array",
"{",
"if",
"(",
"(",
"$",
"max",
"-",
"$",
"min",
")",
"<",
"0",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Maximum cannot be'",
".",
"' less than minimum.'",
")",
";",
"}",
"if",
"(",
"$",
"n",
"<",
"1",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Cannot generate less'",
".",
"' than 1 parameter.'",
")",
";",
"}",
"if",
"(",
"$",
"n",
">",
"(",
"$",
"max",
"-",
"$",
"min",
"+",
"1",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Cannot generate more'",
".",
"' unique integers than in range.'",
")",
";",
"}",
"$",
"distribution",
"=",
"[",
"]",
";",
"while",
"(",
"count",
"(",
"$",
"distribution",
")",
"<",
"$",
"n",
")",
"{",
"$",
"r",
"=",
"rand",
"(",
"$",
"min",
",",
"$",
"max",
")",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"r",
",",
"$",
"distribution",
")",
")",
"{",
"$",
"distribution",
"[",
"]",
"=",
"$",
"r",
";",
"}",
"}",
"return",
"$",
"distribution",
";",
"}"
] | Generate a random unique integer distribution.
@param int $min
@param int $max
@param int $n
@throws \InvalidArgumentException
@return int[] | [
"Generate",
"a",
"random",
"unique",
"integer",
"distribution",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Params.php#L32-L60 |
RubixML/RubixML | src/Other/Helpers/Params.php | Params.floats | public static function floats(float $min, float $max, int $n = 10) : array
{
if (($max - $min) < 0.) {
throw new InvalidArgumentException('Maximum cannot be'
. ' less than minimum.');
}
if ($n < 1) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 1 parameter.');
}
$min = (int) round($min * self::PHI);
$max = (int) round($max * self::PHI);
$distribution = [];
for ($i = 0; $i < $n; $i++) {
$distribution[] = rand($min, $max) / self::PHI;
}
return $distribution;
} | php | public static function floats(float $min, float $max, int $n = 10) : array
{
if (($max - $min) < 0.) {
throw new InvalidArgumentException('Maximum cannot be'
. ' less than minimum.');
}
if ($n < 1) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 1 parameter.');
}
$min = (int) round($min * self::PHI);
$max = (int) round($max * self::PHI);
$distribution = [];
for ($i = 0; $i < $n; $i++) {
$distribution[] = rand($min, $max) / self::PHI;
}
return $distribution;
} | [
"public",
"static",
"function",
"floats",
"(",
"float",
"$",
"min",
",",
"float",
"$",
"max",
",",
"int",
"$",
"n",
"=",
"10",
")",
":",
"array",
"{",
"if",
"(",
"(",
"$",
"max",
"-",
"$",
"min",
")",
"<",
"0.",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Maximum cannot be'",
".",
"' less than minimum.'",
")",
";",
"}",
"if",
"(",
"$",
"n",
"<",
"1",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Cannot generate less'",
".",
"' than 1 parameter.'",
")",
";",
"}",
"$",
"min",
"=",
"(",
"int",
")",
"round",
"(",
"$",
"min",
"*",
"self",
"::",
"PHI",
")",
";",
"$",
"max",
"=",
"(",
"int",
")",
"round",
"(",
"$",
"max",
"*",
"self",
"::",
"PHI",
")",
";",
"$",
"distribution",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"n",
";",
"$",
"i",
"++",
")",
"{",
"$",
"distribution",
"[",
"]",
"=",
"rand",
"(",
"$",
"min",
",",
"$",
"max",
")",
"/",
"self",
"::",
"PHI",
";",
"}",
"return",
"$",
"distribution",
";",
"}"
] | Generate a random distribution of floating point parameters.
@param float $min
@param float $max
@param int $n
@throws \InvalidArgumentException
@return float[] | [
"Generate",
"a",
"random",
"distribution",
"of",
"floating",
"point",
"parameters",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Params.php#L71-L93 |
RubixML/RubixML | src/Other/Helpers/Params.php | Params.grid | public static function grid(float $min, float $max, int $n = 10) : array
{
if ($min > $max) {
throw new InvalidArgumentException('Max cannot be less'
. ' then min.');
}
if ($n < 2) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 2 parameters.');
}
$interval = ($max - $min) / ($n - 1);
return range($min, $max, $interval);
} | php | public static function grid(float $min, float $max, int $n = 10) : array
{
if ($min > $max) {
throw new InvalidArgumentException('Max cannot be less'
. ' then min.');
}
if ($n < 2) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 2 parameters.');
}
$interval = ($max - $min) / ($n - 1);
return range($min, $max, $interval);
} | [
"public",
"static",
"function",
"grid",
"(",
"float",
"$",
"min",
",",
"float",
"$",
"max",
",",
"int",
"$",
"n",
"=",
"10",
")",
":",
"array",
"{",
"if",
"(",
"$",
"min",
">",
"$",
"max",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Max cannot be less'",
".",
"' then min.'",
")",
";",
"}",
"if",
"(",
"$",
"n",
"<",
"2",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Cannot generate less'",
".",
"' than 2 parameters.'",
")",
";",
"}",
"$",
"interval",
"=",
"(",
"$",
"max",
"-",
"$",
"min",
")",
"/",
"(",
"$",
"n",
"-",
"1",
")",
";",
"return",
"range",
"(",
"$",
"min",
",",
"$",
"max",
",",
"$",
"interval",
")",
";",
"}"
] | Generate a grid of evenly distributed parameters.
@param float $min
@param float $max
@param int $n
@throws \InvalidArgumentException
@return float[] | [
"Generate",
"a",
"grid",
"of",
"evenly",
"distributed",
"parameters",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Params.php#L104-L119 |
RubixML/RubixML | src/Other/Helpers/Params.php | Params.args | public static function args($object) : array
{
if (!is_object($object)) {
throw new InvalidArgumentException('Argument must be'
. ' an object ' . gettype($object) . ' found.');
}
$reflector = new ReflectionClass($object);
$constructor = $reflector->getConstructor();
if ($constructor instanceof ReflectionMethod) {
$args = array_column($constructor->getParameters(), 'name');
} else {
$args = [];
}
return $args;
} | php | public static function args($object) : array
{
if (!is_object($object)) {
throw new InvalidArgumentException('Argument must be'
. ' an object ' . gettype($object) . ' found.');
}
$reflector = new ReflectionClass($object);
$constructor = $reflector->getConstructor();
if ($constructor instanceof ReflectionMethod) {
$args = array_column($constructor->getParameters(), 'name');
} else {
$args = [];
}
return $args;
} | [
"public",
"static",
"function",
"args",
"(",
"$",
"object",
")",
":",
"array",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"object",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Argument must be'",
".",
"' an object '",
".",
"gettype",
"(",
"$",
"object",
")",
".",
"' found.'",
")",
";",
"}",
"$",
"reflector",
"=",
"new",
"ReflectionClass",
"(",
"$",
"object",
")",
";",
"$",
"constructor",
"=",
"$",
"reflector",
"->",
"getConstructor",
"(",
")",
";",
"if",
"(",
"$",
"constructor",
"instanceof",
"ReflectionMethod",
")",
"{",
"$",
"args",
"=",
"array_column",
"(",
"$",
"constructor",
"->",
"getParameters",
"(",
")",
",",
"'name'",
")",
";",
"}",
"else",
"{",
"$",
"args",
"=",
"[",
"]",
";",
"}",
"return",
"$",
"args",
";",
"}"
] | Extract the arguments from the model constructor for display.
@param object $object
@throws \InvalidArgumentException
@return string[] | [
"Extract",
"the",
"arguments",
"from",
"the",
"model",
"constructor",
"for",
"display",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Params.php#L128-L146 |
RubixML/RubixML | src/Other/Helpers/Params.php | Params.stringify | public static function stringify(array $constructor, string $equator = '=', string $separator = ' ') : string
{
$strings = [];
foreach ($constructor as $arg => $param) {
if (is_object($param)) {
$param = self::shortName($param);
}
if (is_array($param)) {
$temp = array_combine(array_keys($param), $param) ?: [];
$param = '[' . self::stringify($temp) . ']';
}
$strings[] = (string) $arg . $equator . (string) $param;
}
return implode($separator, $strings);
} | php | public static function stringify(array $constructor, string $equator = '=', string $separator = ' ') : string
{
$strings = [];
foreach ($constructor as $arg => $param) {
if (is_object($param)) {
$param = self::shortName($param);
}
if (is_array($param)) {
$temp = array_combine(array_keys($param), $param) ?: [];
$param = '[' . self::stringify($temp) . ']';
}
$strings[] = (string) $arg . $equator . (string) $param;
}
return implode($separator, $strings);
} | [
"public",
"static",
"function",
"stringify",
"(",
"array",
"$",
"constructor",
",",
"string",
"$",
"equator",
"=",
"'='",
",",
"string",
"$",
"separator",
"=",
"' '",
")",
":",
"string",
"{",
"$",
"strings",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"constructor",
"as",
"$",
"arg",
"=>",
"$",
"param",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"param",
")",
")",
"{",
"$",
"param",
"=",
"self",
"::",
"shortName",
"(",
"$",
"param",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"param",
")",
")",
"{",
"$",
"temp",
"=",
"array_combine",
"(",
"array_keys",
"(",
"$",
"param",
")",
",",
"$",
"param",
")",
"?",
":",
"[",
"]",
";",
"$",
"param",
"=",
"'['",
".",
"self",
"::",
"stringify",
"(",
"$",
"temp",
")",
".",
"']'",
";",
"}",
"$",
"strings",
"[",
"]",
"=",
"(",
"string",
")",
"$",
"arg",
".",
"$",
"equator",
".",
"(",
"string",
")",
"$",
"param",
";",
"}",
"return",
"implode",
"(",
"$",
"separator",
",",
"$",
"strings",
")",
";",
"}"
] | Return a string representation of the constructor arguments from
an associative constructor array.
@param array $constructor
@param string $equator
@param string $separator
@return string | [
"Return",
"a",
"string",
"representation",
"of",
"the",
"constructor",
"arguments",
"from",
"an",
"associative",
"constructor",
"array",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Params.php#L157-L176 |
RubixML/RubixML | src/Other/Helpers/Params.php | Params.shortName | public static function shortName($object) : string
{
if (!is_object($object)) {
throw new InvalidArgumentException('Must provide an object'
. gettype($object) . ' given.');
}
return substr(strrchr(get_class($object), '\\') ?: '', 1);
} | php | public static function shortName($object) : string
{
if (!is_object($object)) {
throw new InvalidArgumentException('Must provide an object'
. gettype($object) . ' given.');
}
return substr(strrchr(get_class($object), '\\') ?: '', 1);
} | [
"public",
"static",
"function",
"shortName",
"(",
"$",
"object",
")",
":",
"string",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"object",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Must provide an object'",
".",
"gettype",
"(",
"$",
"object",
")",
".",
"' given.'",
")",
";",
"}",
"return",
"substr",
"(",
"strrchr",
"(",
"get_class",
"(",
"$",
"object",
")",
",",
"'\\\\'",
")",
"?",
":",
"''",
",",
"1",
")",
";",
"}"
] | Return the short class name from a fully qualified class name
(fqcn).
@param mixed $object
@throws \InvalidArgumentException
@return string | [
"Return",
"the",
"short",
"class",
"name",
"from",
"a",
"fully",
"qualified",
"class",
"name",
"(",
"fqcn",
")",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Params.php#L186-L194 |
RubixML/RubixML | src/CommitteeMachine.php | CommitteeMachine.train | 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');
}
} | php | 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');
}
} | [
"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'",
")",
";",
"}",
"}"
] | Train all the experts with the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Train",
"all",
"the",
"experts",
"with",
"the",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CommitteeMachine.php#L215-L270 |
RubixML/RubixML | src/CommitteeMachine.php | CommitteeMachine.predict | public function predict(Dataset $dataset) : array
{
$aggregate = [];
foreach ($this->experts as $estimator) {
foreach ($estimator->predict($dataset) as $i => $prediction) {
$aggregate[$i][] = $prediction;
}
}
switch ($this->type) {
case self::CLASSIFIER:
return array_map([$this, 'decideClass'], $aggregate);
case self::REGRESSOR:
return array_map([$this, 'decideValue'], $aggregate);
case self::ANOMALY_DETECTOR:
return array_map([$this, 'decideAnomaly'], $aggregate);
}
} | php | public function predict(Dataset $dataset) : array
{
$aggregate = [];
foreach ($this->experts as $estimator) {
foreach ($estimator->predict($dataset) as $i => $prediction) {
$aggregate[$i][] = $prediction;
}
}
switch ($this->type) {
case self::CLASSIFIER:
return array_map([$this, 'decideClass'], $aggregate);
case self::REGRESSOR:
return array_map([$this, 'decideValue'], $aggregate);
case self::ANOMALY_DETECTOR:
return array_map([$this, 'decideAnomaly'], $aggregate);
}
} | [
"public",
"function",
"predict",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"array",
"{",
"$",
"aggregate",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"experts",
"as",
"$",
"estimator",
")",
"{",
"foreach",
"(",
"$",
"estimator",
"->",
"predict",
"(",
"$",
"dataset",
")",
"as",
"$",
"i",
"=>",
"$",
"prediction",
")",
"{",
"$",
"aggregate",
"[",
"$",
"i",
"]",
"[",
"]",
"=",
"$",
"prediction",
";",
"}",
"}",
"switch",
"(",
"$",
"this",
"->",
"type",
")",
"{",
"case",
"self",
"::",
"CLASSIFIER",
":",
"return",
"array_map",
"(",
"[",
"$",
"this",
",",
"'decideClass'",
"]",
",",
"$",
"aggregate",
")",
";",
"case",
"self",
"::",
"REGRESSOR",
":",
"return",
"array_map",
"(",
"[",
"$",
"this",
",",
"'decideValue'",
"]",
",",
"$",
"aggregate",
")",
";",
"case",
"self",
"::",
"ANOMALY_DETECTOR",
":",
"return",
"array_map",
"(",
"[",
"$",
"this",
",",
"'decideAnomaly'",
"]",
",",
"$",
"aggregate",
")",
";",
"}",
"}"
] | Make predictions from a dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@return array | [
"Make",
"predictions",
"from",
"a",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CommitteeMachine.php#L278-L298 |
RubixML/RubixML | src/CommitteeMachine.php | CommitteeMachine.decideClass | public function decideClass(array $votes)
{
$scores = array_fill_keys($this->classes, 0.);
foreach ($votes as $i => $vote) {
$scores[$vote] += $this->influences[$i];
}
return argmax($scores);
} | php | public function decideClass(array $votes)
{
$scores = array_fill_keys($this->classes, 0.);
foreach ($votes as $i => $vote) {
$scores[$vote] += $this->influences[$i];
}
return argmax($scores);
} | [
"public",
"function",
"decideClass",
"(",
"array",
"$",
"votes",
")",
"{",
"$",
"scores",
"=",
"array_fill_keys",
"(",
"$",
"this",
"->",
"classes",
",",
"0.",
")",
";",
"foreach",
"(",
"$",
"votes",
"as",
"$",
"i",
"=>",
"$",
"vote",
")",
"{",
"$",
"scores",
"[",
"$",
"vote",
"]",
"+=",
"$",
"this",
"->",
"influences",
"[",
"$",
"i",
"]",
";",
"}",
"return",
"argmax",
"(",
"$",
"scores",
")",
";",
"}"
] | Decide on a class outcome.
@param (int|string)[] $votes
@return int|string | [
"Decide",
"on",
"a",
"class",
"outcome",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CommitteeMachine.php#L306-L315 |
RubixML/RubixML | src/CommitteeMachine.php | CommitteeMachine.decideAnomaly | public function decideAnomaly(array $votes) : int
{
$scores = array_fill(0, 2, 0.);
foreach ($votes as $i => $vote) {
$scores[$vote] += $this->influences[$i];
}
return argmax($scores);
} | php | public function decideAnomaly(array $votes) : int
{
$scores = array_fill(0, 2, 0.);
foreach ($votes as $i => $vote) {
$scores[$vote] += $this->influences[$i];
}
return argmax($scores);
} | [
"public",
"function",
"decideAnomaly",
"(",
"array",
"$",
"votes",
")",
":",
"int",
"{",
"$",
"scores",
"=",
"array_fill",
"(",
"0",
",",
"2",
",",
"0.",
")",
";",
"foreach",
"(",
"$",
"votes",
"as",
"$",
"i",
"=>",
"$",
"vote",
")",
"{",
"$",
"scores",
"[",
"$",
"vote",
"]",
"+=",
"$",
"this",
"->",
"influences",
"[",
"$",
"i",
"]",
";",
"}",
"return",
"argmax",
"(",
"$",
"scores",
")",
";",
"}"
] | Decide on an anomaly outcome.
@param int[] $votes
@return int | [
"Decide",
"on",
"an",
"anomaly",
"outcome",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CommitteeMachine.php#L334-L343 |
RubixML/RubixML | src/CommitteeMachine.php | CommitteeMachine._train | public function _train(Learner $estimator, Dataset $dataset) : Learner
{
$estimator->train($dataset);
return $estimator;
} | php | public function _train(Learner $estimator, Dataset $dataset) : Learner
{
$estimator->train($dataset);
return $estimator;
} | [
"public",
"function",
"_train",
"(",
"Learner",
"$",
"estimator",
",",
"Dataset",
"$",
"dataset",
")",
":",
"Learner",
"{",
"$",
"estimator",
"->",
"train",
"(",
"$",
"dataset",
")",
";",
"return",
"$",
"estimator",
";",
"}"
] | Train an learner using a dataset and return it.
@param \Rubix\ML\Learner $estimator
@param \Rubix\ML\Datasets\Dataset $dataset
@return \Rubix\ML\Learner | [
"Train",
"an",
"learner",
"using",
"a",
"dataset",
"and",
"return",
"it",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CommitteeMachine.php#L352-L357 |
RubixML/RubixML | src/NeuralNet/Deferred.php | Deferred.result | public function result() : Matrix
{
if (!$this->result) {
$this->result = call_user_func($this->computation);
}
return $this->result;
} | php | public function result() : Matrix
{
if (!$this->result) {
$this->result = call_user_func($this->computation);
}
return $this->result;
} | [
"public",
"function",
"result",
"(",
")",
":",
"Matrix",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"result",
")",
"{",
"$",
"this",
"->",
"result",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"computation",
")",
";",
"}",
"return",
"$",
"this",
"->",
"result",
";",
"}"
] | Return the result of the computation.
@return \Rubix\Tensor\Matrix | [
"Return",
"the",
"result",
"of",
"the",
"computation",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Deferred.php#L49-L56 |
RubixML/RubixML | src/Transformers/MaxAbsoluteScaler.php | MaxAbsoluteScaler.fit | public function fit(Dataset $dataset) : void
{
$this->maxabs = [];
foreach ($dataset->types() as $column => $type) {
if ($type === DataType::CONTINUOUS) {
$this->maxabs[$column] = -INF;
}
}
$this->update($dataset);
} | php | public function fit(Dataset $dataset) : void
{
$this->maxabs = [];
foreach ($dataset->types() as $column => $type) {
if ($type === DataType::CONTINUOUS) {
$this->maxabs[$column] = -INF;
}
}
$this->update($dataset);
} | [
"public",
"function",
"fit",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"$",
"this",
"->",
"maxabs",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"dataset",
"->",
"types",
"(",
")",
"as",
"$",
"column",
"=>",
"$",
"type",
")",
"{",
"if",
"(",
"$",
"type",
"===",
"DataType",
"::",
"CONTINUOUS",
")",
"{",
"$",
"this",
"->",
"maxabs",
"[",
"$",
"column",
"]",
"=",
"-",
"INF",
";",
"}",
"}",
"$",
"this",
"->",
"update",
"(",
"$",
"dataset",
")",
";",
"}"
] | Fit the transformer to the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset | [
"Fit",
"the",
"transformer",
"to",
"the",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/MaxAbsoluteScaler.php#L55-L66 |
RubixML/RubixML | src/Transformers/MaxAbsoluteScaler.php | MaxAbsoluteScaler.update | public function update(Dataset $dataset) : void
{
if ($this->maxabs === null) {
$this->fit($dataset);
return;
}
foreach ($this->maxabs as $column => $oldMax) {
$values = $dataset->column($column);
$max = max(array_map('abs', $values));
$max = max($oldMax, $max);
$this->maxabs[$column] = $max ?: EPSILON;
}
} | php | public function update(Dataset $dataset) : void
{
if ($this->maxabs === null) {
$this->fit($dataset);
return;
}
foreach ($this->maxabs as $column => $oldMax) {
$values = $dataset->column($column);
$max = max(array_map('abs', $values));
$max = max($oldMax, $max);
$this->maxabs[$column] = $max ?: EPSILON;
}
} | [
"public",
"function",
"update",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"maxabs",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"fit",
"(",
"$",
"dataset",
")",
";",
"return",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"maxabs",
"as",
"$",
"column",
"=>",
"$",
"oldMax",
")",
"{",
"$",
"values",
"=",
"$",
"dataset",
"->",
"column",
"(",
"$",
"column",
")",
";",
"$",
"max",
"=",
"max",
"(",
"array_map",
"(",
"'abs'",
",",
"$",
"values",
")",
")",
";",
"$",
"max",
"=",
"max",
"(",
"$",
"oldMax",
",",
"$",
"max",
")",
";",
"$",
"this",
"->",
"maxabs",
"[",
"$",
"column",
"]",
"=",
"$",
"max",
"?",
":",
"EPSILON",
";",
"}",
"}"
] | Update the fitting of the transformer.
@param \Rubix\ML\Datasets\Dataset $dataset | [
"Update",
"the",
"fitting",
"of",
"the",
"transformer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/MaxAbsoluteScaler.php#L73-L90 |
RubixML/RubixML | src/Transformers/MaxAbsoluteScaler.php | MaxAbsoluteScaler.transform | public function transform(array &$samples) : void
{
if ($this->maxabs === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
foreach ($this->maxabs as $column => $maxabs) {
$sample[$column] /= $maxabs;
}
}
} | php | public function transform(array &$samples) : void
{
if ($this->maxabs === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
foreach ($this->maxabs as $column => $maxabs) {
$sample[$column] /= $maxabs;
}
}
} | [
"public",
"function",
"transform",
"(",
"array",
"&",
"$",
"samples",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"maxabs",
"===",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Transformer has not been fitted.'",
")",
";",
"}",
"foreach",
"(",
"$",
"samples",
"as",
"&",
"$",
"sample",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"maxabs",
"as",
"$",
"column",
"=>",
"$",
"maxabs",
")",
"{",
"$",
"sample",
"[",
"$",
"column",
"]",
"/=",
"$",
"maxabs",
";",
"}",
"}",
"}"
] | Transform the dataset in place.
@param array $samples
@throws \RuntimeException | [
"Transform",
"the",
"dataset",
"in",
"place",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/MaxAbsoluteScaler.php#L98-L109 |
RubixML/RubixML | src/NeuralNet/CostFunctions/HuberLoss.php | HuberLoss.compute | public function compute(Tensor $expected, Tensor $output) : float
{
return $expected->subtract($output)
->map([$this, '_compute'])->sum()->mean();
} | php | public function compute(Tensor $expected, Tensor $output) : float
{
return $expected->subtract($output)
->map([$this, '_compute'])->sum()->mean();
} | [
"public",
"function",
"compute",
"(",
"Tensor",
"$",
"expected",
",",
"Tensor",
"$",
"output",
")",
":",
"float",
"{",
"return",
"$",
"expected",
"->",
"subtract",
"(",
"$",
"output",
")",
"->",
"map",
"(",
"[",
"$",
"this",
",",
"'_compute'",
"]",
")",
"->",
"sum",
"(",
")",
"->",
"mean",
"(",
")",
";",
"}"
] | Compute the loss.
@param \Rubix\Tensor\Tensor $expected
@param \Rubix\Tensor\Tensor $output
@return float | [
"Compute",
"the",
"loss",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/CostFunctions/HuberLoss.php#L69-L73 |
RubixML/RubixML | src/NeuralNet/CostFunctions/HuberLoss.php | HuberLoss.differentiate | public function differentiate(Tensor $expected, Tensor $output) : Tensor
{
$alpha = $output->subtract($expected);
return $alpha->square()
->add($this->beta)
->pow(-0.5)
->multiply($alpha);
} | php | public function differentiate(Tensor $expected, Tensor $output) : Tensor
{
$alpha = $output->subtract($expected);
return $alpha->square()
->add($this->beta)
->pow(-0.5)
->multiply($alpha);
} | [
"public",
"function",
"differentiate",
"(",
"Tensor",
"$",
"expected",
",",
"Tensor",
"$",
"output",
")",
":",
"Tensor",
"{",
"$",
"alpha",
"=",
"$",
"output",
"->",
"subtract",
"(",
"$",
"expected",
")",
";",
"return",
"$",
"alpha",
"->",
"square",
"(",
")",
"->",
"add",
"(",
"$",
"this",
"->",
"beta",
")",
"->",
"pow",
"(",
"-",
"0.5",
")",
"->",
"multiply",
"(",
"$",
"alpha",
")",
";",
"}"
] | Calculate the gradient of the cost function with respect to the output.
@param \Rubix\Tensor\Tensor $expected
@param \Rubix\Tensor\Tensor $output
@return \Rubix\Tensor\Tensor | [
"Calculate",
"the",
"gradient",
"of",
"the",
"cost",
"function",
"with",
"respect",
"to",
"the",
"output",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/CostFunctions/HuberLoss.php#L82-L90 |
RubixML/RubixML | src/Datasets/Generators/HalfMoon.php | HalfMoon.generate | public function generate(int $n) : Dataset
{
$r = Vector::rand($n)->multiply(180)
->add($this->rotation)
->radians();
$x = $r->cos();
$y = $r->sin();
$noise = Matrix::gaussian($n, 2)
->multiply($this->noise);
$samples = Matrix::stack([$x, $y])
->transpose()
->add($noise)
->multiply($this->scale)
->add($this->center)
->asArray();
$labels = $r->degrees()->asArray();
return Labeled::quick($samples, $labels);
} | php | public function generate(int $n) : Dataset
{
$r = Vector::rand($n)->multiply(180)
->add($this->rotation)
->radians();
$x = $r->cos();
$y = $r->sin();
$noise = Matrix::gaussian($n, 2)
->multiply($this->noise);
$samples = Matrix::stack([$x, $y])
->transpose()
->add($noise)
->multiply($this->scale)
->add($this->center)
->asArray();
$labels = $r->degrees()->asArray();
return Labeled::quick($samples, $labels);
} | [
"public",
"function",
"generate",
"(",
"int",
"$",
"n",
")",
":",
"Dataset",
"{",
"$",
"r",
"=",
"Vector",
"::",
"rand",
"(",
"$",
"n",
")",
"->",
"multiply",
"(",
"180",
")",
"->",
"add",
"(",
"$",
"this",
"->",
"rotation",
")",
"->",
"radians",
"(",
")",
";",
"$",
"x",
"=",
"$",
"r",
"->",
"cos",
"(",
")",
";",
"$",
"y",
"=",
"$",
"r",
"->",
"sin",
"(",
")",
";",
"$",
"noise",
"=",
"Matrix",
"::",
"gaussian",
"(",
"$",
"n",
",",
"2",
")",
"->",
"multiply",
"(",
"$",
"this",
"->",
"noise",
")",
";",
"$",
"samples",
"=",
"Matrix",
"::",
"stack",
"(",
"[",
"$",
"x",
",",
"$",
"y",
"]",
")",
"->",
"transpose",
"(",
")",
"->",
"add",
"(",
"$",
"noise",
")",
"->",
"multiply",
"(",
"$",
"this",
"->",
"scale",
")",
"->",
"add",
"(",
"$",
"this",
"->",
"center",
")",
"->",
"asArray",
"(",
")",
";",
"$",
"labels",
"=",
"$",
"r",
"->",
"degrees",
"(",
")",
"->",
"asArray",
"(",
")",
";",
"return",
"Labeled",
"::",
"quick",
"(",
"$",
"samples",
",",
"$",
"labels",
")",
";",
"}"
] | Generate n data points.
@param int $n
@return \Rubix\ML\Datasets\Dataset | [
"Generate",
"n",
"data",
"points",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Generators/HalfMoon.php#L102-L124 |
RubixML/RubixML | src/Classifiers/GaussianNB.php | GaussianNB.train | 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);
}
}
} | php | 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);
}
}
} | [
"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",
")",
";",
"}",
"}",
"}"
] | Compute the necessary statistics to estimate a probability density for
each feature column.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Compute",
"the",
"necessary",
"statistics",
"to",
"estimate",
"a",
"probability",
"density",
"for",
"each",
"feature",
"column",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/GaussianNB.php#L207-L248 |
RubixML/RubixML | src/Classifiers/GaussianNB.php | GaussianNB.partial | 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);
}
}
} | php | 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);
}
}
} | [
"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",
")",
";",
"}",
"}",
"}"
] | Uupdate the rolling means and variances of each feature column using an
online updating algorithm.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Uupdate",
"the",
"rolling",
"means",
"and",
"variances",
"of",
"each",
"feature",
"column",
"using",
"an",
"online",
"updating",
"algorithm",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/GaussianNB.php#L257-L311 |
RubixML/RubixML | src/Classifiers/GaussianNB.php | GaussianNB.jointLogLikelihood | protected function jointLogLikelihood(array $sample) : array
{
$likelihoods = [];
foreach ($this->means as $class => $means) {
$variances = $this->variances[$class];
$likelihood = $this->priors[$class] ?? LOG_EPSILON;
foreach ($sample as $column => $feature) {
$mean = $means[$column];
$variance = $variances[$column];
$pdf = -0.5 * log(TWO_PI * $variance);
$pdf -= 0.5 * (($feature - $mean) ** 2) / $variance;
$likelihood += $pdf;
}
$likelihoods[$class] = $likelihood;
}
return $likelihoods;
} | php | protected function jointLogLikelihood(array $sample) : array
{
$likelihoods = [];
foreach ($this->means as $class => $means) {
$variances = $this->variances[$class];
$likelihood = $this->priors[$class] ?? LOG_EPSILON;
foreach ($sample as $column => $feature) {
$mean = $means[$column];
$variance = $variances[$column];
$pdf = -0.5 * log(TWO_PI * $variance);
$pdf -= 0.5 * (($feature - $mean) ** 2) / $variance;
$likelihood += $pdf;
}
$likelihoods[$class] = $likelihood;
}
return $likelihoods;
} | [
"protected",
"function",
"jointLogLikelihood",
"(",
"array",
"$",
"sample",
")",
":",
"array",
"{",
"$",
"likelihoods",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"means",
"as",
"$",
"class",
"=>",
"$",
"means",
")",
"{",
"$",
"variances",
"=",
"$",
"this",
"->",
"variances",
"[",
"$",
"class",
"]",
";",
"$",
"likelihood",
"=",
"$",
"this",
"->",
"priors",
"[",
"$",
"class",
"]",
"??",
"LOG_EPSILON",
";",
"foreach",
"(",
"$",
"sample",
"as",
"$",
"column",
"=>",
"$",
"feature",
")",
"{",
"$",
"mean",
"=",
"$",
"means",
"[",
"$",
"column",
"]",
";",
"$",
"variance",
"=",
"$",
"variances",
"[",
"$",
"column",
"]",
";",
"$",
"pdf",
"=",
"-",
"0.5",
"*",
"log",
"(",
"TWO_PI",
"*",
"$",
"variance",
")",
";",
"$",
"pdf",
"-=",
"0.5",
"*",
"(",
"(",
"$",
"feature",
"-",
"$",
"mean",
")",
"**",
"2",
")",
"/",
"$",
"variance",
";",
"$",
"likelihood",
"+=",
"$",
"pdf",
";",
"}",
"$",
"likelihoods",
"[",
"$",
"class",
"]",
"=",
"$",
"likelihood",
";",
"}",
"return",
"$",
"likelihoods",
";",
"}"
] | Calculate the joint log likelihood of a sample being a member of each class.
@param array $sample
@return array | [
"Calculate",
"the",
"joint",
"log",
"likelihood",
"of",
"a",
"sample",
"being",
"a",
"member",
"of",
"each",
"class",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/GaussianNB.php#L384-L407 |
RubixML/RubixML | src/NeuralNet/Layers/BatchNorm.php | BatchNorm.parameters | public function parameters() : Generator
{
if (!$this->beta or !$this->gamma) {
throw new RuntimeException('Layer has not been initilaized.');
}
yield $this->beta;
yield $this->gamma;
} | php | public function parameters() : Generator
{
if (!$this->beta or !$this->gamma) {
throw new RuntimeException('Layer has not been initilaized.');
}
yield $this->beta;
yield $this->gamma;
} | [
"public",
"function",
"parameters",
"(",
")",
":",
"Generator",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"beta",
"or",
"!",
"$",
"this",
"->",
"gamma",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer has not been initilaized.'",
")",
";",
"}",
"yield",
"$",
"this",
"->",
"beta",
";",
"yield",
"$",
"this",
"->",
"gamma",
";",
"}"
] | Return the parameters of the layer.
@throws \RuntimeException
@return \Generator | [
"Return",
"the",
"parameters",
"of",
"the",
"layer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/BatchNorm.php#L151-L159 |
RubixML/RubixML | src/NeuralNet/Layers/BatchNorm.php | BatchNorm.initialize | public function initialize(int $fanIn) : int
{
$fanOut = $fanIn;
$beta = $this->betaInitializer->initialize(1, $fanOut)->columnAsVector(0);
$gamma = $this->gammaInitializer->initialize(1, $fanOut)->columnAsVector(0);
$this->beta = new VectorParam($beta);
$this->gamma = new VectorParam($gamma);
$this->width = $fanOut;
return $fanOut;
} | php | public function initialize(int $fanIn) : int
{
$fanOut = $fanIn;
$beta = $this->betaInitializer->initialize(1, $fanOut)->columnAsVector(0);
$gamma = $this->gammaInitializer->initialize(1, $fanOut)->columnAsVector(0);
$this->beta = new VectorParam($beta);
$this->gamma = new VectorParam($gamma);
$this->width = $fanOut;
return $fanOut;
} | [
"public",
"function",
"initialize",
"(",
"int",
"$",
"fanIn",
")",
":",
"int",
"{",
"$",
"fanOut",
"=",
"$",
"fanIn",
";",
"$",
"beta",
"=",
"$",
"this",
"->",
"betaInitializer",
"->",
"initialize",
"(",
"1",
",",
"$",
"fanOut",
")",
"->",
"columnAsVector",
"(",
"0",
")",
";",
"$",
"gamma",
"=",
"$",
"this",
"->",
"gammaInitializer",
"->",
"initialize",
"(",
"1",
",",
"$",
"fanOut",
")",
"->",
"columnAsVector",
"(",
"0",
")",
";",
"$",
"this",
"->",
"beta",
"=",
"new",
"VectorParam",
"(",
"$",
"beta",
")",
";",
"$",
"this",
"->",
"gamma",
"=",
"new",
"VectorParam",
"(",
"$",
"gamma",
")",
";",
"$",
"this",
"->",
"width",
"=",
"$",
"fanOut",
";",
"return",
"$",
"fanOut",
";",
"}"
] | Initialize the layer with the fan in from the previous layer and return
the fan out for this layer.
@param int $fanIn
@return int | [
"Initialize",
"the",
"layer",
"with",
"the",
"fan",
"in",
"from",
"the",
"previous",
"layer",
"and",
"return",
"the",
"fan",
"out",
"for",
"this",
"layer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/BatchNorm.php#L168-L181 |
RubixML/RubixML | src/NeuralNet/Layers/BatchNorm.php | BatchNorm.forward | public function forward(Matrix $input) : Matrix
{
if (!$this->beta or !$this->gamma) {
throw new RuntimeException('Layer is not initialized.');
}
$means = $variances = [];
foreach ($input as $row) {
[$means[], $variances[]] = Stats::meanVar($row);
}
$mean = ColumnVector::quick($means);
$variance = ColumnVector::quick($variances);
if (!$this->mean or !$this->variance) {
$this->mean = $mean;
$this->variance = $variance;
}
$stdDev = $variance->clipLower(EPSILON)->sqrt();
$stdInv = $stdDev->reciprocal();
$xHat = $stdInv->multiply($input->subtract($mean));
$this->mean = $this->mean->multiply($this->decay)
->add($mean->multiply(1. - $this->decay));
$this->variance = $this->variance->multiply($this->decay)
->add($variance->multiply(1. - $this->decay));
$this->stdInv = $stdInv;
$this->xHat = $xHat;
return $this->gamma->w()->multiply($xHat)->add($this->beta->w());
} | php | public function forward(Matrix $input) : Matrix
{
if (!$this->beta or !$this->gamma) {
throw new RuntimeException('Layer is not initialized.');
}
$means = $variances = [];
foreach ($input as $row) {
[$means[], $variances[]] = Stats::meanVar($row);
}
$mean = ColumnVector::quick($means);
$variance = ColumnVector::quick($variances);
if (!$this->mean or !$this->variance) {
$this->mean = $mean;
$this->variance = $variance;
}
$stdDev = $variance->clipLower(EPSILON)->sqrt();
$stdInv = $stdDev->reciprocal();
$xHat = $stdInv->multiply($input->subtract($mean));
$this->mean = $this->mean->multiply($this->decay)
->add($mean->multiply(1. - $this->decay));
$this->variance = $this->variance->multiply($this->decay)
->add($variance->multiply(1. - $this->decay));
$this->stdInv = $stdInv;
$this->xHat = $xHat;
return $this->gamma->w()->multiply($xHat)->add($this->beta->w());
} | [
"public",
"function",
"forward",
"(",
"Matrix",
"$",
"input",
")",
":",
"Matrix",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"beta",
"or",
"!",
"$",
"this",
"->",
"gamma",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer is not initialized.'",
")",
";",
"}",
"$",
"means",
"=",
"$",
"variances",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"input",
"as",
"$",
"row",
")",
"{",
"[",
"$",
"means",
"[",
"]",
",",
"$",
"variances",
"[",
"]",
"]",
"=",
"Stats",
"::",
"meanVar",
"(",
"$",
"row",
")",
";",
"}",
"$",
"mean",
"=",
"ColumnVector",
"::",
"quick",
"(",
"$",
"means",
")",
";",
"$",
"variance",
"=",
"ColumnVector",
"::",
"quick",
"(",
"$",
"variances",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"mean",
"or",
"!",
"$",
"this",
"->",
"variance",
")",
"{",
"$",
"this",
"->",
"mean",
"=",
"$",
"mean",
";",
"$",
"this",
"->",
"variance",
"=",
"$",
"variance",
";",
"}",
"$",
"stdDev",
"=",
"$",
"variance",
"->",
"clipLower",
"(",
"EPSILON",
")",
"->",
"sqrt",
"(",
")",
";",
"$",
"stdInv",
"=",
"$",
"stdDev",
"->",
"reciprocal",
"(",
")",
";",
"$",
"xHat",
"=",
"$",
"stdInv",
"->",
"multiply",
"(",
"$",
"input",
"->",
"subtract",
"(",
"$",
"mean",
")",
")",
";",
"$",
"this",
"->",
"mean",
"=",
"$",
"this",
"->",
"mean",
"->",
"multiply",
"(",
"$",
"this",
"->",
"decay",
")",
"->",
"add",
"(",
"$",
"mean",
"->",
"multiply",
"(",
"1.",
"-",
"$",
"this",
"->",
"decay",
")",
")",
";",
"$",
"this",
"->",
"variance",
"=",
"$",
"this",
"->",
"variance",
"->",
"multiply",
"(",
"$",
"this",
"->",
"decay",
")",
"->",
"add",
"(",
"$",
"variance",
"->",
"multiply",
"(",
"1.",
"-",
"$",
"this",
"->",
"decay",
")",
")",
";",
"$",
"this",
"->",
"stdInv",
"=",
"$",
"stdInv",
";",
"$",
"this",
"->",
"xHat",
"=",
"$",
"xHat",
";",
"return",
"$",
"this",
"->",
"gamma",
"->",
"w",
"(",
")",
"->",
"multiply",
"(",
"$",
"xHat",
")",
"->",
"add",
"(",
"$",
"this",
"->",
"beta",
"->",
"w",
"(",
")",
")",
";",
"}"
] | Compute a forward pass through the layer.
@param \Rubix\Tensor\Matrix $input
@throws \RuntimeException
@return \Rubix\Tensor\Matrix | [
"Compute",
"a",
"forward",
"pass",
"through",
"the",
"layer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/BatchNorm.php#L190-L226 |
RubixML/RubixML | src/NeuralNet/Layers/BatchNorm.php | BatchNorm.infer | public function infer(Matrix $input) : Matrix
{
if (!$this->mean or !$this->variance or !$this->beta or !$this->gamma) {
throw new RuntimeException('Layer has not been initilaized.');
}
$xHat = $input->subtract($this->mean)
->divide($this->variance->clipLower(EPSILON)->sqrt());
return $this->gamma->w()->multiply($xHat)->add($this->beta->w());
} | php | public function infer(Matrix $input) : Matrix
{
if (!$this->mean or !$this->variance or !$this->beta or !$this->gamma) {
throw new RuntimeException('Layer has not been initilaized.');
}
$xHat = $input->subtract($this->mean)
->divide($this->variance->clipLower(EPSILON)->sqrt());
return $this->gamma->w()->multiply($xHat)->add($this->beta->w());
} | [
"public",
"function",
"infer",
"(",
"Matrix",
"$",
"input",
")",
":",
"Matrix",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"mean",
"or",
"!",
"$",
"this",
"->",
"variance",
"or",
"!",
"$",
"this",
"->",
"beta",
"or",
"!",
"$",
"this",
"->",
"gamma",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer has not been initilaized.'",
")",
";",
"}",
"$",
"xHat",
"=",
"$",
"input",
"->",
"subtract",
"(",
"$",
"this",
"->",
"mean",
")",
"->",
"divide",
"(",
"$",
"this",
"->",
"variance",
"->",
"clipLower",
"(",
"EPSILON",
")",
"->",
"sqrt",
"(",
")",
")",
";",
"return",
"$",
"this",
"->",
"gamma",
"->",
"w",
"(",
")",
"->",
"multiply",
"(",
"$",
"xHat",
")",
"->",
"add",
"(",
"$",
"this",
"->",
"beta",
"->",
"w",
"(",
")",
")",
";",
"}"
] | Compute an inferential pass through the layer.
@param \Rubix\Tensor\Matrix $input
@throws \RuntimeException
@return \Rubix\Tensor\Matrix | [
"Compute",
"an",
"inferential",
"pass",
"through",
"the",
"layer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/BatchNorm.php#L235-L245 |
RubixML/RubixML | src/NeuralNet/Layers/BatchNorm.php | BatchNorm.back | public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred
{
if (!$this->beta or !$this->gamma) {
throw new RuntimeException('Layer has not been initilaized.');
}
if (!$this->stdInv or !$this->xHat) {
throw new RuntimeException('Must perform forward pass before'
. ' backpropagating.');
}
$dOut = $prevGradient->result();
$dBeta = $dOut->sum();
$dGamma = $dOut->multiply($this->xHat)->sum();
$gamma = $this->gamma->w();
$optimizer->step($this->beta, $dBeta);
$optimizer->step($this->gamma, $dGamma);
$stdInv = $this->stdInv;
$xHat = $this->xHat;
unset($this->stdInv, $this->xHat);
return new Deferred(function () use ($dOut, $gamma, $stdInv, $xHat) {
$dXHat = $dOut->multiply($gamma);
$xHatSigma = $dXHat->multiply($xHat)->sum();
$dXHatSigma = $dXHat->sum();
return $dXHat->multiply($dOut->m())
->subtract($dXHatSigma)
->subtract($xHat->multiply($xHatSigma))
->multiply($stdInv->divide($dOut->m()));
});
} | php | public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred
{
if (!$this->beta or !$this->gamma) {
throw new RuntimeException('Layer has not been initilaized.');
}
if (!$this->stdInv or !$this->xHat) {
throw new RuntimeException('Must perform forward pass before'
. ' backpropagating.');
}
$dOut = $prevGradient->result();
$dBeta = $dOut->sum();
$dGamma = $dOut->multiply($this->xHat)->sum();
$gamma = $this->gamma->w();
$optimizer->step($this->beta, $dBeta);
$optimizer->step($this->gamma, $dGamma);
$stdInv = $this->stdInv;
$xHat = $this->xHat;
unset($this->stdInv, $this->xHat);
return new Deferred(function () use ($dOut, $gamma, $stdInv, $xHat) {
$dXHat = $dOut->multiply($gamma);
$xHatSigma = $dXHat->multiply($xHat)->sum();
$dXHatSigma = $dXHat->sum();
return $dXHat->multiply($dOut->m())
->subtract($dXHatSigma)
->subtract($xHat->multiply($xHatSigma))
->multiply($stdInv->divide($dOut->m()));
});
} | [
"public",
"function",
"back",
"(",
"Deferred",
"$",
"prevGradient",
",",
"Optimizer",
"$",
"optimizer",
")",
":",
"Deferred",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"beta",
"or",
"!",
"$",
"this",
"->",
"gamma",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer has not been initilaized.'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"stdInv",
"or",
"!",
"$",
"this",
"->",
"xHat",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Must perform forward pass before'",
".",
"' backpropagating.'",
")",
";",
"}",
"$",
"dOut",
"=",
"$",
"prevGradient",
"->",
"result",
"(",
")",
";",
"$",
"dBeta",
"=",
"$",
"dOut",
"->",
"sum",
"(",
")",
";",
"$",
"dGamma",
"=",
"$",
"dOut",
"->",
"multiply",
"(",
"$",
"this",
"->",
"xHat",
")",
"->",
"sum",
"(",
")",
";",
"$",
"gamma",
"=",
"$",
"this",
"->",
"gamma",
"->",
"w",
"(",
")",
";",
"$",
"optimizer",
"->",
"step",
"(",
"$",
"this",
"->",
"beta",
",",
"$",
"dBeta",
")",
";",
"$",
"optimizer",
"->",
"step",
"(",
"$",
"this",
"->",
"gamma",
",",
"$",
"dGamma",
")",
";",
"$",
"stdInv",
"=",
"$",
"this",
"->",
"stdInv",
";",
"$",
"xHat",
"=",
"$",
"this",
"->",
"xHat",
";",
"unset",
"(",
"$",
"this",
"->",
"stdInv",
",",
"$",
"this",
"->",
"xHat",
")",
";",
"return",
"new",
"Deferred",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"dOut",
",",
"$",
"gamma",
",",
"$",
"stdInv",
",",
"$",
"xHat",
")",
"{",
"$",
"dXHat",
"=",
"$",
"dOut",
"->",
"multiply",
"(",
"$",
"gamma",
")",
";",
"$",
"xHatSigma",
"=",
"$",
"dXHat",
"->",
"multiply",
"(",
"$",
"xHat",
")",
"->",
"sum",
"(",
")",
";",
"$",
"dXHatSigma",
"=",
"$",
"dXHat",
"->",
"sum",
"(",
")",
";",
"return",
"$",
"dXHat",
"->",
"multiply",
"(",
"$",
"dOut",
"->",
"m",
"(",
")",
")",
"->",
"subtract",
"(",
"$",
"dXHatSigma",
")",
"->",
"subtract",
"(",
"$",
"xHat",
"->",
"multiply",
"(",
"$",
"xHatSigma",
")",
")",
"->",
"multiply",
"(",
"$",
"stdInv",
"->",
"divide",
"(",
"$",
"dOut",
"->",
"m",
"(",
")",
")",
")",
";",
"}",
")",
";",
"}"
] | Calculate the errors and gradients of the layer and update the parameters.
@param \Rubix\ML\NeuralNet\Deferred $prevGradient
@param \Rubix\ML\NeuralNet\Optimizers\Optimizer $optimizer
@throws \RuntimeException
@return \Rubix\ML\NeuralNet\Deferred | [
"Calculate",
"the",
"errors",
"and",
"gradients",
"of",
"the",
"layer",
"and",
"update",
"the",
"parameters",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/BatchNorm.php#L255-L293 |
RubixML/RubixML | src/NeuralNet/Layers/BatchNorm.php | BatchNorm.read | public function read() : array
{
if (!$this->beta or !$this->gamma) {
throw new RuntimeException('Layer has not been initilaized.');
}
return [
'beta' => clone $this->beta,
'gamma' => clone $this->gamma,
];
} | php | public function read() : array
{
if (!$this->beta or !$this->gamma) {
throw new RuntimeException('Layer has not been initilaized.');
}
return [
'beta' => clone $this->beta,
'gamma' => clone $this->gamma,
];
} | [
"public",
"function",
"read",
"(",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"beta",
"or",
"!",
"$",
"this",
"->",
"gamma",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer has not been initilaized.'",
")",
";",
"}",
"return",
"[",
"'beta'",
"=>",
"clone",
"$",
"this",
"->",
"beta",
",",
"'gamma'",
"=>",
"clone",
"$",
"this",
"->",
"gamma",
",",
"]",
";",
"}"
] | Return the parameters of the layer in an associative array.
@throws \RuntimeException
@return array | [
"Return",
"the",
"parameters",
"of",
"the",
"layer",
"in",
"an",
"associative",
"array",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/BatchNorm.php#L301-L311 |
RubixML/RubixML | src/Classifiers/ClassificationTree.php | ClassificationTree.proba | public function proba(Dataset $dataset) : array
{
if ($this->bare()) {
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) {
$node = $this->search($sample);
$probabilities[] = $node instanceof Outcome
? array_replace($template, $node->probabilities())
: null;
}
return $probabilities;
} | php | public function proba(Dataset $dataset) : array
{
if ($this->bare()) {
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) {
$node = $this->search($sample);
$probabilities[] = $node instanceof Outcome
? array_replace($template, $node->probabilities())
: null;
}
return $probabilities;
} | [
"public",
"function",
"proba",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"array",
"{",
"if",
"(",
"$",
"this",
"->",
"bare",
"(",
")",
")",
"{",
"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",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"search",
"(",
"$",
"sample",
")",
";",
"$",
"probabilities",
"[",
"]",
"=",
"$",
"node",
"instanceof",
"Outcome",
"?",
"array_replace",
"(",
"$",
"template",
",",
"$",
"node",
"->",
"probabilities",
"(",
")",
")",
":",
"null",
";",
"}",
"return",
"$",
"probabilities",
";",
"}"
] | Estimate probabilities for each possible outcome.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \RuntimeException
@throws \InvalidArgumentException
@return array | [
"Estimate",
"probabilities",
"for",
"each",
"possible",
"outcome",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/ClassificationTree.php#L195-L217 |
RubixML/RubixML | src/Classifiers/ClassificationTree.php | ClassificationTree.terminate | protected function terminate(Labeled $dataset) : BinaryNode
{
$n = $dataset->numRows();
$labels = $dataset->labels();
$counts = array_count_values($labels);
$outcome = argmax($counts);
$probabilities = [];
foreach ($counts as $class => $count) {
$probabilities[$class] = $count / $n;
}
$impurity = 1. - (max($counts) / $n) ** 2;
return new Outcome($outcome, $probabilities, $impurity, $n);
} | php | protected function terminate(Labeled $dataset) : BinaryNode
{
$n = $dataset->numRows();
$labels = $dataset->labels();
$counts = array_count_values($labels);
$outcome = argmax($counts);
$probabilities = [];
foreach ($counts as $class => $count) {
$probabilities[$class] = $count / $n;
}
$impurity = 1. - (max($counts) / $n) ** 2;
return new Outcome($outcome, $probabilities, $impurity, $n);
} | [
"protected",
"function",
"terminate",
"(",
"Labeled",
"$",
"dataset",
")",
":",
"BinaryNode",
"{",
"$",
"n",
"=",
"$",
"dataset",
"->",
"numRows",
"(",
")",
";",
"$",
"labels",
"=",
"$",
"dataset",
"->",
"labels",
"(",
")",
";",
"$",
"counts",
"=",
"array_count_values",
"(",
"$",
"labels",
")",
";",
"$",
"outcome",
"=",
"argmax",
"(",
"$",
"counts",
")",
";",
"$",
"probabilities",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"counts",
"as",
"$",
"class",
"=>",
"$",
"count",
")",
"{",
"$",
"probabilities",
"[",
"$",
"class",
"]",
"=",
"$",
"count",
"/",
"$",
"n",
";",
"}",
"$",
"impurity",
"=",
"1.",
"-",
"(",
"max",
"(",
"$",
"counts",
")",
"/",
"$",
"n",
")",
"**",
"2",
";",
"return",
"new",
"Outcome",
"(",
"$",
"outcome",
",",
"$",
"probabilities",
",",
"$",
"impurity",
",",
"$",
"n",
")",
";",
"}"
] | Terminate the branch by selecting the class outcome with the highest
probability.
@param \Rubix\ML\Datasets\Labeled $dataset
@return \Rubix\ML\Graph\Nodes\BinaryNode | [
"Terminate",
"the",
"branch",
"by",
"selecting",
"the",
"class",
"outcome",
"with",
"the",
"highest",
"probability",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/ClassificationTree.php#L264-L283 |
RubixML/RubixML | src/Classifiers/ClassificationTree.php | ClassificationTree.splitImpurity | protected function splitImpurity(array $groups) : float
{
$n = array_sum(array_map('count', $groups));
$impurity = 0.;
foreach ($groups as $dataset) {
$k = $dataset->numRows();
if ($k < 2) {
continue 1;
}
$counts = array_count_values($dataset->labels());
$p = 0.;
foreach ($counts as $count) {
$p += 1. - ($count / $n) ** 2;
}
$impurity += ($k / $n) * $p;
}
return $impurity;
} | php | protected function splitImpurity(array $groups) : float
{
$n = array_sum(array_map('count', $groups));
$impurity = 0.;
foreach ($groups as $dataset) {
$k = $dataset->numRows();
if ($k < 2) {
continue 1;
}
$counts = array_count_values($dataset->labels());
$p = 0.;
foreach ($counts as $count) {
$p += 1. - ($count / $n) ** 2;
}
$impurity += ($k / $n) * $p;
}
return $impurity;
} | [
"protected",
"function",
"splitImpurity",
"(",
"array",
"$",
"groups",
")",
":",
"float",
"{",
"$",
"n",
"=",
"array_sum",
"(",
"array_map",
"(",
"'count'",
",",
"$",
"groups",
")",
")",
";",
"$",
"impurity",
"=",
"0.",
";",
"foreach",
"(",
"$",
"groups",
"as",
"$",
"dataset",
")",
"{",
"$",
"k",
"=",
"$",
"dataset",
"->",
"numRows",
"(",
")",
";",
"if",
"(",
"$",
"k",
"<",
"2",
")",
"{",
"continue",
"1",
";",
"}",
"$",
"counts",
"=",
"array_count_values",
"(",
"$",
"dataset",
"->",
"labels",
"(",
")",
")",
";",
"$",
"p",
"=",
"0.",
";",
"foreach",
"(",
"$",
"counts",
"as",
"$",
"count",
")",
"{",
"$",
"p",
"+=",
"1.",
"-",
"(",
"$",
"count",
"/",
"$",
"n",
")",
"**",
"2",
";",
"}",
"$",
"impurity",
"+=",
"(",
"$",
"k",
"/",
"$",
"n",
")",
"*",
"$",
"p",
";",
"}",
"return",
"$",
"impurity",
";",
"}"
] | Calculate the Gini impurity for a given split.
@param array $groups
@return float | [
"Calculate",
"the",
"Gini",
"impurity",
"for",
"a",
"given",
"split",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/ClassificationTree.php#L291-L316 |
RubixML/RubixML | src/Datasets/DataFrame.php | DataFrame.columnType | public function columnType(int $index) : int
{
if (empty($this->samples)) {
throw new RuntimeException('Cannot determine data type'
. ' of an empty data frame.');
}
$sample = reset($this->samples);
if (!isset($sample[$index])) {
throw new InvalidArgumentException("Column $index does"
. ' not exist.');
}
return DataType::determine($sample[$index]);
} | php | public function columnType(int $index) : int
{
if (empty($this->samples)) {
throw new RuntimeException('Cannot determine data type'
. ' of an empty data frame.');
}
$sample = reset($this->samples);
if (!isset($sample[$index])) {
throw new InvalidArgumentException("Column $index does"
. ' not exist.');
}
return DataType::determine($sample[$index]);
} | [
"public",
"function",
"columnType",
"(",
"int",
"$",
"index",
")",
":",
"int",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"samples",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Cannot determine data type'",
".",
"' of an empty data frame.'",
")",
";",
"}",
"$",
"sample",
"=",
"reset",
"(",
"$",
"this",
"->",
"samples",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"sample",
"[",
"$",
"index",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Column $index does\"",
".",
"' not exist.'",
")",
";",
"}",
"return",
"DataType",
"::",
"determine",
"(",
"$",
"sample",
"[",
"$",
"index",
"]",
")",
";",
"}"
] | Get the datatype for a feature column given a column index.
@param int $index
@throws \InvalidArgumentException
@throws \RuntimeException
@return int | [
"Get",
"the",
"datatype",
"for",
"a",
"feature",
"column",
"given",
"a",
"column",
"index",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/DataFrame.php#L145-L160 |
RubixML/RubixML | src/Datasets/DataFrame.php | DataFrame.columns | 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;
} | php | 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;
} | [
"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",
";",
"}"
] | Rotate the dataframe and return it in an array. i.e. rows become
columns and columns become rows.
@return array | [
"Rotate",
"the",
"dataframe",
"and",
"return",
"it",
"in",
"an",
"array",
".",
"i",
".",
"e",
".",
"rows",
"become",
"columns",
"and",
"columns",
"become",
"rows",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/DataFrame.php#L189-L204 |
RubixML/RubixML | src/Datasets/DataFrame.php | DataFrame.columnsByType | public function columnsByType(int $type) : array
{
$n = $this->numColumns();
$columns = [];
for ($i = 0; $i < $n; $i++) {
if ($this->columnType($i) === $type) {
$columns[$i] = $this->column($i);
}
}
return $columns;
} | php | public function columnsByType(int $type) : array
{
$n = $this->numColumns();
$columns = [];
for ($i = 0; $i < $n; $i++) {
if ($this->columnType($i) === $type) {
$columns[$i] = $this->column($i);
}
}
return $columns;
} | [
"public",
"function",
"columnsByType",
"(",
"int",
"$",
"type",
")",
":",
"array",
"{",
"$",
"n",
"=",
"$",
"this",
"->",
"numColumns",
"(",
")",
";",
"$",
"columns",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"n",
";",
"$",
"i",
"++",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"columnType",
"(",
"$",
"i",
")",
"===",
"$",
"type",
")",
"{",
"$",
"columns",
"[",
"$",
"i",
"]",
"=",
"$",
"this",
"->",
"column",
"(",
"$",
"i",
")",
";",
"}",
"}",
"return",
"$",
"columns",
";",
"}"
] | Return the columns that match a given data type.
@param int $type
@return array | [
"Return",
"the",
"columns",
"that",
"match",
"a",
"given",
"data",
"type",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/DataFrame.php#L212-L225 |
RubixML/RubixML | src/Transformers/StopWordFilter.php | StopWordFilter.transform | public function transform(array &$samples) : void
{
foreach ($samples as &$sample) {
foreach ($sample as &$feature) {
if (is_string($feature)) {
$feature = preg_replace($this->stopWords, '', $feature);
}
}
}
} | php | public function transform(array &$samples) : void
{
foreach ($samples as &$sample) {
foreach ($sample as &$feature) {
if (is_string($feature)) {
$feature = preg_replace($this->stopWords, '', $feature);
}
}
}
} | [
"public",
"function",
"transform",
"(",
"array",
"&",
"$",
"samples",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"samples",
"as",
"&",
"$",
"sample",
")",
"{",
"foreach",
"(",
"$",
"sample",
"as",
"&",
"$",
"feature",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"feature",
")",
")",
"{",
"$",
"feature",
"=",
"preg_replace",
"(",
"$",
"this",
"->",
"stopWords",
",",
"''",
",",
"$",
"feature",
")",
";",
"}",
"}",
"}",
"}"
] | Transform the dataset in place.
@param array $samples | [
"Transform",
"the",
"dataset",
"in",
"place",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/StopWordFilter.php#L50-L59 |
RubixML/RubixML | src/Transformers/PolynomialExpander.php | PolynomialExpander.transform | public function transform(array &$samples) : void
{
foreach ($samples as &$sample) {
$vector = [];
foreach ($sample as $feature) {
for ($i = 1; $i <= $this->degree; $i++) {
$vector[] = $feature ** $i;
}
}
$sample = $vector;
}
} | php | public function transform(array &$samples) : void
{
foreach ($samples as &$sample) {
$vector = [];
foreach ($sample as $feature) {
for ($i = 1; $i <= $this->degree; $i++) {
$vector[] = $feature ** $i;
}
}
$sample = $vector;
}
} | [
"public",
"function",
"transform",
"(",
"array",
"&",
"$",
"samples",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"samples",
"as",
"&",
"$",
"sample",
")",
"{",
"$",
"vector",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"sample",
"as",
"$",
"feature",
")",
"{",
"for",
"(",
"$",
"i",
"=",
"1",
";",
"$",
"i",
"<=",
"$",
"this",
"->",
"degree",
";",
"$",
"i",
"++",
")",
"{",
"$",
"vector",
"[",
"]",
"=",
"$",
"feature",
"**",
"$",
"i",
";",
"}",
"}",
"$",
"sample",
"=",
"$",
"vector",
";",
"}",
"}"
] | Transform the dataset in place.
@param array $samples | [
"Transform",
"the",
"dataset",
"in",
"place",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/PolynomialExpander.php#L49-L62 |
RubixML/RubixML | src/NeuralNet/Layers/Continuous.php | Continuous.parameters | public function parameters() : Generator
{
if (!$this->weights or !$this->biases) {
throw new RuntimeException('Layer is not initialized');
}
yield $this->weights;
yield $this->biases;
} | php | public function parameters() : Generator
{
if (!$this->weights or !$this->biases) {
throw new RuntimeException('Layer is not initialized');
}
yield $this->weights;
yield $this->biases;
} | [
"public",
"function",
"parameters",
"(",
")",
":",
"Generator",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"weights",
"or",
"!",
"$",
"this",
"->",
"biases",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer is not initialized'",
")",
";",
"}",
"yield",
"$",
"this",
"->",
"weights",
";",
"yield",
"$",
"this",
"->",
"biases",
";",
"}"
] | Return the parameters of the layer.
@throws \RuntimeException
@return \Generator | [
"Return",
"the",
"parameters",
"of",
"the",
"layer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/Continuous.php#L128-L136 |
RubixML/RubixML | src/NeuralNet/Layers/Continuous.php | Continuous.forward | public function forward(Matrix $input) : Matrix
{
if (!$this->weights or !$this->biases) {
throw new RuntimeException('Layer is not initialized');
}
$this->input = $input;
$this->z = $this->weights->w()->matmul($input)
->add($this->biases->w());
return $this->z;
} | php | public function forward(Matrix $input) : Matrix
{
if (!$this->weights or !$this->biases) {
throw new RuntimeException('Layer is not initialized');
}
$this->input = $input;
$this->z = $this->weights->w()->matmul($input)
->add($this->biases->w());
return $this->z;
} | [
"public",
"function",
"forward",
"(",
"Matrix",
"$",
"input",
")",
":",
"Matrix",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"weights",
"or",
"!",
"$",
"this",
"->",
"biases",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer is not initialized'",
")",
";",
"}",
"$",
"this",
"->",
"input",
"=",
"$",
"input",
";",
"$",
"this",
"->",
"z",
"=",
"$",
"this",
"->",
"weights",
"->",
"w",
"(",
")",
"->",
"matmul",
"(",
"$",
"input",
")",
"->",
"add",
"(",
"$",
"this",
"->",
"biases",
"->",
"w",
"(",
")",
")",
";",
"return",
"$",
"this",
"->",
"z",
";",
"}"
] | Compute a forward pass through the layer.
@param \Rubix\Tensor\Matrix $input
@throws \RuntimeException
@return \Rubix\Tensor\Matrix | [
"Compute",
"a",
"forward",
"pass",
"through",
"the",
"layer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/Continuous.php#L165-L177 |
RubixML/RubixML | src/NeuralNet/Layers/Continuous.php | Continuous.back | public function back(array $labels, Optimizer $optimizer) : array
{
if (!$this->weights or !$this->biases) {
throw new RuntimeException('Layer is not initialized');
}
if (!$this->input or !$this->z) {
throw new RuntimeException('Must perform forward pass before'
. ' backpropagating.');
}
$expected = Vector::quick($labels);
$penalties = $this->weights->w()->sum()
->multiply($this->alpha);
$dL = $this->costFn
->differentiate($expected, $this->z)
->add($penalties)
->divide($this->z->n());
$dW = $dL->matmul($this->input->transpose());
$dB = $dL->sum();
$w = $this->weights->w();
$optimizer->step($this->weights, $dW);
$optimizer->step($this->biases, $dB);
$loss = $this->costFn->compute($expected, $this->z);
$gradient = new Deferred(function () use ($w, $dL) {
return $w->transpose()->matmul($dL);
});
unset($this->input, $this->z);
return [$gradient, $loss];
} | php | public function back(array $labels, Optimizer $optimizer) : array
{
if (!$this->weights or !$this->biases) {
throw new RuntimeException('Layer is not initialized');
}
if (!$this->input or !$this->z) {
throw new RuntimeException('Must perform forward pass before'
. ' backpropagating.');
}
$expected = Vector::quick($labels);
$penalties = $this->weights->w()->sum()
->multiply($this->alpha);
$dL = $this->costFn
->differentiate($expected, $this->z)
->add($penalties)
->divide($this->z->n());
$dW = $dL->matmul($this->input->transpose());
$dB = $dL->sum();
$w = $this->weights->w();
$optimizer->step($this->weights, $dW);
$optimizer->step($this->biases, $dB);
$loss = $this->costFn->compute($expected, $this->z);
$gradient = new Deferred(function () use ($w, $dL) {
return $w->transpose()->matmul($dL);
});
unset($this->input, $this->z);
return [$gradient, $loss];
} | [
"public",
"function",
"back",
"(",
"array",
"$",
"labels",
",",
"Optimizer",
"$",
"optimizer",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"weights",
"or",
"!",
"$",
"this",
"->",
"biases",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer is not initialized'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"input",
"or",
"!",
"$",
"this",
"->",
"z",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Must perform forward pass before'",
".",
"' backpropagating.'",
")",
";",
"}",
"$",
"expected",
"=",
"Vector",
"::",
"quick",
"(",
"$",
"labels",
")",
";",
"$",
"penalties",
"=",
"$",
"this",
"->",
"weights",
"->",
"w",
"(",
")",
"->",
"sum",
"(",
")",
"->",
"multiply",
"(",
"$",
"this",
"->",
"alpha",
")",
";",
"$",
"dL",
"=",
"$",
"this",
"->",
"costFn",
"->",
"differentiate",
"(",
"$",
"expected",
",",
"$",
"this",
"->",
"z",
")",
"->",
"add",
"(",
"$",
"penalties",
")",
"->",
"divide",
"(",
"$",
"this",
"->",
"z",
"->",
"n",
"(",
")",
")",
";",
"$",
"dW",
"=",
"$",
"dL",
"->",
"matmul",
"(",
"$",
"this",
"->",
"input",
"->",
"transpose",
"(",
")",
")",
";",
"$",
"dB",
"=",
"$",
"dL",
"->",
"sum",
"(",
")",
";",
"$",
"w",
"=",
"$",
"this",
"->",
"weights",
"->",
"w",
"(",
")",
";",
"$",
"optimizer",
"->",
"step",
"(",
"$",
"this",
"->",
"weights",
",",
"$",
"dW",
")",
";",
"$",
"optimizer",
"->",
"step",
"(",
"$",
"this",
"->",
"biases",
",",
"$",
"dB",
")",
";",
"$",
"loss",
"=",
"$",
"this",
"->",
"costFn",
"->",
"compute",
"(",
"$",
"expected",
",",
"$",
"this",
"->",
"z",
")",
";",
"$",
"gradient",
"=",
"new",
"Deferred",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"w",
",",
"$",
"dL",
")",
"{",
"return",
"$",
"w",
"->",
"transpose",
"(",
")",
"->",
"matmul",
"(",
"$",
"dL",
")",
";",
"}",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"input",
",",
"$",
"this",
"->",
"z",
")",
";",
"return",
"[",
"$",
"gradient",
",",
"$",
"loss",
"]",
";",
"}"
] | Calculate the gradients for each output neuron and update.
@param array $labels
@param \Rubix\ML\NeuralNet\Optimizers\Optimizer $optimizer
@throws \RuntimeException
@return array | [
"Calculate",
"the",
"gradients",
"for",
"each",
"output",
"neuron",
"and",
"update",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/Continuous.php#L204-L242 |
RubixML/RubixML | src/NeuralNet/Optimizers/Momentum.php | Momentum.step | public function step(Parameter $param, Tensor $gradient) : void
{
$velocity = $this->cache[$param->id()];
$velocity = $gradient->multiply($this->rate)
->add($velocity->multiply($this->decay));
$this->cache[$param->id()] = $velocity;
$param->update($velocity);
} | php | public function step(Parameter $param, Tensor $gradient) : void
{
$velocity = $this->cache[$param->id()];
$velocity = $gradient->multiply($this->rate)
->add($velocity->multiply($this->decay));
$this->cache[$param->id()] = $velocity;
$param->update($velocity);
} | [
"public",
"function",
"step",
"(",
"Parameter",
"$",
"param",
",",
"Tensor",
"$",
"gradient",
")",
":",
"void",
"{",
"$",
"velocity",
"=",
"$",
"this",
"->",
"cache",
"[",
"$",
"param",
"->",
"id",
"(",
")",
"]",
";",
"$",
"velocity",
"=",
"$",
"gradient",
"->",
"multiply",
"(",
"$",
"this",
"->",
"rate",
")",
"->",
"add",
"(",
"$",
"velocity",
"->",
"multiply",
"(",
"$",
"this",
"->",
"decay",
")",
")",
";",
"$",
"this",
"->",
"cache",
"[",
"$",
"param",
"->",
"id",
"(",
")",
"]",
"=",
"$",
"velocity",
";",
"$",
"param",
"->",
"update",
"(",
"$",
"velocity",
")",
";",
"}"
] | Take a step of gradient descent for a given parameter.
@param \Rubix\ML\NeuralNet\Parameters\Parameter $param
@param \Rubix\Tensor\Tensor $gradient | [
"Take",
"a",
"step",
"of",
"gradient",
"descent",
"for",
"a",
"given",
"parameter",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Optimizers/Momentum.php#L86-L96 |
RubixML/RubixML | src/Transformers/VarianceThresholdFilter.php | VarianceThresholdFilter.fit | public function fit(Dataset $dataset) : void
{
$columns = $dataset->columnsByType(DataType::CONTINUOUS);
$this->selected = [];
foreach ($columns as $column => $values) {
if (Stats::variance($values) <= $this->threshold) {
continue 1;
}
$this->selected[$column] = true;
}
} | php | public function fit(Dataset $dataset) : void
{
$columns = $dataset->columnsByType(DataType::CONTINUOUS);
$this->selected = [];
foreach ($columns as $column => $values) {
if (Stats::variance($values) <= $this->threshold) {
continue 1;
}
$this->selected[$column] = true;
}
} | [
"public",
"function",
"fit",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"$",
"columns",
"=",
"$",
"dataset",
"->",
"columnsByType",
"(",
"DataType",
"::",
"CONTINUOUS",
")",
";",
"$",
"this",
"->",
"selected",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"column",
"=>",
"$",
"values",
")",
"{",
"if",
"(",
"Stats",
"::",
"variance",
"(",
"$",
"values",
")",
"<=",
"$",
"this",
"->",
"threshold",
")",
"{",
"continue",
"1",
";",
"}",
"$",
"this",
"->",
"selected",
"[",
"$",
"column",
"]",
"=",
"true",
";",
"}",
"}"
] | Fit the transformer to the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset | [
"Fit",
"the",
"transformer",
"to",
"the",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/VarianceThresholdFilter.php#L78-L91 |
RubixML/RubixML | src/Transformers/VarianceThresholdFilter.php | VarianceThresholdFilter.transform | public function transform(array &$samples) : void
{
if ($this->selected === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
$sample = array_intersect_key($sample, $this->selected);
}
} | php | public function transform(array &$samples) : void
{
if ($this->selected === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
$sample = array_intersect_key($sample, $this->selected);
}
} | [
"public",
"function",
"transform",
"(",
"array",
"&",
"$",
"samples",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"selected",
"===",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Transformer has not been fitted.'",
")",
";",
"}",
"foreach",
"(",
"$",
"samples",
"as",
"&",
"$",
"sample",
")",
"{",
"$",
"sample",
"=",
"array_intersect_key",
"(",
"$",
"sample",
",",
"$",
"this",
"->",
"selected",
")",
";",
"}",
"}"
] | Transform the dataset in place.
@param array $samples
@throws \RuntimeException | [
"Transform",
"the",
"dataset",
"in",
"place",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/VarianceThresholdFilter.php#L99-L108 |
RubixML/RubixML | src/Classifiers/LogisticRegression.php | LogisticRegression.partial | 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();
$randomize = $n > $this->batchSize ? true : false;
$previous = INF;
for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
if ($randomize) {
$dataset->randomize();
}
$batches = $dataset->batch($this->batchSize);
$loss = 0.;
foreach ($batches as $batch) {
$loss += $this->network->roundtrip($batch);
}
$loss /= $n;
$this->steps[] = $loss;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete, loss=$loss");
}
if (is_nan($loss)) {
break 1;
}
if (abs($previous - $loss) < $this->minChange) {
break 1;
}
$previous = $loss;
}
if ($this->logger) {
$this->logger->info('Training complete');
}
} | php | 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();
$randomize = $n > $this->batchSize ? true : false;
$previous = INF;
for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
if ($randomize) {
$dataset->randomize();
}
$batches = $dataset->batch($this->batchSize);
$loss = 0.;
foreach ($batches as $batch) {
$loss += $this->network->roundtrip($batch);
}
$loss /= $n;
$this->steps[] = $loss;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete, loss=$loss");
}
if (is_nan($loss)) {
break 1;
}
if (abs($previous - $loss) < $this->minChange) {
break 1;
}
$previous = $loss;
}
if ($this->logger) {
$this->logger->info('Training complete');
}
} | [
"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",
"(",
")",
";",
"$",
"randomize",
"=",
"$",
"n",
">",
"$",
"this",
"->",
"batchSize",
"?",
"true",
":",
"false",
";",
"$",
"previous",
"=",
"INF",
";",
"for",
"(",
"$",
"epoch",
"=",
"1",
";",
"$",
"epoch",
"<=",
"$",
"this",
"->",
"epochs",
";",
"$",
"epoch",
"++",
")",
"{",
"if",
"(",
"$",
"randomize",
")",
"{",
"$",
"dataset",
"->",
"randomize",
"(",
")",
";",
"}",
"$",
"batches",
"=",
"$",
"dataset",
"->",
"batch",
"(",
"$",
"this",
"->",
"batchSize",
")",
";",
"$",
"loss",
"=",
"0.",
";",
"foreach",
"(",
"$",
"batches",
"as",
"$",
"batch",
")",
"{",
"$",
"loss",
"+=",
"$",
"this",
"->",
"network",
"->",
"roundtrip",
"(",
"$",
"batch",
")",
";",
"}",
"$",
"loss",
"/=",
"$",
"n",
";",
"$",
"this",
"->",
"steps",
"[",
"]",
"=",
"$",
"loss",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"\"Epoch $epoch complete, loss=$loss\"",
")",
";",
"}",
"if",
"(",
"is_nan",
"(",
"$",
"loss",
")",
")",
"{",
"break",
"1",
";",
"}",
"if",
"(",
"abs",
"(",
"$",
"previous",
"-",
"$",
"loss",
")",
"<",
"$",
"this",
"->",
"minChange",
")",
"{",
"break",
"1",
";",
"}",
"$",
"previous",
"=",
"$",
"loss",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Training complete'",
")",
";",
"}",
"}"
] | Perform mini-batch gradient descent with given optimizer over the training
set and update the input weights accordingly.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Perform",
"mini",
"-",
"batch",
"gradient",
"descent",
"with",
"given",
"optimizer",
"over",
"the",
"training",
"set",
"and",
"update",
"the",
"input",
"weights",
"accordingly",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/LogisticRegression.php#L237-L304 |
RubixML/RubixML | src/Classifiers/LogisticRegression.php | LogisticRegression.proba | 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();
$y = $this->network->infer($xT)->row(0);
[$classA, $classB] = $this->classes;
$probabilities = [];
foreach ($y as $activation) {
$probabilities[] = [
$classA => 1. - $activation,
$classB => $activation,
];
}
return $probabilities;
} | php | 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();
$y = $this->network->infer($xT)->row(0);
[$classA, $classB] = $this->classes;
$probabilities = [];
foreach ($y as $activation) {
$probabilities[] = [
$classA => 1. - $activation,
$classB => $activation,
];
}
return $probabilities;
} | [
"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",
"(",
")",
";",
"$",
"y",
"=",
"$",
"this",
"->",
"network",
"->",
"infer",
"(",
"$",
"xT",
")",
"->",
"row",
"(",
"0",
")",
";",
"[",
"$",
"classA",
",",
"$",
"classB",
"]",
"=",
"$",
"this",
"->",
"classes",
";",
"$",
"probabilities",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"y",
"as",
"$",
"activation",
")",
"{",
"$",
"probabilities",
"[",
"]",
"=",
"[",
"$",
"classA",
"=>",
"1.",
"-",
"$",
"activation",
",",
"$",
"classB",
"=>",
"$",
"activation",
",",
"]",
";",
"}",
"return",
"$",
"probabilities",
";",
"}"
] | Estimate probabilities for each possible outcome.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException
@throws \RuntimeException
@return array | [
"Estimate",
"probabilities",
"for",
"each",
"possible",
"outcome",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/LogisticRegression.php#L325-L350 |
RubixML/RubixML | src/Kernels/Distance/Diagonal.php | Diagonal.compute | public function compute(array $a, array $b) : float
{
$deltas = [];
foreach ($a as $i => $value) {
$deltas[] = abs($value - $b[$i]);
}
return max($deltas);
} | php | public function compute(array $a, array $b) : float
{
$deltas = [];
foreach ($a as $i => $value) {
$deltas[] = abs($value - $b[$i]);
}
return max($deltas);
} | [
"public",
"function",
"compute",
"(",
"array",
"$",
"a",
",",
"array",
"$",
"b",
")",
":",
"float",
"{",
"$",
"deltas",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"a",
"as",
"$",
"i",
"=>",
"$",
"value",
")",
"{",
"$",
"deltas",
"[",
"]",
"=",
"abs",
"(",
"$",
"value",
"-",
"$",
"b",
"[",
"$",
"i",
"]",
")",
";",
"}",
"return",
"max",
"(",
"$",
"deltas",
")",
";",
"}"
] | Compute the distance between two vectors.
@param array $a
@param array $b
@return float | [
"Compute",
"the",
"distance",
"between",
"two",
"vectors",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Kernels/Distance/Diagonal.php#L25-L34 |
RubixML/RubixML | src/Transformers/NumericStringConverter.php | NumericStringConverter.transform | public function transform(array &$samples) : void
{
foreach ($samples as &$sample) {
foreach ($sample as &$feature) {
if (is_string($feature) and is_numeric($feature)) {
$feature = (int) $feature == $feature
? (int) $feature
: (float) $feature;
}
}
}
} | php | public function transform(array &$samples) : void
{
foreach ($samples as &$sample) {
foreach ($sample as &$feature) {
if (is_string($feature) and is_numeric($feature)) {
$feature = (int) $feature == $feature
? (int) $feature
: (float) $feature;
}
}
}
} | [
"public",
"function",
"transform",
"(",
"array",
"&",
"$",
"samples",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"samples",
"as",
"&",
"$",
"sample",
")",
"{",
"foreach",
"(",
"$",
"sample",
"as",
"&",
"$",
"feature",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"feature",
")",
"and",
"is_numeric",
"(",
"$",
"feature",
")",
")",
"{",
"$",
"feature",
"=",
"(",
"int",
")",
"$",
"feature",
"==",
"$",
"feature",
"?",
"(",
"int",
")",
"$",
"feature",
":",
"(",
"float",
")",
"$",
"feature",
";",
"}",
"}",
"}",
"}"
] | Transform the dataset in place.
@param array $samples | [
"Transform",
"the",
"dataset",
"in",
"place",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/NumericStringConverter.php#L23-L34 |
RubixML/RubixML | src/Classifiers/MultiLayerPerceptron.php | MultiLayerPerceptron.proba | 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;
} | php | 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;
} | [
"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",
";",
"}"
] | Estimate probabilities for each possible outcome.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException
@throws \RuntimeException
@return array | [
"Estimate",
"probabilities",
"for",
"each",
"possible",
"outcome",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/MultiLayerPerceptron.php#L462-L482 |
RubixML/RubixML | src/Transformers/L1Normalizer.php | L1Normalizer.transform | public function transform(array &$samples) : void
{
foreach ($samples as &$sample) {
$norm = array_sum(array_map('abs', $sample)) ?: EPSILON;
foreach ($sample as &$feature) {
$feature /= $norm;
}
}
} | php | public function transform(array &$samples) : void
{
foreach ($samples as &$sample) {
$norm = array_sum(array_map('abs', $sample)) ?: EPSILON;
foreach ($sample as &$feature) {
$feature /= $norm;
}
}
} | [
"public",
"function",
"transform",
"(",
"array",
"&",
"$",
"samples",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"samples",
"as",
"&",
"$",
"sample",
")",
"{",
"$",
"norm",
"=",
"array_sum",
"(",
"array_map",
"(",
"'abs'",
",",
"$",
"sample",
")",
")",
"?",
":",
"EPSILON",
";",
"foreach",
"(",
"$",
"sample",
"as",
"&",
"$",
"feature",
")",
"{",
"$",
"feature",
"/=",
"$",
"norm",
";",
"}",
"}",
"}"
] | Transform the dataset in place.
@param array $samples | [
"Transform",
"the",
"dataset",
"in",
"place",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/L1Normalizer.php#L24-L33 |
RubixML/RubixML | src/Regressors/GradientBoost.php | GradientBoost.compatibility | public function compatibility() : array
{
$compatibility = array_intersect($this->base->compatibility(), $this->booster->compatibility());
return array_values($compatibility);
} | php | public function compatibility() : array
{
$compatibility = array_intersect($this->base->compatibility(), $this->booster->compatibility());
return array_values($compatibility);
} | [
"public",
"function",
"compatibility",
"(",
")",
":",
"array",
"{",
"$",
"compatibility",
"=",
"array_intersect",
"(",
"$",
"this",
"->",
"base",
"->",
"compatibility",
"(",
")",
",",
"$",
"this",
"->",
"booster",
"->",
"compatibility",
"(",
")",
")",
";",
"return",
"array_values",
"(",
"$",
"compatibility",
")",
";",
"}"
] | Return the data types that this estimator is compatible with.
@return int[] | [
"Return",
"the",
"data",
"types",
"that",
"this",
"estimator",
"is",
"compatible",
"with",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/GradientBoost.php#L192-L197 |
RubixML/RubixML | src/Regressors/GradientBoost.php | GradientBoost.train | public function train(Dataset $dataset) : void
{
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([
'booster' => $this->booster,
'rate' => $this->rate,
'estimators' => $this->estimators,
'ratio' => $this->ratio,
'min_change' => $this->minChange,
'tolerance' => $this->tolerance,
'base' => $this->base,
]));
}
$n = $dataset->numRows();
$p = (int) round($this->ratio * $n);
if ($this->logger) {
$this->logger->info('Training '
. Params::shortName($this->base) . ' base estimator');
}
$this->base->train($dataset);
$predictions = $this->base->predict($dataset);
$yHat = [];
foreach ($predictions as $i => $prediction) {
$yHat[] = $dataset->label($i) - $prediction;
}
$residual = Labeled::quick($dataset->samples(), $yHat);
if ($this->logger) {
$this->logger->info("Boosting with $this->estimators "
. Params::shortName($this->booster)
. ($this->estimators > 1 ? 's' : ''));
}
$this->ensemble = $this->steps = [];
$previous = INF;
for ($epoch = 1; $epoch <= $this->estimators; $epoch++) {
$booster = clone $this->booster;
$subset = $residual->randomize()->head($p);
$booster->train($subset);
$predictions = $booster->predict($residual);
$labels = $residual->labels();
$loss = 0.;
foreach ($predictions as $i => $prediction) {
$label = $labels[$i];
$loss += ($label - $prediction) ** 2;
$yHat[$i] = $label - ($this->rate * $prediction);
}
$loss /= $n;
$this->ensemble[] = $booster;
$this->steps[] = $loss;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete, loss=$loss");
}
if (is_nan($loss)) {
break 1;
}
if (abs($previous - $loss) < $this->minChange) {
break 1;
}
if ($loss < $this->tolerance) {
break 1;
}
$residual = Labeled::quick($residual->samples(), $yHat);
$previous = $loss;
}
if ($this->logger) {
$this->logger->info('Training complete');
}
} | php | public function train(Dataset $dataset) : void
{
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([
'booster' => $this->booster,
'rate' => $this->rate,
'estimators' => $this->estimators,
'ratio' => $this->ratio,
'min_change' => $this->minChange,
'tolerance' => $this->tolerance,
'base' => $this->base,
]));
}
$n = $dataset->numRows();
$p = (int) round($this->ratio * $n);
if ($this->logger) {
$this->logger->info('Training '
. Params::shortName($this->base) . ' base estimator');
}
$this->base->train($dataset);
$predictions = $this->base->predict($dataset);
$yHat = [];
foreach ($predictions as $i => $prediction) {
$yHat[] = $dataset->label($i) - $prediction;
}
$residual = Labeled::quick($dataset->samples(), $yHat);
if ($this->logger) {
$this->logger->info("Boosting with $this->estimators "
. Params::shortName($this->booster)
. ($this->estimators > 1 ? 's' : ''));
}
$this->ensemble = $this->steps = [];
$previous = INF;
for ($epoch = 1; $epoch <= $this->estimators; $epoch++) {
$booster = clone $this->booster;
$subset = $residual->randomize()->head($p);
$booster->train($subset);
$predictions = $booster->predict($residual);
$labels = $residual->labels();
$loss = 0.;
foreach ($predictions as $i => $prediction) {
$label = $labels[$i];
$loss += ($label - $prediction) ** 2;
$yHat[$i] = $label - ($this->rate * $prediction);
}
$loss /= $n;
$this->ensemble[] = $booster;
$this->steps[] = $loss;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete, loss=$loss");
}
if (is_nan($loss)) {
break 1;
}
if (abs($previous - $loss) < $this->minChange) {
break 1;
}
if ($loss < $this->tolerance) {
break 1;
}
$residual = Labeled::quick($residual->samples(), $yHat);
$previous = $loss;
}
if ($this->logger) {
$this->logger->info('Training complete');
}
} | [
"public",
"function",
"train",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"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",
"(",
"[",
"'booster'",
"=>",
"$",
"this",
"->",
"booster",
",",
"'rate'",
"=>",
"$",
"this",
"->",
"rate",
",",
"'estimators'",
"=>",
"$",
"this",
"->",
"estimators",
",",
"'ratio'",
"=>",
"$",
"this",
"->",
"ratio",
",",
"'min_change'",
"=>",
"$",
"this",
"->",
"minChange",
",",
"'tolerance'",
"=>",
"$",
"this",
"->",
"tolerance",
",",
"'base'",
"=>",
"$",
"this",
"->",
"base",
",",
"]",
")",
")",
";",
"}",
"$",
"n",
"=",
"$",
"dataset",
"->",
"numRows",
"(",
")",
";",
"$",
"p",
"=",
"(",
"int",
")",
"round",
"(",
"$",
"this",
"->",
"ratio",
"*",
"$",
"n",
")",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Training '",
".",
"Params",
"::",
"shortName",
"(",
"$",
"this",
"->",
"base",
")",
".",
"' base estimator'",
")",
";",
"}",
"$",
"this",
"->",
"base",
"->",
"train",
"(",
"$",
"dataset",
")",
";",
"$",
"predictions",
"=",
"$",
"this",
"->",
"base",
"->",
"predict",
"(",
"$",
"dataset",
")",
";",
"$",
"yHat",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"predictions",
"as",
"$",
"i",
"=>",
"$",
"prediction",
")",
"{",
"$",
"yHat",
"[",
"]",
"=",
"$",
"dataset",
"->",
"label",
"(",
"$",
"i",
")",
"-",
"$",
"prediction",
";",
"}",
"$",
"residual",
"=",
"Labeled",
"::",
"quick",
"(",
"$",
"dataset",
"->",
"samples",
"(",
")",
",",
"$",
"yHat",
")",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"\"Boosting with $this->estimators \"",
".",
"Params",
"::",
"shortName",
"(",
"$",
"this",
"->",
"booster",
")",
".",
"(",
"$",
"this",
"->",
"estimators",
">",
"1",
"?",
"'s'",
":",
"''",
")",
")",
";",
"}",
"$",
"this",
"->",
"ensemble",
"=",
"$",
"this",
"->",
"steps",
"=",
"[",
"]",
";",
"$",
"previous",
"=",
"INF",
";",
"for",
"(",
"$",
"epoch",
"=",
"1",
";",
"$",
"epoch",
"<=",
"$",
"this",
"->",
"estimators",
";",
"$",
"epoch",
"++",
")",
"{",
"$",
"booster",
"=",
"clone",
"$",
"this",
"->",
"booster",
";",
"$",
"subset",
"=",
"$",
"residual",
"->",
"randomize",
"(",
")",
"->",
"head",
"(",
"$",
"p",
")",
";",
"$",
"booster",
"->",
"train",
"(",
"$",
"subset",
")",
";",
"$",
"predictions",
"=",
"$",
"booster",
"->",
"predict",
"(",
"$",
"residual",
")",
";",
"$",
"labels",
"=",
"$",
"residual",
"->",
"labels",
"(",
")",
";",
"$",
"loss",
"=",
"0.",
";",
"foreach",
"(",
"$",
"predictions",
"as",
"$",
"i",
"=>",
"$",
"prediction",
")",
"{",
"$",
"label",
"=",
"$",
"labels",
"[",
"$",
"i",
"]",
";",
"$",
"loss",
"+=",
"(",
"$",
"label",
"-",
"$",
"prediction",
")",
"**",
"2",
";",
"$",
"yHat",
"[",
"$",
"i",
"]",
"=",
"$",
"label",
"-",
"(",
"$",
"this",
"->",
"rate",
"*",
"$",
"prediction",
")",
";",
"}",
"$",
"loss",
"/=",
"$",
"n",
";",
"$",
"this",
"->",
"ensemble",
"[",
"]",
"=",
"$",
"booster",
";",
"$",
"this",
"->",
"steps",
"[",
"]",
"=",
"$",
"loss",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"\"Epoch $epoch complete, loss=$loss\"",
")",
";",
"}",
"if",
"(",
"is_nan",
"(",
"$",
"loss",
")",
")",
"{",
"break",
"1",
";",
"}",
"if",
"(",
"abs",
"(",
"$",
"previous",
"-",
"$",
"loss",
")",
"<",
"$",
"this",
"->",
"minChange",
")",
"{",
"break",
"1",
";",
"}",
"if",
"(",
"$",
"loss",
"<",
"$",
"this",
"->",
"tolerance",
")",
"{",
"break",
"1",
";",
"}",
"$",
"residual",
"=",
"Labeled",
"::",
"quick",
"(",
"$",
"residual",
"->",
"samples",
"(",
")",
",",
"$",
"yHat",
")",
";",
"$",
"previous",
"=",
"$",
"loss",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Training complete'",
")",
";",
"}",
"}"
] | Train the estimator with a dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Train",
"the",
"estimator",
"with",
"a",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/GradientBoost.php#L225-L325 |
RubixML/RubixML | src/Regressors/GradientBoost.php | GradientBoost.predict | 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;
} | php | 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;
} | [
"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",
";",
"}"
] | Make a prediction from a dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \RuntimeException
@throws \InvalidArgumentException
@return array | [
"Make",
"a",
"prediction",
"from",
"a",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/GradientBoost.php#L335-L352 |
RubixML/RubixML | src/Kernels/Distance/Canberra.php | Canberra.compute | public function compute(array $a, array $b) : float
{
$distance = 0.;
foreach ($a as $i => $valueA) {
$valueB = $b[$i];
$distance += abs($valueA - $valueB)
/ ((abs($valueA) + abs($valueB)) ?: EPSILON);
}
return $distance;
} | php | public function compute(array $a, array $b) : float
{
$distance = 0.;
foreach ($a as $i => $valueA) {
$valueB = $b[$i];
$distance += abs($valueA - $valueB)
/ ((abs($valueA) + abs($valueB)) ?: EPSILON);
}
return $distance;
} | [
"public",
"function",
"compute",
"(",
"array",
"$",
"a",
",",
"array",
"$",
"b",
")",
":",
"float",
"{",
"$",
"distance",
"=",
"0.",
";",
"foreach",
"(",
"$",
"a",
"as",
"$",
"i",
"=>",
"$",
"valueA",
")",
"{",
"$",
"valueB",
"=",
"$",
"b",
"[",
"$",
"i",
"]",
";",
"$",
"distance",
"+=",
"abs",
"(",
"$",
"valueA",
"-",
"$",
"valueB",
")",
"/",
"(",
"(",
"abs",
"(",
"$",
"valueA",
")",
"+",
"abs",
"(",
"$",
"valueB",
")",
")",
"?",
":",
"EPSILON",
")",
";",
"}",
"return",
"$",
"distance",
";",
"}"
] | Compute the distance between two vectors.
@param array $a
@param array $b
@return float | [
"Compute",
"the",
"distance",
"between",
"two",
"vectors",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Kernels/Distance/Canberra.php#L26-L38 |
RubixML/RubixML | src/Transformers/MinMaxNormalizer.php | MinMaxNormalizer.fit | 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);
} | php | 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);
} | [
"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",
")",
";",
"}"
] | Fit the transformer to the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset | [
"Fit",
"the",
"transformer",
"to",
"the",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/MinMaxNormalizer.php#L117-L129 |
RubixML/RubixML | src/Transformers/MinMaxNormalizer.php | MinMaxNormalizer.update | public function update(Dataset $dataset) : void
{
if ($this->minimums === null or $this->maximums === null) {
$this->fit($dataset);
return;
}
$columns = $dataset->columnsByType(DataType::CONTINUOUS);
foreach ($columns as $column => $values) {
$min = min($values);
$max = max($values);
$min = min($min, $this->minimums[$column]);
$max = max($max, $this->maximums[$column]);
$scale = ($this->max - $this->min)
/ (($max - $min) ?: EPSILON);
$minHat = $this->min - $min * $scale;
$this->minimums[$column] = $min;
$this->maximums[$column] = $max;
$this->scales[$column] = $scale;
$this->mins[$column] = $minHat;
}
} | php | public function update(Dataset $dataset) : void
{
if ($this->minimums === null or $this->maximums === null) {
$this->fit($dataset);
return;
}
$columns = $dataset->columnsByType(DataType::CONTINUOUS);
foreach ($columns as $column => $values) {
$min = min($values);
$max = max($values);
$min = min($min, $this->minimums[$column]);
$max = max($max, $this->maximums[$column]);
$scale = ($this->max - $this->min)
/ (($max - $min) ?: EPSILON);
$minHat = $this->min - $min * $scale;
$this->minimums[$column] = $min;
$this->maximums[$column] = $max;
$this->scales[$column] = $scale;
$this->mins[$column] = $minHat;
}
} | [
"public",
"function",
"update",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"minimums",
"===",
"null",
"or",
"$",
"this",
"->",
"maximums",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"fit",
"(",
"$",
"dataset",
")",
";",
"return",
";",
"}",
"$",
"columns",
"=",
"$",
"dataset",
"->",
"columnsByType",
"(",
"DataType",
"::",
"CONTINUOUS",
")",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"column",
"=>",
"$",
"values",
")",
"{",
"$",
"min",
"=",
"min",
"(",
"$",
"values",
")",
";",
"$",
"max",
"=",
"max",
"(",
"$",
"values",
")",
";",
"$",
"min",
"=",
"min",
"(",
"$",
"min",
",",
"$",
"this",
"->",
"minimums",
"[",
"$",
"column",
"]",
")",
";",
"$",
"max",
"=",
"max",
"(",
"$",
"max",
",",
"$",
"this",
"->",
"maximums",
"[",
"$",
"column",
"]",
")",
";",
"$",
"scale",
"=",
"(",
"$",
"this",
"->",
"max",
"-",
"$",
"this",
"->",
"min",
")",
"/",
"(",
"(",
"$",
"max",
"-",
"$",
"min",
")",
"?",
":",
"EPSILON",
")",
";",
"$",
"minHat",
"=",
"$",
"this",
"->",
"min",
"-",
"$",
"min",
"*",
"$",
"scale",
";",
"$",
"this",
"->",
"minimums",
"[",
"$",
"column",
"]",
"=",
"$",
"min",
";",
"$",
"this",
"->",
"maximums",
"[",
"$",
"column",
"]",
"=",
"$",
"max",
";",
"$",
"this",
"->",
"scales",
"[",
"$",
"column",
"]",
"=",
"$",
"scale",
";",
"$",
"this",
"->",
"mins",
"[",
"$",
"column",
"]",
"=",
"$",
"minHat",
";",
"}",
"}"
] | Update the fitting of the transformer.
@param \Rubix\ML\Datasets\Dataset $dataset | [
"Update",
"the",
"fitting",
"of",
"the",
"transformer",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/MinMaxNormalizer.php#L136-L163 |
RubixML/RubixML | src/Transformers/MinMaxNormalizer.php | MinMaxNormalizer.transform | public function transform(array &$samples) : void
{
if ($this->mins === null or $this->scales === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
foreach ($this->scales as $column => $scale) {
$sample[$column] *= $scale;
$sample[$column] += $this->mins[$column];
}
}
} | php | public function transform(array &$samples) : void
{
if ($this->mins === null or $this->scales === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
foreach ($this->scales as $column => $scale) {
$sample[$column] *= $scale;
$sample[$column] += $this->mins[$column];
}
}
} | [
"public",
"function",
"transform",
"(",
"array",
"&",
"$",
"samples",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"mins",
"===",
"null",
"or",
"$",
"this",
"->",
"scales",
"===",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Transformer has not been fitted.'",
")",
";",
"}",
"foreach",
"(",
"$",
"samples",
"as",
"&",
"$",
"sample",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"scales",
"as",
"$",
"column",
"=>",
"$",
"scale",
")",
"{",
"$",
"sample",
"[",
"$",
"column",
"]",
"*=",
"$",
"scale",
";",
"$",
"sample",
"[",
"$",
"column",
"]",
"+=",
"$",
"this",
"->",
"mins",
"[",
"$",
"column",
"]",
";",
"}",
"}",
"}"
] | Transform the dataset in place.
@param array $samples
@throws \RuntimeException | [
"Transform",
"the",
"dataset",
"in",
"place",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/MinMaxNormalizer.php#L171-L183 |
RubixML/RubixML | src/Embedders/TSNE.php | TSNE.predict | public function predict(Dataset $dataset) : array
{
DatasetIsCompatibleWithEstimator::check($dataset, $this);
if ($this->logger) {
$this->logger->info('Embedder initialized w/ '
. Params::stringify([
'dimensions' => $this->dimensions,
'perplexity' => $this->perplexity,
'exaggeration' => $this->exaggeration,
'rate' => $this->rate,
'kernel' => $this->kernel,
'epochs' => $this->epochs,
'min_gradient' => $this->minGradient,
'window' => $this->window,
]));
}
$n = $dataset->numRows();
$x = Matrix::build($dataset->samples());
if ($this->logger) {
$this->logger->info('Computing affinity matrix');
}
$distances = $this->pairwiseDistances($x);
$p = $this->highAffinities($distances)
->multiply($this->exaggeration);
$y = $yHat = Matrix::gaussian($n, $this->dimensions)
->multiply(self::Y_INIT);
$velocity = Matrix::zeros($n, $this->dimensions);
$gains = Matrix::ones($n, $this->dimensions)->asArray();
$momentum = self::INIT_MOMENTUM;
$this->steps = [];
for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
$distances = $this->pairwiseDistances($y);
$gradient = $this->gradient($p, $y, $distances);
$magnitude = $gradient->l2Norm();
$direction = $velocity->multiply($gradient);
foreach ($gains as $i => &$row) {
$temp = $direction[$i];
foreach ($row as $j => &$gain) {
$gain = $temp[$j] < 0.
? $gain + self::GAIN_ACCELERATE
: $gain * self::GAIN_BRAKE;
$gain = max(self::MIN_GAIN, $gain);
}
}
$gradient = $gradient->multiply(Matrix::quick($gains));
$velocity = $velocity->multiply($momentum)
->subtract($gradient->multiply($this->rate));
$y = $y->add($velocity);
$this->steps[] = $magnitude;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete,"
. " gradient=$magnitude");
}
if (is_nan($magnitude)) {
break 1;
}
if ($magnitude < $this->minGradient) {
break 1;
}
if ($epoch > $this->window) {
$window = array_slice($this->steps, -$this->window);
$worst = $window;
sort($worst);
if ($window === $worst) {
break 1;
}
}
if ($epoch === $this->early) {
$p = $p->divide($this->exaggeration);
$momentum += self::MOMENTUM_BOOST;
if ($this->logger) {
$this->logger->info('Early exaggeration'
. ' stage exhausted');
}
}
}
if ($this->logger) {
$this->logger->info('Embedding complete');
}
return $y->asArray();
} | php | public function predict(Dataset $dataset) : array
{
DatasetIsCompatibleWithEstimator::check($dataset, $this);
if ($this->logger) {
$this->logger->info('Embedder initialized w/ '
. Params::stringify([
'dimensions' => $this->dimensions,
'perplexity' => $this->perplexity,
'exaggeration' => $this->exaggeration,
'rate' => $this->rate,
'kernel' => $this->kernel,
'epochs' => $this->epochs,
'min_gradient' => $this->minGradient,
'window' => $this->window,
]));
}
$n = $dataset->numRows();
$x = Matrix::build($dataset->samples());
if ($this->logger) {
$this->logger->info('Computing affinity matrix');
}
$distances = $this->pairwiseDistances($x);
$p = $this->highAffinities($distances)
->multiply($this->exaggeration);
$y = $yHat = Matrix::gaussian($n, $this->dimensions)
->multiply(self::Y_INIT);
$velocity = Matrix::zeros($n, $this->dimensions);
$gains = Matrix::ones($n, $this->dimensions)->asArray();
$momentum = self::INIT_MOMENTUM;
$this->steps = [];
for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
$distances = $this->pairwiseDistances($y);
$gradient = $this->gradient($p, $y, $distances);
$magnitude = $gradient->l2Norm();
$direction = $velocity->multiply($gradient);
foreach ($gains as $i => &$row) {
$temp = $direction[$i];
foreach ($row as $j => &$gain) {
$gain = $temp[$j] < 0.
? $gain + self::GAIN_ACCELERATE
: $gain * self::GAIN_BRAKE;
$gain = max(self::MIN_GAIN, $gain);
}
}
$gradient = $gradient->multiply(Matrix::quick($gains));
$velocity = $velocity->multiply($momentum)
->subtract($gradient->multiply($this->rate));
$y = $y->add($velocity);
$this->steps[] = $magnitude;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete,"
. " gradient=$magnitude");
}
if (is_nan($magnitude)) {
break 1;
}
if ($magnitude < $this->minGradient) {
break 1;
}
if ($epoch > $this->window) {
$window = array_slice($this->steps, -$this->window);
$worst = $window;
sort($worst);
if ($window === $worst) {
break 1;
}
}
if ($epoch === $this->early) {
$p = $p->divide($this->exaggeration);
$momentum += self::MOMENTUM_BOOST;
if ($this->logger) {
$this->logger->info('Early exaggeration'
. ' stage exhausted');
}
}
}
if ($this->logger) {
$this->logger->info('Embedding complete');
}
return $y->asArray();
} | [
"public",
"function",
"predict",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"array",
"{",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Embedder initialized w/ '",
".",
"Params",
"::",
"stringify",
"(",
"[",
"'dimensions'",
"=>",
"$",
"this",
"->",
"dimensions",
",",
"'perplexity'",
"=>",
"$",
"this",
"->",
"perplexity",
",",
"'exaggeration'",
"=>",
"$",
"this",
"->",
"exaggeration",
",",
"'rate'",
"=>",
"$",
"this",
"->",
"rate",
",",
"'kernel'",
"=>",
"$",
"this",
"->",
"kernel",
",",
"'epochs'",
"=>",
"$",
"this",
"->",
"epochs",
",",
"'min_gradient'",
"=>",
"$",
"this",
"->",
"minGradient",
",",
"'window'",
"=>",
"$",
"this",
"->",
"window",
",",
"]",
")",
")",
";",
"}",
"$",
"n",
"=",
"$",
"dataset",
"->",
"numRows",
"(",
")",
";",
"$",
"x",
"=",
"Matrix",
"::",
"build",
"(",
"$",
"dataset",
"->",
"samples",
"(",
")",
")",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Computing affinity matrix'",
")",
";",
"}",
"$",
"distances",
"=",
"$",
"this",
"->",
"pairwiseDistances",
"(",
"$",
"x",
")",
";",
"$",
"p",
"=",
"$",
"this",
"->",
"highAffinities",
"(",
"$",
"distances",
")",
"->",
"multiply",
"(",
"$",
"this",
"->",
"exaggeration",
")",
";",
"$",
"y",
"=",
"$",
"yHat",
"=",
"Matrix",
"::",
"gaussian",
"(",
"$",
"n",
",",
"$",
"this",
"->",
"dimensions",
")",
"->",
"multiply",
"(",
"self",
"::",
"Y_INIT",
")",
";",
"$",
"velocity",
"=",
"Matrix",
"::",
"zeros",
"(",
"$",
"n",
",",
"$",
"this",
"->",
"dimensions",
")",
";",
"$",
"gains",
"=",
"Matrix",
"::",
"ones",
"(",
"$",
"n",
",",
"$",
"this",
"->",
"dimensions",
")",
"->",
"asArray",
"(",
")",
";",
"$",
"momentum",
"=",
"self",
"::",
"INIT_MOMENTUM",
";",
"$",
"this",
"->",
"steps",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"epoch",
"=",
"1",
";",
"$",
"epoch",
"<=",
"$",
"this",
"->",
"epochs",
";",
"$",
"epoch",
"++",
")",
"{",
"$",
"distances",
"=",
"$",
"this",
"->",
"pairwiseDistances",
"(",
"$",
"y",
")",
";",
"$",
"gradient",
"=",
"$",
"this",
"->",
"gradient",
"(",
"$",
"p",
",",
"$",
"y",
",",
"$",
"distances",
")",
";",
"$",
"magnitude",
"=",
"$",
"gradient",
"->",
"l2Norm",
"(",
")",
";",
"$",
"direction",
"=",
"$",
"velocity",
"->",
"multiply",
"(",
"$",
"gradient",
")",
";",
"foreach",
"(",
"$",
"gains",
"as",
"$",
"i",
"=>",
"&",
"$",
"row",
")",
"{",
"$",
"temp",
"=",
"$",
"direction",
"[",
"$",
"i",
"]",
";",
"foreach",
"(",
"$",
"row",
"as",
"$",
"j",
"=>",
"&",
"$",
"gain",
")",
"{",
"$",
"gain",
"=",
"$",
"temp",
"[",
"$",
"j",
"]",
"<",
"0.",
"?",
"$",
"gain",
"+",
"self",
"::",
"GAIN_ACCELERATE",
":",
"$",
"gain",
"*",
"self",
"::",
"GAIN_BRAKE",
";",
"$",
"gain",
"=",
"max",
"(",
"self",
"::",
"MIN_GAIN",
",",
"$",
"gain",
")",
";",
"}",
"}",
"$",
"gradient",
"=",
"$",
"gradient",
"->",
"multiply",
"(",
"Matrix",
"::",
"quick",
"(",
"$",
"gains",
")",
")",
";",
"$",
"velocity",
"=",
"$",
"velocity",
"->",
"multiply",
"(",
"$",
"momentum",
")",
"->",
"subtract",
"(",
"$",
"gradient",
"->",
"multiply",
"(",
"$",
"this",
"->",
"rate",
")",
")",
";",
"$",
"y",
"=",
"$",
"y",
"->",
"add",
"(",
"$",
"velocity",
")",
";",
"$",
"this",
"->",
"steps",
"[",
"]",
"=",
"$",
"magnitude",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"\"Epoch $epoch complete,\"",
".",
"\" gradient=$magnitude\"",
")",
";",
"}",
"if",
"(",
"is_nan",
"(",
"$",
"magnitude",
")",
")",
"{",
"break",
"1",
";",
"}",
"if",
"(",
"$",
"magnitude",
"<",
"$",
"this",
"->",
"minGradient",
")",
"{",
"break",
"1",
";",
"}",
"if",
"(",
"$",
"epoch",
">",
"$",
"this",
"->",
"window",
")",
"{",
"$",
"window",
"=",
"array_slice",
"(",
"$",
"this",
"->",
"steps",
",",
"-",
"$",
"this",
"->",
"window",
")",
";",
"$",
"worst",
"=",
"$",
"window",
";",
"sort",
"(",
"$",
"worst",
")",
";",
"if",
"(",
"$",
"window",
"===",
"$",
"worst",
")",
"{",
"break",
"1",
";",
"}",
"}",
"if",
"(",
"$",
"epoch",
"===",
"$",
"this",
"->",
"early",
")",
"{",
"$",
"p",
"=",
"$",
"p",
"->",
"divide",
"(",
"$",
"this",
"->",
"exaggeration",
")",
";",
"$",
"momentum",
"+=",
"self",
"::",
"MOMENTUM_BOOST",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Early exaggeration'",
".",
"' stage exhausted'",
")",
";",
"}",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Embedding complete'",
")",
";",
"}",
"return",
"$",
"y",
"->",
"asArray",
"(",
")",
";",
"}"
] | Embed a high dimensional sample matrix into a lower dimensional one.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException
@return array[] | [
"Embed",
"a",
"high",
"dimensional",
"sample",
"matrix",
"into",
"a",
"lower",
"dimensional",
"one",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Embedders/TSNE.php#L254-L365 |
RubixML/RubixML | src/Embedders/TSNE.php | TSNE.pairwiseDistances | protected function pairwiseDistances(Matrix $samples) : Matrix
{
$distances = [];
foreach ($samples as $a) {
$temp = [];
foreach ($samples as $b) {
$temp[] = $this->kernel->compute($a, $b);
}
$distances[] = $temp;
}
return Matrix::quick($distances);
} | php | protected function pairwiseDistances(Matrix $samples) : Matrix
{
$distances = [];
foreach ($samples as $a) {
$temp = [];
foreach ($samples as $b) {
$temp[] = $this->kernel->compute($a, $b);
}
$distances[] = $temp;
}
return Matrix::quick($distances);
} | [
"protected",
"function",
"pairwiseDistances",
"(",
"Matrix",
"$",
"samples",
")",
":",
"Matrix",
"{",
"$",
"distances",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"samples",
"as",
"$",
"a",
")",
"{",
"$",
"temp",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"samples",
"as",
"$",
"b",
")",
"{",
"$",
"temp",
"[",
"]",
"=",
"$",
"this",
"->",
"kernel",
"->",
"compute",
"(",
"$",
"a",
",",
"$",
"b",
")",
";",
"}",
"$",
"distances",
"[",
"]",
"=",
"$",
"temp",
";",
"}",
"return",
"Matrix",
"::",
"quick",
"(",
"$",
"distances",
")",
";",
"}"
] | Calculate the pairwise distances for each sample.
@param \Rubix\Tensor\Matrix $samples
@return \Rubix\Tensor\Matrix | [
"Calculate",
"the",
"pairwise",
"distances",
"for",
"each",
"sample",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Embedders/TSNE.php#L373-L388 |
RubixML/RubixML | src/Embedders/TSNE.php | TSNE.highAffinities | protected function highAffinities(Matrix $distances) : Matrix
{
$zeros = array_fill(0, count($distances), 0);
$p = [];
foreach ($distances as $i => $row) {
$affinities = $zeros;
$minBeta = -INF;
$maxBeta = INF;
$beta = 1.;
for ($l = 0; $l < self::BINARY_PRECISION; $l++) {
$affinities = [];
$pSigma = 0.;
foreach ($row as $j => $distance) {
if ($i !== $j) {
$affinity = exp(-$distance * $beta);
} else {
$affinity = 0.;
}
$affinities[] = $affinity;
$pSigma += $affinity;
}
if ($pSigma === 0.) {
$pSigma = EPSILON;
}
$distSigma = 0.;
foreach ($affinities as $j => &$prob) {
$prob /= $pSigma;
$distSigma += $row[$j] * $prob;
}
$entropy = log($pSigma) + $beta * $distSigma;
$diff = $entropy - $this->entropy;
if (abs($diff) < self::SEARCH_TOLERANCE) {
break 1;
}
if ($diff > 0.) {
$minBeta = $beta;
if ($maxBeta === INF) {
$beta *= 2.;
} else {
$beta = ($beta + $maxBeta) / 2.;
}
} else {
$maxBeta = $beta;
if ($minBeta === -INF) {
$beta /= 2.;
} else {
$beta = ($beta + $minBeta) / 2.;
}
}
}
$p[] = $affinities;
}
$p = Matrix::quick($p);
$pHat = $p->add($p->transpose());
$sigma = $pHat->sum()
->clipLower(EPSILON);
return $pHat->divide($sigma);
} | php | protected function highAffinities(Matrix $distances) : Matrix
{
$zeros = array_fill(0, count($distances), 0);
$p = [];
foreach ($distances as $i => $row) {
$affinities = $zeros;
$minBeta = -INF;
$maxBeta = INF;
$beta = 1.;
for ($l = 0; $l < self::BINARY_PRECISION; $l++) {
$affinities = [];
$pSigma = 0.;
foreach ($row as $j => $distance) {
if ($i !== $j) {
$affinity = exp(-$distance * $beta);
} else {
$affinity = 0.;
}
$affinities[] = $affinity;
$pSigma += $affinity;
}
if ($pSigma === 0.) {
$pSigma = EPSILON;
}
$distSigma = 0.;
foreach ($affinities as $j => &$prob) {
$prob /= $pSigma;
$distSigma += $row[$j] * $prob;
}
$entropy = log($pSigma) + $beta * $distSigma;
$diff = $entropy - $this->entropy;
if (abs($diff) < self::SEARCH_TOLERANCE) {
break 1;
}
if ($diff > 0.) {
$minBeta = $beta;
if ($maxBeta === INF) {
$beta *= 2.;
} else {
$beta = ($beta + $maxBeta) / 2.;
}
} else {
$maxBeta = $beta;
if ($minBeta === -INF) {
$beta /= 2.;
} else {
$beta = ($beta + $minBeta) / 2.;
}
}
}
$p[] = $affinities;
}
$p = Matrix::quick($p);
$pHat = $p->add($p->transpose());
$sigma = $pHat->sum()
->clipLower(EPSILON);
return $pHat->divide($sigma);
} | [
"protected",
"function",
"highAffinities",
"(",
"Matrix",
"$",
"distances",
")",
":",
"Matrix",
"{",
"$",
"zeros",
"=",
"array_fill",
"(",
"0",
",",
"count",
"(",
"$",
"distances",
")",
",",
"0",
")",
";",
"$",
"p",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"distances",
"as",
"$",
"i",
"=>",
"$",
"row",
")",
"{",
"$",
"affinities",
"=",
"$",
"zeros",
";",
"$",
"minBeta",
"=",
"-",
"INF",
";",
"$",
"maxBeta",
"=",
"INF",
";",
"$",
"beta",
"=",
"1.",
";",
"for",
"(",
"$",
"l",
"=",
"0",
";",
"$",
"l",
"<",
"self",
"::",
"BINARY_PRECISION",
";",
"$",
"l",
"++",
")",
"{",
"$",
"affinities",
"=",
"[",
"]",
";",
"$",
"pSigma",
"=",
"0.",
";",
"foreach",
"(",
"$",
"row",
"as",
"$",
"j",
"=>",
"$",
"distance",
")",
"{",
"if",
"(",
"$",
"i",
"!==",
"$",
"j",
")",
"{",
"$",
"affinity",
"=",
"exp",
"(",
"-",
"$",
"distance",
"*",
"$",
"beta",
")",
";",
"}",
"else",
"{",
"$",
"affinity",
"=",
"0.",
";",
"}",
"$",
"affinities",
"[",
"]",
"=",
"$",
"affinity",
";",
"$",
"pSigma",
"+=",
"$",
"affinity",
";",
"}",
"if",
"(",
"$",
"pSigma",
"===",
"0.",
")",
"{",
"$",
"pSigma",
"=",
"EPSILON",
";",
"}",
"$",
"distSigma",
"=",
"0.",
";",
"foreach",
"(",
"$",
"affinities",
"as",
"$",
"j",
"=>",
"&",
"$",
"prob",
")",
"{",
"$",
"prob",
"/=",
"$",
"pSigma",
";",
"$",
"distSigma",
"+=",
"$",
"row",
"[",
"$",
"j",
"]",
"*",
"$",
"prob",
";",
"}",
"$",
"entropy",
"=",
"log",
"(",
"$",
"pSigma",
")",
"+",
"$",
"beta",
"*",
"$",
"distSigma",
";",
"$",
"diff",
"=",
"$",
"entropy",
"-",
"$",
"this",
"->",
"entropy",
";",
"if",
"(",
"abs",
"(",
"$",
"diff",
")",
"<",
"self",
"::",
"SEARCH_TOLERANCE",
")",
"{",
"break",
"1",
";",
"}",
"if",
"(",
"$",
"diff",
">",
"0.",
")",
"{",
"$",
"minBeta",
"=",
"$",
"beta",
";",
"if",
"(",
"$",
"maxBeta",
"===",
"INF",
")",
"{",
"$",
"beta",
"*=",
"2.",
";",
"}",
"else",
"{",
"$",
"beta",
"=",
"(",
"$",
"beta",
"+",
"$",
"maxBeta",
")",
"/",
"2.",
";",
"}",
"}",
"else",
"{",
"$",
"maxBeta",
"=",
"$",
"beta",
";",
"if",
"(",
"$",
"minBeta",
"===",
"-",
"INF",
")",
"{",
"$",
"beta",
"/=",
"2.",
";",
"}",
"else",
"{",
"$",
"beta",
"=",
"(",
"$",
"beta",
"+",
"$",
"minBeta",
")",
"/",
"2.",
";",
"}",
"}",
"}",
"$",
"p",
"[",
"]",
"=",
"$",
"affinities",
";",
"}",
"$",
"p",
"=",
"Matrix",
"::",
"quick",
"(",
"$",
"p",
")",
";",
"$",
"pHat",
"=",
"$",
"p",
"->",
"add",
"(",
"$",
"p",
"->",
"transpose",
"(",
")",
")",
";",
"$",
"sigma",
"=",
"$",
"pHat",
"->",
"sum",
"(",
")",
"->",
"clipLower",
"(",
"EPSILON",
")",
";",
"return",
"$",
"pHat",
"->",
"divide",
"(",
"$",
"sigma",
")",
";",
"}"
] | Calculate the joint likelihood of each sample in the high dimensional
space as being nearest neighbor to each other sample.
@param \Rubix\Tensor\Matrix $distances
@return \Rubix\Tensor\Matrix | [
"Calculate",
"the",
"joint",
"likelihood",
"of",
"each",
"sample",
"in",
"the",
"high",
"dimensional",
"space",
"as",
"being",
"nearest",
"neighbor",
"to",
"each",
"other",
"sample",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Embedders/TSNE.php#L397-L473 |
RubixML/RubixML | src/Embedders/TSNE.php | TSNE.gradient | protected function gradient(Matrix $p, Matrix $y, Matrix $distances) : Matrix
{
$q = $distances->square()
->divide($this->degrees)
->add(1.)
->pow((1. + $this->degrees) / -2.);
$qSigma = $q->sum()->multiply(2.);
$q = $q->divide($qSigma)
->clipLower(EPSILON);
$pqd = $p->subtract($q)
->multiply($distances);
$c = 2. * (1. + $this->degrees) / $this->degrees;
$gradient = [];
foreach ($pqd->asVectors() as $i => $row) {
$yHat = $y->rowAsVector($i)
->subtract($y);
$gradient[] = $row->matmul($yHat)
->multiply($c)
->row(0);
}
return Matrix::quick($gradient);
} | php | protected function gradient(Matrix $p, Matrix $y, Matrix $distances) : Matrix
{
$q = $distances->square()
->divide($this->degrees)
->add(1.)
->pow((1. + $this->degrees) / -2.);
$qSigma = $q->sum()->multiply(2.);
$q = $q->divide($qSigma)
->clipLower(EPSILON);
$pqd = $p->subtract($q)
->multiply($distances);
$c = 2. * (1. + $this->degrees) / $this->degrees;
$gradient = [];
foreach ($pqd->asVectors() as $i => $row) {
$yHat = $y->rowAsVector($i)
->subtract($y);
$gradient[] = $row->matmul($yHat)
->multiply($c)
->row(0);
}
return Matrix::quick($gradient);
} | [
"protected",
"function",
"gradient",
"(",
"Matrix",
"$",
"p",
",",
"Matrix",
"$",
"y",
",",
"Matrix",
"$",
"distances",
")",
":",
"Matrix",
"{",
"$",
"q",
"=",
"$",
"distances",
"->",
"square",
"(",
")",
"->",
"divide",
"(",
"$",
"this",
"->",
"degrees",
")",
"->",
"add",
"(",
"1.",
")",
"->",
"pow",
"(",
"(",
"1.",
"+",
"$",
"this",
"->",
"degrees",
")",
"/",
"-",
"2.",
")",
";",
"$",
"qSigma",
"=",
"$",
"q",
"->",
"sum",
"(",
")",
"->",
"multiply",
"(",
"2.",
")",
";",
"$",
"q",
"=",
"$",
"q",
"->",
"divide",
"(",
"$",
"qSigma",
")",
"->",
"clipLower",
"(",
"EPSILON",
")",
";",
"$",
"pqd",
"=",
"$",
"p",
"->",
"subtract",
"(",
"$",
"q",
")",
"->",
"multiply",
"(",
"$",
"distances",
")",
";",
"$",
"c",
"=",
"2.",
"*",
"(",
"1.",
"+",
"$",
"this",
"->",
"degrees",
")",
"/",
"$",
"this",
"->",
"degrees",
";",
"$",
"gradient",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"pqd",
"->",
"asVectors",
"(",
")",
"as",
"$",
"i",
"=>",
"$",
"row",
")",
"{",
"$",
"yHat",
"=",
"$",
"y",
"->",
"rowAsVector",
"(",
"$",
"i",
")",
"->",
"subtract",
"(",
"$",
"y",
")",
";",
"$",
"gradient",
"[",
"]",
"=",
"$",
"row",
"->",
"matmul",
"(",
"$",
"yHat",
")",
"->",
"multiply",
"(",
"$",
"c",
")",
"->",
"row",
"(",
"0",
")",
";",
"}",
"return",
"Matrix",
"::",
"quick",
"(",
"$",
"gradient",
")",
";",
"}"
] | Compute the gradient of the KL Divergence cost function with respect to
the embedding.
@param \Rubix\Tensor\Matrix $p
@param \Rubix\Tensor\Matrix $y
@param \Rubix\Tensor\Matrix $distances
@return \Rubix\Tensor\Matrix | [
"Compute",
"the",
"gradient",
"of",
"the",
"KL",
"Divergence",
"cost",
"function",
"with",
"respect",
"to",
"the",
"embedding",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Embedders/TSNE.php#L484-L513 |
RubixML/RubixML | src/Kernels/Distance/Jaccard.php | Jaccard.compute | public function compute(array $a, array $b) : float
{
$distance = $min = $max = 0.;
foreach ($a as $i => $valueA) {
$valueB = $b[$i];
$min += min($valueA, $valueB);
$max += max($valueA, $valueB);
}
return 1. - ($min / ($max ?: EPSILON));
} | php | public function compute(array $a, array $b) : float
{
$distance = $min = $max = 0.;
foreach ($a as $i => $valueA) {
$valueB = $b[$i];
$min += min($valueA, $valueB);
$max += max($valueA, $valueB);
}
return 1. - ($min / ($max ?: EPSILON));
} | [
"public",
"function",
"compute",
"(",
"array",
"$",
"a",
",",
"array",
"$",
"b",
")",
":",
"float",
"{",
"$",
"distance",
"=",
"$",
"min",
"=",
"$",
"max",
"=",
"0.",
";",
"foreach",
"(",
"$",
"a",
"as",
"$",
"i",
"=>",
"$",
"valueA",
")",
"{",
"$",
"valueB",
"=",
"$",
"b",
"[",
"$",
"i",
"]",
";",
"$",
"min",
"+=",
"min",
"(",
"$",
"valueA",
",",
"$",
"valueB",
")",
";",
"$",
"max",
"+=",
"max",
"(",
"$",
"valueA",
",",
"$",
"valueB",
")",
";",
"}",
"return",
"1.",
"-",
"(",
"$",
"min",
"/",
"(",
"$",
"max",
"?",
":",
"EPSILON",
")",
")",
";",
"}"
] | Compute the distance between two vectors.
@param array $a
@param array $b
@return float | [
"Compute",
"the",
"distance",
"between",
"two",
"vectors",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Kernels/Distance/Jaccard.php#L27-L39 |
RubixML/RubixML | src/Transformers/RobustStandardizer.php | RobustStandardizer.fit | public function fit(Dataset $dataset) : void
{
$columns = $dataset->columnsByType(DataType::CONTINUOUS);
$this->medians = $this->mads = [];
foreach ($columns as $column => $values) {
[$median, $mad] = Stats::medMad($values);
$this->medians[$column] = $median;
$this->mads[$column] = $mad ?: EPSILON;
}
} | php | public function fit(Dataset $dataset) : void
{
$columns = $dataset->columnsByType(DataType::CONTINUOUS);
$this->medians = $this->mads = [];
foreach ($columns as $column => $values) {
[$median, $mad] = Stats::medMad($values);
$this->medians[$column] = $median;
$this->mads[$column] = $mad ?: EPSILON;
}
} | [
"public",
"function",
"fit",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"$",
"columns",
"=",
"$",
"dataset",
"->",
"columnsByType",
"(",
"DataType",
"::",
"CONTINUOUS",
")",
";",
"$",
"this",
"->",
"medians",
"=",
"$",
"this",
"->",
"mads",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"column",
"=>",
"$",
"values",
")",
"{",
"[",
"$",
"median",
",",
"$",
"mad",
"]",
"=",
"Stats",
"::",
"medMad",
"(",
"$",
"values",
")",
";",
"$",
"this",
"->",
"medians",
"[",
"$",
"column",
"]",
"=",
"$",
"median",
";",
"$",
"this",
"->",
"mads",
"[",
"$",
"column",
"]",
"=",
"$",
"mad",
"?",
":",
"EPSILON",
";",
"}",
"}"
] | Fit the transformer to the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset | [
"Fit",
"the",
"transformer",
"to",
"the",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/RobustStandardizer.php#L91-L103 |
RubixML/RubixML | src/Transformers/RobustStandardizer.php | RobustStandardizer.transform | public function transform(array &$samples) : void
{
if ($this->medians === null or $this->mads === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
foreach ($this->mads as $column => $mad) {
$feature = $sample[$column];
if ($this->center) {
$feature -= $this->medians[$column];
}
$sample[$column] = $feature / $mad;
}
}
} | php | public function transform(array &$samples) : void
{
if ($this->medians === null or $this->mads === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
foreach ($samples as &$sample) {
foreach ($this->mads as $column => $mad) {
$feature = $sample[$column];
if ($this->center) {
$feature -= $this->medians[$column];
}
$sample[$column] = $feature / $mad;
}
}
} | [
"public",
"function",
"transform",
"(",
"array",
"&",
"$",
"samples",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"medians",
"===",
"null",
"or",
"$",
"this",
"->",
"mads",
"===",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Transformer has not been fitted.'",
")",
";",
"}",
"foreach",
"(",
"$",
"samples",
"as",
"&",
"$",
"sample",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"mads",
"as",
"$",
"column",
"=>",
"$",
"mad",
")",
"{",
"$",
"feature",
"=",
"$",
"sample",
"[",
"$",
"column",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"center",
")",
"{",
"$",
"feature",
"-=",
"$",
"this",
"->",
"medians",
"[",
"$",
"column",
"]",
";",
"}",
"$",
"sample",
"[",
"$",
"column",
"]",
"=",
"$",
"feature",
"/",
"$",
"mad",
";",
"}",
"}",
"}"
] | Transform the dataset in place.
@param array $samples
@throws \RuntimeException | [
"Transform",
"the",
"dataset",
"in",
"place",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/RobustStandardizer.php#L111-L128 |
RubixML/RubixML | src/CrossValidation/Reports/ContingencyTable.php | ContingencyTable.generate | public function generate(array $predictions, array $labels) : array
{
if (count($predictions) !== count($labels)) {
throw new InvalidArgumentException('The number of labels'
. ' must equal the number of predictions.');
}
$classes = array_unique($labels);
$clusters = array_unique($predictions);
$table = array_fill_keys($clusters, array_fill_keys($classes, 0));
foreach ($labels as $i => $class) {
$table[$predictions[$i]][$class]++;
}
return $table;
} | php | public function generate(array $predictions, array $labels) : array
{
if (count($predictions) !== count($labels)) {
throw new InvalidArgumentException('The number of labels'
. ' must equal the number of predictions.');
}
$classes = array_unique($labels);
$clusters = array_unique($predictions);
$table = array_fill_keys($clusters, array_fill_keys($classes, 0));
foreach ($labels as $i => $class) {
$table[$predictions[$i]][$class]++;
}
return $table;
} | [
"public",
"function",
"generate",
"(",
"array",
"$",
"predictions",
",",
"array",
"$",
"labels",
")",
":",
"array",
"{",
"if",
"(",
"count",
"(",
"$",
"predictions",
")",
"!==",
"count",
"(",
"$",
"labels",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'The number of labels'",
".",
"' must equal the number of predictions.'",
")",
";",
"}",
"$",
"classes",
"=",
"array_unique",
"(",
"$",
"labels",
")",
";",
"$",
"clusters",
"=",
"array_unique",
"(",
"$",
"predictions",
")",
";",
"$",
"table",
"=",
"array_fill_keys",
"(",
"$",
"clusters",
",",
"array_fill_keys",
"(",
"$",
"classes",
",",
"0",
")",
")",
";",
"foreach",
"(",
"$",
"labels",
"as",
"$",
"i",
"=>",
"$",
"class",
")",
"{",
"$",
"table",
"[",
"$",
"predictions",
"[",
"$",
"i",
"]",
"]",
"[",
"$",
"class",
"]",
"++",
";",
"}",
"return",
"$",
"table",
";",
"}"
] | Generate the report.
@param array $predictions
@param array $labels
@throws \InvalidArgumentException
@return array | [
"Generate",
"the",
"report",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CrossValidation/Reports/ContingencyTable.php#L41-L58 |
RubixML/RubixML | src/Transformers/ImageVectorizer.php | ImageVectorizer.transform | public function transform(array &$samples) : void
{
foreach ($samples as &$sample) {
$vectors = [];
foreach ($sample as $column => $image) {
if (is_resource($image) ? get_resource_type($image) === 'gd' : false) {
$width = imagesx($image);
$height = imagesy($image);
$vector = [];
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$pixel = imagecolorat($image, $x, $y);
$vector[] = $pixel & 0xFF;
for ($i = 8; $i <= $this->mu; $i *= 2) {
$vector[] = ($pixel >> $i) & 0xFF;
}
}
}
unset($sample[$column]);
imagedestroy($image);
$vectors[] = $vector;
}
}
$sample = array_merge($sample, ...$vectors);
}
} | php | public function transform(array &$samples) : void
{
foreach ($samples as &$sample) {
$vectors = [];
foreach ($sample as $column => $image) {
if (is_resource($image) ? get_resource_type($image) === 'gd' : false) {
$width = imagesx($image);
$height = imagesy($image);
$vector = [];
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$pixel = imagecolorat($image, $x, $y);
$vector[] = $pixel & 0xFF;
for ($i = 8; $i <= $this->mu; $i *= 2) {
$vector[] = ($pixel >> $i) & 0xFF;
}
}
}
unset($sample[$column]);
imagedestroy($image);
$vectors[] = $vector;
}
}
$sample = array_merge($sample, ...$vectors);
}
} | [
"public",
"function",
"transform",
"(",
"array",
"&",
"$",
"samples",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"samples",
"as",
"&",
"$",
"sample",
")",
"{",
"$",
"vectors",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"sample",
"as",
"$",
"column",
"=>",
"$",
"image",
")",
"{",
"if",
"(",
"is_resource",
"(",
"$",
"image",
")",
"?",
"get_resource_type",
"(",
"$",
"image",
")",
"===",
"'gd'",
":",
"false",
")",
"{",
"$",
"width",
"=",
"imagesx",
"(",
"$",
"image",
")",
";",
"$",
"height",
"=",
"imagesy",
"(",
"$",
"image",
")",
";",
"$",
"vector",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"x",
"=",
"0",
";",
"$",
"x",
"<",
"$",
"width",
";",
"$",
"x",
"++",
")",
"{",
"for",
"(",
"$",
"y",
"=",
"0",
";",
"$",
"y",
"<",
"$",
"height",
";",
"$",
"y",
"++",
")",
"{",
"$",
"pixel",
"=",
"imagecolorat",
"(",
"$",
"image",
",",
"$",
"x",
",",
"$",
"y",
")",
";",
"$",
"vector",
"[",
"]",
"=",
"$",
"pixel",
"&",
"0xFF",
";",
"for",
"(",
"$",
"i",
"=",
"8",
";",
"$",
"i",
"<=",
"$",
"this",
"->",
"mu",
";",
"$",
"i",
"*=",
"2",
")",
"{",
"$",
"vector",
"[",
"]",
"=",
"(",
"$",
"pixel",
">>",
"$",
"i",
")",
"&",
"0xFF",
";",
"}",
"}",
"}",
"unset",
"(",
"$",
"sample",
"[",
"$",
"column",
"]",
")",
";",
"imagedestroy",
"(",
"$",
"image",
")",
";",
"$",
"vectors",
"[",
"]",
"=",
"$",
"vector",
";",
"}",
"}",
"$",
"sample",
"=",
"array_merge",
"(",
"$",
"sample",
",",
"...",
"$",
"vectors",
")",
";",
"}",
"}"
] | Transform the dataset in place.
@param array $samples | [
"Transform",
"the",
"dataset",
"in",
"place",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/ImageVectorizer.php#L62-L96 |
RubixML/RubixML | src/BootstrapAggregator.php | BootstrapAggregator.train | 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);
$p = (int) round($this->ratio * $dataset->numRows());
$this->ensemble = [];
Loop::run(function () use ($dataset, $p) {
$pool = new DefaultPool($this->workers);
$coroutines = [];
for ($i = 0; $i < $this->estimators; $i++) {
$estimator = clone $this->base;
$subset = $dataset->randomSubsetWithReplacement($p);
$task = new CallableTask(
[$this, '_train'],
[$estimator, $subset]
);
$coroutines[] = call(function () use ($pool, $task) {
return yield $pool->enqueue($task);
});
}
$this->ensemble = yield all($coroutines);
return yield $pool->shutdown();
});
} | php | 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);
$p = (int) round($this->ratio * $dataset->numRows());
$this->ensemble = [];
Loop::run(function () use ($dataset, $p) {
$pool = new DefaultPool($this->workers);
$coroutines = [];
for ($i = 0; $i < $this->estimators; $i++) {
$estimator = clone $this->base;
$subset = $dataset->randomSubsetWithReplacement($p);
$task = new CallableTask(
[$this, '_train'],
[$estimator, $subset]
);
$coroutines[] = call(function () use ($pool, $task) {
return yield $pool->enqueue($task);
});
}
$this->ensemble = yield all($coroutines);
return yield $pool->shutdown();
});
} | [
"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",
")",
";",
"$",
"p",
"=",
"(",
"int",
")",
"round",
"(",
"$",
"this",
"->",
"ratio",
"*",
"$",
"dataset",
"->",
"numRows",
"(",
")",
")",
";",
"$",
"this",
"->",
"ensemble",
"=",
"[",
"]",
";",
"Loop",
"::",
"run",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"dataset",
",",
"$",
"p",
")",
"{",
"$",
"pool",
"=",
"new",
"DefaultPool",
"(",
"$",
"this",
"->",
"workers",
")",
";",
"$",
"coroutines",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"this",
"->",
"estimators",
";",
"$",
"i",
"++",
")",
"{",
"$",
"estimator",
"=",
"clone",
"$",
"this",
"->",
"base",
";",
"$",
"subset",
"=",
"$",
"dataset",
"->",
"randomSubsetWithReplacement",
"(",
"$",
"p",
")",
";",
"$",
"task",
"=",
"new",
"CallableTask",
"(",
"[",
"$",
"this",
",",
"'_train'",
"]",
",",
"[",
"$",
"estimator",
",",
"$",
"subset",
"]",
")",
";",
"$",
"coroutines",
"[",
"]",
"=",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"pool",
",",
"$",
"task",
")",
"{",
"return",
"yield",
"$",
"pool",
"->",
"enqueue",
"(",
"$",
"task",
")",
";",
"}",
")",
";",
"}",
"$",
"this",
"->",
"ensemble",
"=",
"yield",
"all",
"(",
"$",
"coroutines",
")",
";",
"return",
"yield",
"$",
"pool",
"->",
"shutdown",
"(",
")",
";",
"}",
")",
";",
"}"
] | Instantiate and train each base estimator in the ensemble on a bootstrap
training set.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Instantiate",
"and",
"train",
"each",
"base",
"estimator",
"in",
"the",
"ensemble",
"on",
"a",
"bootstrap",
"training",
"set",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/BootstrapAggregator.php#L141-L180 |
RubixML/RubixML | src/BootstrapAggregator.php | BootstrapAggregator.predict | 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);
}
} | php | 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);
}
} | [
"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",
")",
";",
"}",
"}"
] | Make predictions from a dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \RuntimeException
@return array | [
"Make",
"predictions",
"from",
"a",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/BootstrapAggregator.php#L189-L214 |
RubixML/RubixML | src/Graph/Nodes/Isolator.php | Isolator.split | public static function split(Dataset $dataset) : self
{
$column = rand(0, $dataset->numColumns() - 1);
$sample = $dataset[rand(0, count($dataset) - 1)];
$value = $sample[$column];
$groups = $dataset->partition($column, $value);
return new self($column, $value, $groups);
} | php | public static function split(Dataset $dataset) : self
{
$column = rand(0, $dataset->numColumns() - 1);
$sample = $dataset[rand(0, count($dataset) - 1)];
$value = $sample[$column];
$groups = $dataset->partition($column, $value);
return new self($column, $value, $groups);
} | [
"public",
"static",
"function",
"split",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"self",
"{",
"$",
"column",
"=",
"rand",
"(",
"0",
",",
"$",
"dataset",
"->",
"numColumns",
"(",
")",
"-",
"1",
")",
";",
"$",
"sample",
"=",
"$",
"dataset",
"[",
"rand",
"(",
"0",
",",
"count",
"(",
"$",
"dataset",
")",
"-",
"1",
")",
"]",
";",
"$",
"value",
"=",
"$",
"sample",
"[",
"$",
"column",
"]",
";",
"$",
"groups",
"=",
"$",
"dataset",
"->",
"partition",
"(",
"$",
"column",
",",
"$",
"value",
")",
";",
"return",
"new",
"self",
"(",
"$",
"column",
",",
"$",
"value",
",",
"$",
"groups",
")",
";",
"}"
] | Factory method to build a isolator node from a dataset
using a random split of the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@return self | [
"Factory",
"method",
"to",
"build",
"a",
"isolator",
"node",
"from",
"a",
"dataset",
"using",
"a",
"random",
"split",
"of",
"the",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/Isolator.php#L48-L59 |
RubixML/RubixML | src/Transformers/OneHotEncoder.php | OneHotEncoder.fit | public function fit(Dataset $dataset) : void
{
$columns = $dataset->columnsByType(DataType::CATEGORICAL);
$this->categories = [];
foreach ($columns as $column => $values) {
$categories = array_values(array_unique($values));
$this->categories[$column] = array_flip($categories);
}
} | php | public function fit(Dataset $dataset) : void
{
$columns = $dataset->columnsByType(DataType::CATEGORICAL);
$this->categories = [];
foreach ($columns as $column => $values) {
$categories = array_values(array_unique($values));
$this->categories[$column] = array_flip($categories);
}
} | [
"public",
"function",
"fit",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"$",
"columns",
"=",
"$",
"dataset",
"->",
"columnsByType",
"(",
"DataType",
"::",
"CATEGORICAL",
")",
";",
"$",
"this",
"->",
"categories",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"column",
"=>",
"$",
"values",
")",
"{",
"$",
"categories",
"=",
"array_values",
"(",
"array_unique",
"(",
"$",
"values",
")",
")",
";",
"$",
"this",
"->",
"categories",
"[",
"$",
"column",
"]",
"=",
"array_flip",
"(",
"$",
"categories",
")",
";",
"}",
"}"
] | Fit the transformer to the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset | [
"Fit",
"the",
"transformer",
"to",
"the",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/OneHotEncoder.php#L45-L56 |
RubixML/RubixML | src/Transformers/OneHotEncoder.php | OneHotEncoder.transform | public function transform(array &$samples) : void
{
if ($this->categories === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
$templates = [];
foreach ($this->categories as $column => $categories) {
$templates[$column] = array_fill(0, count($categories), 0);
}
foreach ($samples as &$sample) {
$vector = [];
foreach ($this->categories as $column => $categories) {
$category = $sample[$column];
$features = $templates[$column];
if (isset($categories[$category])) {
$features[$categories[$category]] = 1;
}
$vector = array_merge($vector, $features);
unset($sample[$column]);
}
$sample = array_merge($sample, $vector);
}
} | php | public function transform(array &$samples) : void
{
if ($this->categories === null) {
throw new RuntimeException('Transformer has not been fitted.');
}
$templates = [];
foreach ($this->categories as $column => $categories) {
$templates[$column] = array_fill(0, count($categories), 0);
}
foreach ($samples as &$sample) {
$vector = [];
foreach ($this->categories as $column => $categories) {
$category = $sample[$column];
$features = $templates[$column];
if (isset($categories[$category])) {
$features[$categories[$category]] = 1;
}
$vector = array_merge($vector, $features);
unset($sample[$column]);
}
$sample = array_merge($sample, $vector);
}
} | [
"public",
"function",
"transform",
"(",
"array",
"&",
"$",
"samples",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"categories",
"===",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Transformer has not been fitted.'",
")",
";",
"}",
"$",
"templates",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"categories",
"as",
"$",
"column",
"=>",
"$",
"categories",
")",
"{",
"$",
"templates",
"[",
"$",
"column",
"]",
"=",
"array_fill",
"(",
"0",
",",
"count",
"(",
"$",
"categories",
")",
",",
"0",
")",
";",
"}",
"foreach",
"(",
"$",
"samples",
"as",
"&",
"$",
"sample",
")",
"{",
"$",
"vector",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"categories",
"as",
"$",
"column",
"=>",
"$",
"categories",
")",
"{",
"$",
"category",
"=",
"$",
"sample",
"[",
"$",
"column",
"]",
";",
"$",
"features",
"=",
"$",
"templates",
"[",
"$",
"column",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"categories",
"[",
"$",
"category",
"]",
")",
")",
"{",
"$",
"features",
"[",
"$",
"categories",
"[",
"$",
"category",
"]",
"]",
"=",
"1",
";",
"}",
"$",
"vector",
"=",
"array_merge",
"(",
"$",
"vector",
",",
"$",
"features",
")",
";",
"unset",
"(",
"$",
"sample",
"[",
"$",
"column",
"]",
")",
";",
"}",
"$",
"sample",
"=",
"array_merge",
"(",
"$",
"sample",
",",
"$",
"vector",
")",
";",
"}",
"}"
] | Transform the dataset in place.
@param array $samples
@throws \RuntimeException | [
"Transform",
"the",
"dataset",
"in",
"place",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/OneHotEncoder.php#L64-L94 |
RubixML/RubixML | src/Clusterers/MeanShift.php | MeanShift.estimateRadius | public static function estimateRadius(Dataset $dataset, float $percentile = 30., ?Distance $kernel = null) : float
{
if ($percentile < 0. or $percentile > 100.) {
throw new InvalidArgumentException('Percentile must be between'
. " 0 and 100, $percentile given.");
}
$kernel = $kernel ?? new Euclidean();
$distances = [];
foreach ($dataset as $sampleA) {
foreach ($dataset as $sampleB) {
$distances[] = $kernel->compute($sampleA, $sampleB);
}
}
return Stats::percentile($distances, $percentile);
} | php | public static function estimateRadius(Dataset $dataset, float $percentile = 30., ?Distance $kernel = null) : float
{
if ($percentile < 0. or $percentile > 100.) {
throw new InvalidArgumentException('Percentile must be between'
. " 0 and 100, $percentile given.");
}
$kernel = $kernel ?? new Euclidean();
$distances = [];
foreach ($dataset as $sampleA) {
foreach ($dataset as $sampleB) {
$distances[] = $kernel->compute($sampleA, $sampleB);
}
}
return Stats::percentile($distances, $percentile);
} | [
"public",
"static",
"function",
"estimateRadius",
"(",
"Dataset",
"$",
"dataset",
",",
"float",
"$",
"percentile",
"=",
"30.",
",",
"?",
"Distance",
"$",
"kernel",
"=",
"null",
")",
":",
"float",
"{",
"if",
"(",
"$",
"percentile",
"<",
"0.",
"or",
"$",
"percentile",
">",
"100.",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Percentile must be between'",
".",
"\" 0 and 100, $percentile given.\"",
")",
";",
"}",
"$",
"kernel",
"=",
"$",
"kernel",
"??",
"new",
"Euclidean",
"(",
")",
";",
"$",
"distances",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"dataset",
"as",
"$",
"sampleA",
")",
"{",
"foreach",
"(",
"$",
"dataset",
"as",
"$",
"sampleB",
")",
"{",
"$",
"distances",
"[",
"]",
"=",
"$",
"kernel",
"->",
"compute",
"(",
"$",
"sampleA",
",",
"$",
"sampleB",
")",
";",
"}",
"}",
"return",
"Stats",
"::",
"percentile",
"(",
"$",
"distances",
",",
"$",
"percentile",
")",
";",
"}"
] | Estimate the radius of a cluster that encompasses a certain percentage of
the total training samples.
> **Note**: Since radius estimation scales quadratically in the number of
samples, for large datasets you can speed up the process by running it on
a sample subset of the training data.
@param \Rubix\ML\Datasets\Dataset $dataset
@param float $percentile
@param \Rubix\ML\Kernels\Distance\Distance|null $kernel
@throws \InvalidArgumentException
@return float | [
"Estimate",
"the",
"radius",
"of",
"a",
"cluster",
"that",
"encompasses",
"a",
"certain",
"percentage",
"of",
"the",
"total",
"training",
"samples",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/MeanShift.php#L137-L155 |
RubixML/RubixML | src/Clusterers/MeanShift.php | MeanShift.train | public function train(Dataset $dataset) : void
{
DatasetIsCompatibleWithEstimator::check($dataset, $this);
if ($this->logger) {
$this->logger->info('Learner init ' . Params::stringify([
'radius' => $this->radius,
'kernel' => $this->kernel,
'max_leaf_size' => $this->maxLeafSize,
'epochs' => $this->epochs,
'min_change' => $this->minChange,
'seeder' => $this->seeder,
'ratio' => $this->ratio,
]));
}
$n = $dataset->numRows();
$tree = new BallTree($this->maxLeafSize, $this->kernel);
if ($this->seeder and $n > self::MIN_SEEDS) {
$k = (int) round($this->ratio * $n);
$centroids = $this->seeder->seed($dataset, $k);
} else {
$centroids = $dataset->samples();
}
$tree->grow($dataset);
$previous = $centroids;
$this->steps = [];
for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
foreach ($centroids as $i => &$centroid) {
[$samples, $labels, $distances] = $tree->range($centroid, $this->radius);
$step = Matrix::quick($samples)
->transpose()
->mean()
->asArray();
$mu2 = Stats::mean($distances) ** 2;
$weight = exp(-$mu2 / $this->delta);
foreach ($centroid as $column => &$mean) {
$mean = ($weight * $step[$column]) / $weight;
}
foreach ($centroids as $j => $neighbor) {
if ($i === $j) {
continue 1;
}
$distance = $this->kernel->compute($centroid, $neighbor);
if ($distance < $this->radius) {
unset($centroids[$j]);
}
}
}
$shift = $this->shift($centroids, $previous);
$this->steps[] = $shift;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete, shift=$shift");
}
if (is_nan($shift)) {
break 1;
}
if ($shift < $this->minChange) {
break 1;
}
$previous = $centroids;
}
$this->centroids = array_values($centroids);
if ($this->logger) {
$this->logger->info('Training complete');
}
} | php | public function train(Dataset $dataset) : void
{
DatasetIsCompatibleWithEstimator::check($dataset, $this);
if ($this->logger) {
$this->logger->info('Learner init ' . Params::stringify([
'radius' => $this->radius,
'kernel' => $this->kernel,
'max_leaf_size' => $this->maxLeafSize,
'epochs' => $this->epochs,
'min_change' => $this->minChange,
'seeder' => $this->seeder,
'ratio' => $this->ratio,
]));
}
$n = $dataset->numRows();
$tree = new BallTree($this->maxLeafSize, $this->kernel);
if ($this->seeder and $n > self::MIN_SEEDS) {
$k = (int) round($this->ratio * $n);
$centroids = $this->seeder->seed($dataset, $k);
} else {
$centroids = $dataset->samples();
}
$tree->grow($dataset);
$previous = $centroids;
$this->steps = [];
for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
foreach ($centroids as $i => &$centroid) {
[$samples, $labels, $distances] = $tree->range($centroid, $this->radius);
$step = Matrix::quick($samples)
->transpose()
->mean()
->asArray();
$mu2 = Stats::mean($distances) ** 2;
$weight = exp(-$mu2 / $this->delta);
foreach ($centroid as $column => &$mean) {
$mean = ($weight * $step[$column]) / $weight;
}
foreach ($centroids as $j => $neighbor) {
if ($i === $j) {
continue 1;
}
$distance = $this->kernel->compute($centroid, $neighbor);
if ($distance < $this->radius) {
unset($centroids[$j]);
}
}
}
$shift = $this->shift($centroids, $previous);
$this->steps[] = $shift;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete, shift=$shift");
}
if (is_nan($shift)) {
break 1;
}
if ($shift < $this->minChange) {
break 1;
}
$previous = $centroids;
}
$this->centroids = array_values($centroids);
if ($this->logger) {
$this->logger->info('Training complete');
}
} | [
"public",
"function",
"train",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Learner init '",
".",
"Params",
"::",
"stringify",
"(",
"[",
"'radius'",
"=>",
"$",
"this",
"->",
"radius",
",",
"'kernel'",
"=>",
"$",
"this",
"->",
"kernel",
",",
"'max_leaf_size'",
"=>",
"$",
"this",
"->",
"maxLeafSize",
",",
"'epochs'",
"=>",
"$",
"this",
"->",
"epochs",
",",
"'min_change'",
"=>",
"$",
"this",
"->",
"minChange",
",",
"'seeder'",
"=>",
"$",
"this",
"->",
"seeder",
",",
"'ratio'",
"=>",
"$",
"this",
"->",
"ratio",
",",
"]",
")",
")",
";",
"}",
"$",
"n",
"=",
"$",
"dataset",
"->",
"numRows",
"(",
")",
";",
"$",
"tree",
"=",
"new",
"BallTree",
"(",
"$",
"this",
"->",
"maxLeafSize",
",",
"$",
"this",
"->",
"kernel",
")",
";",
"if",
"(",
"$",
"this",
"->",
"seeder",
"and",
"$",
"n",
">",
"self",
"::",
"MIN_SEEDS",
")",
"{",
"$",
"k",
"=",
"(",
"int",
")",
"round",
"(",
"$",
"this",
"->",
"ratio",
"*",
"$",
"n",
")",
";",
"$",
"centroids",
"=",
"$",
"this",
"->",
"seeder",
"->",
"seed",
"(",
"$",
"dataset",
",",
"$",
"k",
")",
";",
"}",
"else",
"{",
"$",
"centroids",
"=",
"$",
"dataset",
"->",
"samples",
"(",
")",
";",
"}",
"$",
"tree",
"->",
"grow",
"(",
"$",
"dataset",
")",
";",
"$",
"previous",
"=",
"$",
"centroids",
";",
"$",
"this",
"->",
"steps",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"epoch",
"=",
"1",
";",
"$",
"epoch",
"<=",
"$",
"this",
"->",
"epochs",
";",
"$",
"epoch",
"++",
")",
"{",
"foreach",
"(",
"$",
"centroids",
"as",
"$",
"i",
"=>",
"&",
"$",
"centroid",
")",
"{",
"[",
"$",
"samples",
",",
"$",
"labels",
",",
"$",
"distances",
"]",
"=",
"$",
"tree",
"->",
"range",
"(",
"$",
"centroid",
",",
"$",
"this",
"->",
"radius",
")",
";",
"$",
"step",
"=",
"Matrix",
"::",
"quick",
"(",
"$",
"samples",
")",
"->",
"transpose",
"(",
")",
"->",
"mean",
"(",
")",
"->",
"asArray",
"(",
")",
";",
"$",
"mu2",
"=",
"Stats",
"::",
"mean",
"(",
"$",
"distances",
")",
"**",
"2",
";",
"$",
"weight",
"=",
"exp",
"(",
"-",
"$",
"mu2",
"/",
"$",
"this",
"->",
"delta",
")",
";",
"foreach",
"(",
"$",
"centroid",
"as",
"$",
"column",
"=>",
"&",
"$",
"mean",
")",
"{",
"$",
"mean",
"=",
"(",
"$",
"weight",
"*",
"$",
"step",
"[",
"$",
"column",
"]",
")",
"/",
"$",
"weight",
";",
"}",
"foreach",
"(",
"$",
"centroids",
"as",
"$",
"j",
"=>",
"$",
"neighbor",
")",
"{",
"if",
"(",
"$",
"i",
"===",
"$",
"j",
")",
"{",
"continue",
"1",
";",
"}",
"$",
"distance",
"=",
"$",
"this",
"->",
"kernel",
"->",
"compute",
"(",
"$",
"centroid",
",",
"$",
"neighbor",
")",
";",
"if",
"(",
"$",
"distance",
"<",
"$",
"this",
"->",
"radius",
")",
"{",
"unset",
"(",
"$",
"centroids",
"[",
"$",
"j",
"]",
")",
";",
"}",
"}",
"}",
"$",
"shift",
"=",
"$",
"this",
"->",
"shift",
"(",
"$",
"centroids",
",",
"$",
"previous",
")",
";",
"$",
"this",
"->",
"steps",
"[",
"]",
"=",
"$",
"shift",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"\"Epoch $epoch complete, shift=$shift\"",
")",
";",
"}",
"if",
"(",
"is_nan",
"(",
"$",
"shift",
")",
")",
"{",
"break",
"1",
";",
"}",
"if",
"(",
"$",
"shift",
"<",
"$",
"this",
"->",
"minChange",
")",
"{",
"break",
"1",
";",
"}",
"$",
"previous",
"=",
"$",
"centroids",
";",
"}",
"$",
"this",
"->",
"centroids",
"=",
"array_values",
"(",
"$",
"centroids",
")",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Training complete'",
")",
";",
"}",
"}"
] | Train the learner with a dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Train",
"the",
"learner",
"with",
"a",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/MeanShift.php#L269-L357 |
RubixML/RubixML | src/Clusterers/MeanShift.php | MeanShift.assign | protected function assign(array $sample) : int
{
$bestDistance = INF;
$bestCluster = -1;
foreach ($this->centroids as $cluster => $centroid) {
$distance = $this->kernel->compute($sample, $centroid);
if ($distance < $bestDistance) {
$bestDistance = $distance;
$bestCluster = $cluster;
}
}
return (int) $bestCluster;
} | php | protected function assign(array $sample) : int
{
$bestDistance = INF;
$bestCluster = -1;
foreach ($this->centroids as $cluster => $centroid) {
$distance = $this->kernel->compute($sample, $centroid);
if ($distance < $bestDistance) {
$bestDistance = $distance;
$bestCluster = $cluster;
}
}
return (int) $bestCluster;
} | [
"protected",
"function",
"assign",
"(",
"array",
"$",
"sample",
")",
":",
"int",
"{",
"$",
"bestDistance",
"=",
"INF",
";",
"$",
"bestCluster",
"=",
"-",
"1",
";",
"foreach",
"(",
"$",
"this",
"->",
"centroids",
"as",
"$",
"cluster",
"=>",
"$",
"centroid",
")",
"{",
"$",
"distance",
"=",
"$",
"this",
"->",
"kernel",
"->",
"compute",
"(",
"$",
"sample",
",",
"$",
"centroid",
")",
";",
"if",
"(",
"$",
"distance",
"<",
"$",
"bestDistance",
")",
"{",
"$",
"bestDistance",
"=",
"$",
"distance",
";",
"$",
"bestCluster",
"=",
"$",
"cluster",
";",
"}",
"}",
"return",
"(",
"int",
")",
"$",
"bestCluster",
";",
"}"
] | Label a given sample based on its distance from a particular centroid.
@param array $sample
@return int | [
"Label",
"a",
"given",
"sample",
"based",
"on",
"its",
"distance",
"from",
"a",
"particular",
"centroid",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/MeanShift.php#L403-L418 |
RubixML/RubixML | src/Clusterers/MeanShift.php | MeanShift.membership | 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;
} | php | 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;
} | [
"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",
";",
"}"
] | Return the membership of a sample to each of the centroids.
@param array $sample
@return array | [
"Return",
"the",
"membership",
"of",
"a",
"sample",
"to",
"each",
"of",
"the",
"centroids",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/MeanShift.php#L426-L441 |
RubixML/RubixML | src/Clusterers/MeanShift.php | MeanShift.shift | protected function shift(array $current, array $previous) : float
{
$shift = 0.;
foreach ($current as $cluster => $centroid) {
$prevCentroid = $previous[$cluster];
foreach ($centroid as $column => $mean) {
$shift += abs($prevCentroid[$column] - $mean);
}
}
return $shift;
} | php | protected function shift(array $current, array $previous) : float
{
$shift = 0.;
foreach ($current as $cluster => $centroid) {
$prevCentroid = $previous[$cluster];
foreach ($centroid as $column => $mean) {
$shift += abs($prevCentroid[$column] - $mean);
}
}
return $shift;
} | [
"protected",
"function",
"shift",
"(",
"array",
"$",
"current",
",",
"array",
"$",
"previous",
")",
":",
"float",
"{",
"$",
"shift",
"=",
"0.",
";",
"foreach",
"(",
"$",
"current",
"as",
"$",
"cluster",
"=>",
"$",
"centroid",
")",
"{",
"$",
"prevCentroid",
"=",
"$",
"previous",
"[",
"$",
"cluster",
"]",
";",
"foreach",
"(",
"$",
"centroid",
"as",
"$",
"column",
"=>",
"$",
"mean",
")",
"{",
"$",
"shift",
"+=",
"abs",
"(",
"$",
"prevCentroid",
"[",
"$",
"column",
"]",
"-",
"$",
"mean",
")",
";",
"}",
"}",
"return",
"$",
"shift",
";",
"}"
] | Calculate the magnitude (l1) of centroid shift from the previous epoch.
@param array $current
@param array $previous
@return float | [
"Calculate",
"the",
"magnitude",
"(",
"l1",
")",
"of",
"centroid",
"shift",
"from",
"the",
"previous",
"epoch",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/MeanShift.php#L450-L463 |
RubixML/RubixML | src/AnomalyDetectors/LODA.php | LODA.train | public function train(Dataset $dataset) : void
{
DatasetIsCompatibleWithEstimator::check($dataset, $this);
[$m, $n] = $dataset->shape();
$this->r = Matrix::gaussian($n, $this->estimators);
if ($n >= self::MIN_SPARSE_DIMENSIONS) {
$mask = Matrix::rand($n, $this->estimators)
->less(sqrt($n) / $n);
$this->r = $this->r->multiply($mask);
}
$z = Matrix::quick($dataset->samples())
->matmul($this->r)
->transpose();
foreach ($z as $values) {
$min = min($values) - EPSILON;
$max = max($values) + EPSILON;
$edges = Vector::linspace($min, $max, $this->bins + 1)->asArray();
$edges[] = INF;
$counts = array_fill(0, $this->bins + 2, 0);
$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]++;
}
$densities = [];
foreach ($counts as $count) {
$densities[] = $count > 0
? -log($count / $m)
: -LOG_EPSILON;
}
$this->histograms[] = [$edges, $counts, $densities];
}
$this->n = $m;
} | php | public function train(Dataset $dataset) : void
{
DatasetIsCompatibleWithEstimator::check($dataset, $this);
[$m, $n] = $dataset->shape();
$this->r = Matrix::gaussian($n, $this->estimators);
if ($n >= self::MIN_SPARSE_DIMENSIONS) {
$mask = Matrix::rand($n, $this->estimators)
->less(sqrt($n) / $n);
$this->r = $this->r->multiply($mask);
}
$z = Matrix::quick($dataset->samples())
->matmul($this->r)
->transpose();
foreach ($z as $values) {
$min = min($values) - EPSILON;
$max = max($values) + EPSILON;
$edges = Vector::linspace($min, $max, $this->bins + 1)->asArray();
$edges[] = INF;
$counts = array_fill(0, $this->bins + 2, 0);
$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]++;
}
$densities = [];
foreach ($counts as $count) {
$densities[] = $count > 0
? -log($count / $m)
: -LOG_EPSILON;
}
$this->histograms[] = [$edges, $counts, $densities];
}
$this->n = $m;
} | [
"public",
"function",
"train",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"[",
"$",
"m",
",",
"$",
"n",
"]",
"=",
"$",
"dataset",
"->",
"shape",
"(",
")",
";",
"$",
"this",
"->",
"r",
"=",
"Matrix",
"::",
"gaussian",
"(",
"$",
"n",
",",
"$",
"this",
"->",
"estimators",
")",
";",
"if",
"(",
"$",
"n",
">=",
"self",
"::",
"MIN_SPARSE_DIMENSIONS",
")",
"{",
"$",
"mask",
"=",
"Matrix",
"::",
"rand",
"(",
"$",
"n",
",",
"$",
"this",
"->",
"estimators",
")",
"->",
"less",
"(",
"sqrt",
"(",
"$",
"n",
")",
"/",
"$",
"n",
")",
";",
"$",
"this",
"->",
"r",
"=",
"$",
"this",
"->",
"r",
"->",
"multiply",
"(",
"$",
"mask",
")",
";",
"}",
"$",
"z",
"=",
"Matrix",
"::",
"quick",
"(",
"$",
"dataset",
"->",
"samples",
"(",
")",
")",
"->",
"matmul",
"(",
"$",
"this",
"->",
"r",
")",
"->",
"transpose",
"(",
")",
";",
"foreach",
"(",
"$",
"z",
"as",
"$",
"values",
")",
"{",
"$",
"min",
"=",
"min",
"(",
"$",
"values",
")",
"-",
"EPSILON",
";",
"$",
"max",
"=",
"max",
"(",
"$",
"values",
")",
"+",
"EPSILON",
";",
"$",
"edges",
"=",
"Vector",
"::",
"linspace",
"(",
"$",
"min",
",",
"$",
"max",
",",
"$",
"this",
"->",
"bins",
"+",
"1",
")",
"->",
"asArray",
"(",
")",
";",
"$",
"edges",
"[",
"]",
"=",
"INF",
";",
"$",
"counts",
"=",
"array_fill",
"(",
"0",
",",
"$",
"this",
"->",
"bins",
"+",
"2",
",",
"0",
")",
";",
"$",
"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",
"]",
"++",
";",
"}",
"$",
"densities",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"counts",
"as",
"$",
"count",
")",
"{",
"$",
"densities",
"[",
"]",
"=",
"$",
"count",
">",
"0",
"?",
"-",
"log",
"(",
"$",
"count",
"/",
"$",
"m",
")",
":",
"-",
"LOG_EPSILON",
";",
"}",
"$",
"this",
"->",
"histograms",
"[",
"]",
"=",
"[",
"$",
"edges",
",",
"$",
"counts",
",",
"$",
"densities",
"]",
";",
"}",
"$",
"this",
"->",
"n",
"=",
"$",
"m",
";",
"}"
] | Train the learner with a dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Train",
"the",
"learner",
"with",
"a",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/AnomalyDetectors/LODA.php#L160-L215 |
RubixML/RubixML | src/AnomalyDetectors/LODA.php | LODA.partial | 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];
}
} | php | 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];
}
} | [
"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",
"]",
";",
"}",
"}"
] | Perform a partial train on the learner.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Perform",
"a",
"partial",
"train",
"on",
"the",
"learner",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/AnomalyDetectors/LODA.php#L223-L264 |
RubixML/RubixML | src/AnomalyDetectors/LODA.php | LODA.rank | 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);
} | php | 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);
} | [
"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",
")",
";",
"}"
] | Apply an arbitrary unnormalized scoring function over the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException
@throws \RuntimeException
@return array | [
"Apply",
"an",
"arbitrary",
"unnormalized",
"scoring",
"function",
"over",
"the",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/AnomalyDetectors/LODA.php#L287-L301 |
RubixML/RubixML | src/AnomalyDetectors/LODA.php | LODA.logLikelihood | protected function logLikelihood(Matrix $z) : array
{
$likelihoods = array_fill(0, $z->n(), 0.);
foreach ($z as $i => $values) {
[$edges, $counts, $densities] = $this->histograms[$i];
foreach ($values as $j => $value) {
foreach ($edges as $k => $edge) {
if ($value < $edge) {
$likelihoods[$j] += $densities[$k];
break 1;
}
}
}
}
foreach ($likelihoods as &$likelihood) {
$likelihood /= $this->estimators;
}
return $likelihoods;
} | php | protected function logLikelihood(Matrix $z) : array
{
$likelihoods = array_fill(0, $z->n(), 0.);
foreach ($z as $i => $values) {
[$edges, $counts, $densities] = $this->histograms[$i];
foreach ($values as $j => $value) {
foreach ($edges as $k => $edge) {
if ($value < $edge) {
$likelihoods[$j] += $densities[$k];
break 1;
}
}
}
}
foreach ($likelihoods as &$likelihood) {
$likelihood /= $this->estimators;
}
return $likelihoods;
} | [
"protected",
"function",
"logLikelihood",
"(",
"Matrix",
"$",
"z",
")",
":",
"array",
"{",
"$",
"likelihoods",
"=",
"array_fill",
"(",
"0",
",",
"$",
"z",
"->",
"n",
"(",
")",
",",
"0.",
")",
";",
"foreach",
"(",
"$",
"z",
"as",
"$",
"i",
"=>",
"$",
"values",
")",
"{",
"[",
"$",
"edges",
",",
"$",
"counts",
",",
"$",
"densities",
"]",
"=",
"$",
"this",
"->",
"histograms",
"[",
"$",
"i",
"]",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"j",
"=>",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"edges",
"as",
"$",
"k",
"=>",
"$",
"edge",
")",
"{",
"if",
"(",
"$",
"value",
"<",
"$",
"edge",
")",
"{",
"$",
"likelihoods",
"[",
"$",
"j",
"]",
"+=",
"$",
"densities",
"[",
"$",
"k",
"]",
";",
"break",
"1",
";",
"}",
"}",
"}",
"}",
"foreach",
"(",
"$",
"likelihoods",
"as",
"&",
"$",
"likelihood",
")",
"{",
"$",
"likelihood",
"/=",
"$",
"this",
"->",
"estimators",
";",
"}",
"return",
"$",
"likelihoods",
";",
"}"
] | Return the negative log likelihoods of each projection.
@param \Rubix\Tensor\Matrix $z
@return array | [
"Return",
"the",
"negative",
"log",
"likelihoods",
"of",
"each",
"projection",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/AnomalyDetectors/LODA.php#L309-L332 |
RubixML/RubixML | src/Kernels/Distance/Euclidean.php | Euclidean.compute | public function compute(array $a, array $b) : float
{
$distance = 0.;
foreach ($a as $i => $value) {
$distance += ($value - $b[$i]) ** 2;
}
return sqrt($distance);
} | php | public function compute(array $a, array $b) : float
{
$distance = 0.;
foreach ($a as $i => $value) {
$distance += ($value - $b[$i]) ** 2;
}
return sqrt($distance);
} | [
"public",
"function",
"compute",
"(",
"array",
"$",
"a",
",",
"array",
"$",
"b",
")",
":",
"float",
"{",
"$",
"distance",
"=",
"0.",
";",
"foreach",
"(",
"$",
"a",
"as",
"$",
"i",
"=>",
"$",
"value",
")",
"{",
"$",
"distance",
"+=",
"(",
"$",
"value",
"-",
"$",
"b",
"[",
"$",
"i",
"]",
")",
"**",
"2",
";",
"}",
"return",
"sqrt",
"(",
"$",
"distance",
")",
";",
"}"
] | Compute the distance between two vectors.
@param array $a
@param array $b
@return float | [
"Compute",
"the",
"distance",
"between",
"two",
"vectors",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Kernels/Distance/Euclidean.php#L24-L33 |
RubixML/RubixML | src/Transformers/GaussianRandomProjector.php | GaussianRandomProjector.minDimensions | public static function minDimensions(int $n, float $maxDistortion = 0.1) : int
{
return (int) round(4. * log($n)
/ ($maxDistortion ** 2 / 2. - $maxDistortion ** 3 / 3.));
} | php | public static function minDimensions(int $n, float $maxDistortion = 0.1) : int
{
return (int) round(4. * log($n)
/ ($maxDistortion ** 2 / 2. - $maxDistortion ** 3 / 3.));
} | [
"public",
"static",
"function",
"minDimensions",
"(",
"int",
"$",
"n",
",",
"float",
"$",
"maxDistortion",
"=",
"0.1",
")",
":",
"int",
"{",
"return",
"(",
"int",
")",
"round",
"(",
"4.",
"*",
"log",
"(",
"$",
"n",
")",
"/",
"(",
"$",
"maxDistortion",
"**",
"2",
"/",
"2.",
"-",
"$",
"maxDistortion",
"**",
"3",
"/",
"3.",
")",
")",
";",
"}"
] | Calculate the minimum number of dimensions for n total samples with a
given maximum distortion using the Johnson-Lindenstrauss lemma.
@param int $n
@param float $maxDistortion
@return int | [
"Calculate",
"the",
"minimum",
"number",
"of",
"dimensions",
"for",
"n",
"total",
"samples",
"with",
"a",
"given",
"maximum",
"distortion",
"using",
"the",
"Johnson",
"-",
"Lindenstrauss",
"lemma",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/GaussianRandomProjector.php#L49-L53 |
RubixML/RubixML | src/Transformers/GaussianRandomProjector.php | GaussianRandomProjector.fit | public function fit(Dataset $dataset) : void
{
if (!$dataset->homogeneous() or $dataset->columnType(0) !== DataType::CONTINUOUS) {
throw new InvalidArgumentException('This transformer only works'
. ' with continuous features.');
}
$this->r = Matrix::gaussian($dataset->numColumns(), $this->dimensions);
} | php | public function fit(Dataset $dataset) : void
{
if (!$dataset->homogeneous() or $dataset->columnType(0) !== DataType::CONTINUOUS) {
throw new InvalidArgumentException('This transformer only works'
. ' with continuous features.');
}
$this->r = Matrix::gaussian($dataset->numColumns(), $this->dimensions);
} | [
"public",
"function",
"fit",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"if",
"(",
"!",
"$",
"dataset",
"->",
"homogeneous",
"(",
")",
"or",
"$",
"dataset",
"->",
"columnType",
"(",
"0",
")",
"!==",
"DataType",
"::",
"CONTINUOUS",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'This transformer only works'",
".",
"' with continuous features.'",
")",
";",
"}",
"$",
"this",
"->",
"r",
"=",
"Matrix",
"::",
"gaussian",
"(",
"$",
"dataset",
"->",
"numColumns",
"(",
")",
",",
"$",
"this",
"->",
"dimensions",
")",
";",
"}"
] | Fit the transformer to the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Fit",
"the",
"transformer",
"to",
"the",
"dataset",
"."
] | train | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/GaussianRandomProjector.php#L85-L93 |