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
RubixML/RubixML
src/Transformers/GaussianRandomProjector.php
GaussianRandomProjector.transform
public function transform(array &$samples) : void { if (!$this->r) { throw new RuntimeException('Transformer has not been fitted.'); } $samples = Matrix::quick($samples) ->matmul($this->r) ->asArray(); }
php
public function transform(array &$samples) : void { if (!$this->r) { throw new RuntimeException('Transformer has not been fitted.'); } $samples = Matrix::quick($samples) ->matmul($this->r) ->asArray(); }
[ "public", "function", "transform", "(", "array", "&", "$", "samples", ")", ":", "void", "{", "if", "(", "!", "$", "this", "->", "r", ")", "{", "throw", "new", "RuntimeException", "(", "'Transformer has not been fitted.'", ")", ";", "}", "$", "samples", "=", "Matrix", "::", "quick", "(", "$", "samples", ")", "->", "matmul", "(", "$", "this", "->", "r", ")", "->", "asArray", "(", ")", ";", "}" ]
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/GaussianRandomProjector.php#L101-L110
RubixML/RubixML
src/Other/Tokenizers/SkipGram.php
SkipGram.tokenize
public function tokenize(string $string) : array { $sentences = preg_split(self::SENTENCE_REGEX, $string) ?: []; $skipGrams = []; foreach ($sentences as $sentence) { $words = []; preg_match_all(self::WORD_REGEX, $sentence, $words); $words = $words[0]; $length = count($words) - ($this->n + $this->skip); for ($i = 0; $i <= $length; $i++) { $first = $words[$i]; for ($j = 0; $j <= $this->skip; $j++) { $skipGram = $first; for ($k = 1; $k < $this->n; $k++) { $skipGram .= self::SEPARATOR . $words[$i + $j + $k]; } $skipGrams[] = $skipGram; } } $last = array_slice($words, -$this->n); $skipGrams[] = implode(self::SEPARATOR, $last); } return $skipGrams; }
php
public function tokenize(string $string) : array { $sentences = preg_split(self::SENTENCE_REGEX, $string) ?: []; $skipGrams = []; foreach ($sentences as $sentence) { $words = []; preg_match_all(self::WORD_REGEX, $sentence, $words); $words = $words[0]; $length = count($words) - ($this->n + $this->skip); for ($i = 0; $i <= $length; $i++) { $first = $words[$i]; for ($j = 0; $j <= $this->skip; $j++) { $skipGram = $first; for ($k = 1; $k < $this->n; $k++) { $skipGram .= self::SEPARATOR . $words[$i + $j + $k]; } $skipGrams[] = $skipGram; } } $last = array_slice($words, -$this->n); $skipGrams[] = implode(self::SEPARATOR, $last); } return $skipGrams; }
[ "public", "function", "tokenize", "(", "string", "$", "string", ")", ":", "array", "{", "$", "sentences", "=", "preg_split", "(", "self", "::", "SENTENCE_REGEX", ",", "$", "string", ")", "?", ":", "[", "]", ";", "$", "skipGrams", "=", "[", "]", ";", "foreach", "(", "$", "sentences", "as", "$", "sentence", ")", "{", "$", "words", "=", "[", "]", ";", "preg_match_all", "(", "self", "::", "WORD_REGEX", ",", "$", "sentence", ",", "$", "words", ")", ";", "$", "words", "=", "$", "words", "[", "0", "]", ";", "$", "length", "=", "count", "(", "$", "words", ")", "-", "(", "$", "this", "->", "n", "+", "$", "this", "->", "skip", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<=", "$", "length", ";", "$", "i", "++", ")", "{", "$", "first", "=", "$", "words", "[", "$", "i", "]", ";", "for", "(", "$", "j", "=", "0", ";", "$", "j", "<=", "$", "this", "->", "skip", ";", "$", "j", "++", ")", "{", "$", "skipGram", "=", "$", "first", ";", "for", "(", "$", "k", "=", "1", ";", "$", "k", "<", "$", "this", "->", "n", ";", "$", "k", "++", ")", "{", "$", "skipGram", ".=", "self", "::", "SEPARATOR", ".", "$", "words", "[", "$", "i", "+", "$", "j", "+", "$", "k", "]", ";", "}", "$", "skipGrams", "[", "]", "=", "$", "skipGram", ";", "}", "}", "$", "last", "=", "array_slice", "(", "$", "words", ",", "-", "$", "this", "->", "n", ")", ";", "$", "skipGrams", "[", "]", "=", "implode", "(", "self", "::", "SEPARATOR", ",", "$", "last", ")", ";", "}", "return", "$", "skipGrams", ";", "}" ]
Tokenize a block of text. @param string $string @return array
[ "Tokenize", "a", "block", "of", "text", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Tokenizers/SkipGram.php#L69-L104
RubixML/RubixML
src/Datasets/Generators/Blob.php
Blob.generate
public function generate(int $n) : Dataset { $samples = Matrix::gaussian($n, $this->dimensions()) ->multiply($this->stddev) ->add($this->center) ->asArray(); return Unlabeled::quick($samples); }
php
public function generate(int $n) : Dataset { $samples = Matrix::gaussian($n, $this->dimensions()) ->multiply($this->stddev) ->add($this->center) ->asArray(); return Unlabeled::quick($samples); }
[ "public", "function", "generate", "(", "int", "$", "n", ")", ":", "Dataset", "{", "$", "samples", "=", "Matrix", "::", "gaussian", "(", "$", "n", ",", "$", "this", "->", "dimensions", "(", ")", ")", "->", "multiply", "(", "$", "this", "->", "stddev", ")", "->", "add", "(", "$", "this", "->", "center", ")", "->", "asArray", "(", ")", ";", "return", "Unlabeled", "::", "quick", "(", "$", "samples", ")", ";", "}" ]
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/Blob.php#L99-L107
RubixML/RubixML
src/NeuralNet/Initializers/Xavier2.php
Xavier2.initialize
public function initialize(int $fanIn, int $fanOut) : Matrix { $scale = (6. / ($fanIn + $fanOut)) ** 0.25; return Matrix::uniform($fanOut, $fanIn)->multiply($scale); }
php
public function initialize(int $fanIn, int $fanOut) : Matrix { $scale = (6. / ($fanIn + $fanOut)) ** 0.25; return Matrix::uniform($fanOut, $fanIn)->multiply($scale); }
[ "public", "function", "initialize", "(", "int", "$", "fanIn", ",", "int", "$", "fanOut", ")", ":", "Matrix", "{", "$", "scale", "=", "(", "6.", "/", "(", "$", "fanIn", "+", "$", "fanOut", ")", ")", "**", "0.25", ";", "return", "Matrix", "::", "uniform", "(", "$", "fanOut", ",", "$", "fanIn", ")", "->", "multiply", "(", "$", "scale", ")", ";", "}" ]
Initialize a weight matrix W in the dimensions fan in x fan out. @param int $fanIn @param int $fanOut @return \Rubix\Tensor\Matrix
[ "Initialize", "a", "weight", "matrix", "W", "in", "the", "dimensions", "fan", "in", "x", "fan", "out", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Initializers/Xavier2.php#L32-L37
RubixML/RubixML
src/NeuralNet/Layers/Activation.php
Activation.initialize
public function initialize(int $fanIn) : int { $fanOut = $fanIn; $this->width = $fanOut; return $fanOut; }
php
public function initialize(int $fanIn) : int { $fanOut = $fanIn; $this->width = $fanOut; return $fanOut; }
[ "public", "function", "initialize", "(", "int", "$", "fanIn", ")", ":", "int", "{", "$", "fanOut", "=", "$", "fanIn", ";", "$", "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/Activation.php#L80-L87
RubixML/RubixML
src/NeuralNet/Layers/Activation.php
Activation.forward
public function forward(Matrix $input) : Matrix { $this->input = $input; $this->computed = $this->activationFunction->compute($input); return $this->computed; }
php
public function forward(Matrix $input) : Matrix { $this->input = $input; $this->computed = $this->activationFunction->compute($input); return $this->computed; }
[ "public", "function", "forward", "(", "Matrix", "$", "input", ")", ":", "Matrix", "{", "$", "this", "->", "input", "=", "$", "input", ";", "$", "this", "->", "computed", "=", "$", "this", "->", "activationFunction", "->", "compute", "(", "$", "input", ")", ";", "return", "$", "this", "->", "computed", ";", "}" ]
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/Activation.php#L95-L102
RubixML/RubixML
src/NeuralNet/Layers/Activation.php
Activation.back
public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred { if (!$this->input or !$this->computed) { throw new RuntimeException('Must perform forward pass before' . ' backpropagating.'); } $input = $this->input; $computed = $this->computed; unset($this->input, $this->computed); return new Deferred(function () use ($input, $computed, $prevGradient) { return $this->activationFunction ->differentiate($input, $computed) ->multiply($prevGradient->result()); }); }
php
public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred { if (!$this->input or !$this->computed) { throw new RuntimeException('Must perform forward pass before' . ' backpropagating.'); } $input = $this->input; $computed = $this->computed; unset($this->input, $this->computed); return new Deferred(function () use ($input, $computed, $prevGradient) { return $this->activationFunction ->differentiate($input, $computed) ->multiply($prevGradient->result()); }); }
[ "public", "function", "back", "(", "Deferred", "$", "prevGradient", ",", "Optimizer", "$", "optimizer", ")", ":", "Deferred", "{", "if", "(", "!", "$", "this", "->", "input", "or", "!", "$", "this", "->", "computed", ")", "{", "throw", "new", "RuntimeException", "(", "'Must perform forward pass before'", ".", "' backpropagating.'", ")", ";", "}", "$", "input", "=", "$", "this", "->", "input", ";", "$", "computed", "=", "$", "this", "->", "computed", ";", "unset", "(", "$", "this", "->", "input", ",", "$", "this", "->", "computed", ")", ";", "return", "new", "Deferred", "(", "function", "(", ")", "use", "(", "$", "input", ",", "$", "computed", ",", "$", "prevGradient", ")", "{", "return", "$", "this", "->", "activationFunction", "->", "differentiate", "(", "$", "input", ",", "$", "computed", ")", "->", "multiply", "(", "$", "prevGradient", "->", "result", "(", ")", ")", ";", "}", ")", ";", "}" ]
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/Activation.php#L123-L140
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.fromIterator
public static function fromIterator(iterable $samples) : self { $samples = is_array($samples) ? $samples : iterator_to_array($samples, false); return self::build($samples); }
php
public static function fromIterator(iterable $samples) : self { $samples = is_array($samples) ? $samples : iterator_to_array($samples, false); return self::build($samples); }
[ "public", "static", "function", "fromIterator", "(", "iterable", "$", "samples", ")", ":", "self", "{", "$", "samples", "=", "is_array", "(", "$", "samples", ")", "?", "$", "samples", ":", "iterator_to_array", "(", "$", "samples", ",", "false", ")", ";", "return", "self", "::", "build", "(", "$", "samples", ")", ";", "}" ]
Build a dataset from an iterator. @param iterable $samples @return self
[ "Build", "a", "dataset", "from", "an", "iterator", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L51-L58
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.head
public function head(int $n = 10) : self { return self::quick(array_slice($this->samples, 0, $n)); }
php
public function head(int $n = 10) : self { return self::quick(array_slice($this->samples, 0, $n)); }
[ "public", "function", "head", "(", "int", "$", "n", "=", "10", ")", ":", "self", "{", "return", "self", "::", "quick", "(", "array_slice", "(", "$", "this", "->", "samples", ",", "0", ",", "$", "n", ")", ")", ";", "}" ]
Return a dataset containing only the first n samples. @param int $n @return self
[ "Return", "a", "dataset", "containing", "only", "the", "first", "n", "samples", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L91-L94
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.tail
public function tail(int $n = 10) : self { return self::quick(array_slice($this->samples, -$n)); }
php
public function tail(int $n = 10) : self { return self::quick(array_slice($this->samples, -$n)); }
[ "public", "function", "tail", "(", "int", "$", "n", "=", "10", ")", ":", "self", "{", "return", "self", "::", "quick", "(", "array_slice", "(", "$", "this", "->", "samples", ",", "-", "$", "n", ")", ")", ";", "}" ]
Return a dataset containing only the last n samples. @param int $n @return self
[ "Return", "a", "dataset", "containing", "only", "the", "last", "n", "samples", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L102-L105
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.prepend
public function prepend(Dataset $dataset) : Dataset { return self::quick(array_merge($dataset->samples(), $this->samples)); }
php
public function prepend(Dataset $dataset) : Dataset { return self::quick(array_merge($dataset->samples(), $this->samples)); }
[ "public", "function", "prepend", "(", "Dataset", "$", "dataset", ")", ":", "Dataset", "{", "return", "self", "::", "quick", "(", "array_merge", "(", "$", "dataset", "->", "samples", "(", ")", ",", "$", "this", "->", "samples", ")", ")", ";", "}" ]
Prepend this dataset with another dataset. @param \Rubix\ML\Datasets\Dataset $dataset @return \Rubix\ML\Datasets\Dataset
[ "Prepend", "this", "dataset", "with", "another", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L135-L138
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.append
public function append(Dataset $dataset) : Dataset { return self::quick(array_merge($this->samples, $dataset->samples())); }
php
public function append(Dataset $dataset) : Dataset { return self::quick(array_merge($this->samples, $dataset->samples())); }
[ "public", "function", "append", "(", "Dataset", "$", "dataset", ")", ":", "Dataset", "{", "return", "self", "::", "quick", "(", "array_merge", "(", "$", "this", "->", "samples", ",", "$", "dataset", "->", "samples", "(", ")", ")", ")", ";", "}" ]
Append this dataset with another dataset. @param \Rubix\ML\Datasets\Dataset $dataset @return \Rubix\ML\Datasets\Dataset
[ "Append", "this", "dataset", "with", "another", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L146-L149
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.splice
public function splice(int $offset, int $n) : self { return self::quick(array_splice($this->samples, $offset, $n)); }
php
public function splice(int $offset, int $n) : self { return self::quick(array_splice($this->samples, $offset, $n)); }
[ "public", "function", "splice", "(", "int", "$", "offset", ",", "int", "$", "n", ")", ":", "self", "{", "return", "self", "::", "quick", "(", "array_splice", "(", "$", "this", "->", "samples", ",", "$", "offset", ",", "$", "n", ")", ")", ";", "}" ]
Remove a size n chunk of the dataset starting at offset and return it in a new dataset. @param int $offset @param int $n @return self
[ "Remove", "a", "size", "n", "chunk", "of", "the", "dataset", "starting", "at", "offset", "and", "return", "it", "in", "a", "new", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L159-L162
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.split
public function split(float $ratio = 0.5) : array { if ($ratio <= 0. or $ratio >= 1.) { throw new InvalidArgumentException('Split ratio must be strictly' . " between 0 and 1, $ratio given."); } $p = (int) ($ratio * $this->numRows()); $left = self::quick(array_slice($this->samples, 0, $p)); $right = self::quick(array_slice($this->samples, $p)); return [$left, $right]; }
php
public function split(float $ratio = 0.5) : array { if ($ratio <= 0. or $ratio >= 1.) { throw new InvalidArgumentException('Split ratio must be strictly' . " between 0 and 1, $ratio given."); } $p = (int) ($ratio * $this->numRows()); $left = self::quick(array_slice($this->samples, 0, $p)); $right = self::quick(array_slice($this->samples, $p)); return [$left, $right]; }
[ "public", "function", "split", "(", "float", "$", "ratio", "=", "0.5", ")", ":", "array", "{", "if", "(", "$", "ratio", "<=", "0.", "or", "$", "ratio", ">=", "1.", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Split ratio must be strictly'", ".", "\" between 0 and 1, $ratio given.\"", ")", ";", "}", "$", "p", "=", "(", "int", ")", "(", "$", "ratio", "*", "$", "this", "->", "numRows", "(", ")", ")", ";", "$", "left", "=", "self", "::", "quick", "(", "array_slice", "(", "$", "this", "->", "samples", ",", "0", ",", "$", "p", ")", ")", ";", "$", "right", "=", "self", "::", "quick", "(", "array_slice", "(", "$", "this", "->", "samples", ",", "$", "p", ")", ")", ";", "return", "[", "$", "left", ",", "$", "right", "]", ";", "}" ]
Split the dataset into two stratified subsets with a given ratio of samples. @param float $ratio @throws \InvalidArgumentException @return array
[ "Split", "the", "dataset", "into", "two", "stratified", "subsets", "with", "a", "given", "ratio", "of", "samples", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L219-L232
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.fold
public function fold(int $k = 3) : array { if ($k < 2) { throw new InvalidArgumentException('Cannot create less than 2' . " folds, $k given."); } $samples = $this->samples; $n = (int) floor(count($samples) / $k); $folds = []; for ($i = 0; $i < $k; $i++) { $folds[] = self::quick(array_splice($samples, 0, $n)); } return $folds; }
php
public function fold(int $k = 3) : array { if ($k < 2) { throw new InvalidArgumentException('Cannot create less than 2' . " folds, $k given."); } $samples = $this->samples; $n = (int) floor(count($samples) / $k); $folds = []; for ($i = 0; $i < $k; $i++) { $folds[] = self::quick(array_splice($samples, 0, $n)); } return $folds; }
[ "public", "function", "fold", "(", "int", "$", "k", "=", "3", ")", ":", "array", "{", "if", "(", "$", "k", "<", "2", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Cannot create less than 2'", ".", "\" folds, $k given.\"", ")", ";", "}", "$", "samples", "=", "$", "this", "->", "samples", ";", "$", "n", "=", "(", "int", ")", "floor", "(", "count", "(", "$", "samples", ")", "/", "$", "k", ")", ";", "$", "folds", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "k", ";", "$", "i", "++", ")", "{", "$", "folds", "[", "]", "=", "self", "::", "quick", "(", "array_splice", "(", "$", "samples", ",", "0", ",", "$", "n", ")", ")", ";", "}", "return", "$", "folds", ";", "}" ]
Fold the dataset k - 1 times to form k equal size datasets. @param int $k @throws \InvalidArgumentException @return array
[ "Fold", "the", "dataset", "k", "-", "1", "times", "to", "form", "k", "equal", "size", "datasets", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L241-L259
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.batch
public function batch(int $n = 50) : array { $batches = []; $samples = $this->samples; foreach (array_chunk($this->samples, $n) as $batch) { $batches[] = self::quick($batch); } return $batches; }
php
public function batch(int $n = 50) : array { $batches = []; $samples = $this->samples; foreach (array_chunk($this->samples, $n) as $batch) { $batches[] = self::quick($batch); } return $batches; }
[ "public", "function", "batch", "(", "int", "$", "n", "=", "50", ")", ":", "array", "{", "$", "batches", "=", "[", "]", ";", "$", "samples", "=", "$", "this", "->", "samples", ";", "foreach", "(", "array_chunk", "(", "$", "this", "->", "samples", ",", "$", "n", ")", "as", "$", "batch", ")", "{", "$", "batches", "[", "]", "=", "self", "::", "quick", "(", "$", "batch", ")", ";", "}", "return", "$", "batches", ";", "}" ]
Generate a collection of batches of size n from the dataset. If there are not enough samples to fill an entire batch, then the dataset will contain as many samples as possible. @param int $n @return array
[ "Generate", "a", "collection", "of", "batches", "of", "size", "n", "from", "the", "dataset", ".", "If", "there", "are", "not", "enough", "samples", "to", "fill", "an", "entire", "batch", "then", "the", "dataset", "will", "contain", "as", "many", "samples", "as", "possible", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L269-L280
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.partition
public function partition(int $column, $value) : array { if (!is_string($value) and !is_numeric($value)) { throw new InvalidArgumentException('Value must be a string or' . ' numeric type, ' . gettype($value) . ' given.'); } $left = $right = []; if ($this->columnType($column) === DataType::CATEGORICAL) { foreach ($this->samples as $i => $sample) { if ($sample[$column] === $value) { $left[] = $sample; } else { $right[] = $sample; } } } else { foreach ($this->samples as $i => $sample) { if ($sample[$column] < $value) { $left[] = $sample; } else { $right[] = $sample; } } } return [ self::quick($left), self::quick($right), ]; }
php
public function partition(int $column, $value) : array { if (!is_string($value) and !is_numeric($value)) { throw new InvalidArgumentException('Value must be a string or' . ' numeric type, ' . gettype($value) . ' given.'); } $left = $right = []; if ($this->columnType($column) === DataType::CATEGORICAL) { foreach ($this->samples as $i => $sample) { if ($sample[$column] === $value) { $left[] = $sample; } else { $right[] = $sample; } } } else { foreach ($this->samples as $i => $sample) { if ($sample[$column] < $value) { $left[] = $sample; } else { $right[] = $sample; } } } return [ self::quick($left), self::quick($right), ]; }
[ "public", "function", "partition", "(", "int", "$", "column", ",", "$", "value", ")", ":", "array", "{", "if", "(", "!", "is_string", "(", "$", "value", ")", "and", "!", "is_numeric", "(", "$", "value", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Value must be a string or'", ".", "' numeric type, '", ".", "gettype", "(", "$", "value", ")", ".", "' given.'", ")", ";", "}", "$", "left", "=", "$", "right", "=", "[", "]", ";", "if", "(", "$", "this", "->", "columnType", "(", "$", "column", ")", "===", "DataType", "::", "CATEGORICAL", ")", "{", "foreach", "(", "$", "this", "->", "samples", "as", "$", "i", "=>", "$", "sample", ")", "{", "if", "(", "$", "sample", "[", "$", "column", "]", "===", "$", "value", ")", "{", "$", "left", "[", "]", "=", "$", "sample", ";", "}", "else", "{", "$", "right", "[", "]", "=", "$", "sample", ";", "}", "}", "}", "else", "{", "foreach", "(", "$", "this", "->", "samples", "as", "$", "i", "=>", "$", "sample", ")", "{", "if", "(", "$", "sample", "[", "$", "column", "]", "<", "$", "value", ")", "{", "$", "left", "[", "]", "=", "$", "sample", ";", "}", "else", "{", "$", "right", "[", "]", "=", "$", "sample", ";", "}", "}", "}", "return", "[", "self", "::", "quick", "(", "$", "left", ")", ",", "self", "::", "quick", "(", "$", "right", ")", ",", "]", ";", "}" ]
Partition the dataset into left and right subsets by a specified feature column. The dataset is split such that, for categorical values, the left subset contains all samples that match the value and the right side contains samples that do not match. For continuous values, the left side contains all the samples that are less than the target value, and the right side contains the samples that are greater than or equal to the value. @param int $column @param mixed $value @throws \InvalidArgumentException @return self[]
[ "Partition", "the", "dataset", "into", "left", "and", "right", "subsets", "by", "a", "specified", "feature", "column", ".", "The", "dataset", "is", "split", "such", "that", "for", "categorical", "values", "the", "left", "subset", "contains", "all", "samples", "that", "match", "the", "value", "and", "the", "right", "side", "contains", "samples", "that", "do", "not", "match", ".", "For", "continuous", "values", "the", "left", "side", "contains", "all", "the", "samples", "that", "are", "less", "than", "the", "target", "value", "and", "the", "right", "side", "contains", "the", "samples", "that", "are", "greater", "than", "or", "equal", "to", "the", "value", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L296-L327
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.spatialPartition
public function spatialPartition(array $leftCentroid, array $rightCentroid, Distance $kernel) { if (count($leftCentroid) !== count($rightCentroid)) { throw new InvalidArgumentException('Dimensionality mismatch between' . ' left and right centroids.'); } $left = $right = []; foreach ($this->samples as $i => $sample) { $lHat = $kernel->compute($sample, $leftCentroid); $rHat = $kernel->compute($sample, $rightCentroid); if ($lHat < $rHat) { $left[] = $sample; } else { $right[] = $sample; } } return [ self::quick($left), self::quick($right), ]; }
php
public function spatialPartition(array $leftCentroid, array $rightCentroid, Distance $kernel) { if (count($leftCentroid) !== count($rightCentroid)) { throw new InvalidArgumentException('Dimensionality mismatch between' . ' left and right centroids.'); } $left = $right = []; foreach ($this->samples as $i => $sample) { $lHat = $kernel->compute($sample, $leftCentroid); $rHat = $kernel->compute($sample, $rightCentroid); if ($lHat < $rHat) { $left[] = $sample; } else { $right[] = $sample; } } return [ self::quick($left), self::quick($right), ]; }
[ "public", "function", "spatialPartition", "(", "array", "$", "leftCentroid", ",", "array", "$", "rightCentroid", ",", "Distance", "$", "kernel", ")", "{", "if", "(", "count", "(", "$", "leftCentroid", ")", "!==", "count", "(", "$", "rightCentroid", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Dimensionality mismatch between'", ".", "' left and right centroids.'", ")", ";", "}", "$", "left", "=", "$", "right", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "samples", "as", "$", "i", "=>", "$", "sample", ")", "{", "$", "lHat", "=", "$", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "leftCentroid", ")", ";", "$", "rHat", "=", "$", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "rightCentroid", ")", ";", "if", "(", "$", "lHat", "<", "$", "rHat", ")", "{", "$", "left", "[", "]", "=", "$", "sample", ";", "}", "else", "{", "$", "right", "[", "]", "=", "$", "sample", ";", "}", "}", "return", "[", "self", "::", "quick", "(", "$", "left", ")", ",", "self", "::", "quick", "(", "$", "right", ")", ",", "]", ";", "}" ]
Partition the dataset into left and right subsets based on their distance between two centroids. @param array $leftCentroid @param array $rightCentroid @param \Rubix\ML\Kernels\Distance\Distance $kernel @throws \InvalidArgumentException @return array
[ "Partition", "the", "dataset", "into", "left", "and", "right", "subsets", "based", "on", "their", "distance", "between", "two", "centroids", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L339-L363
RubixML/RubixML
src/Datasets/Unlabeled.php
Unlabeled.randomSubsetWithReplacement
public function randomSubsetWithReplacement(int $n) : self { if ($n < 1) { throw new InvalidArgumentException('Cannot generate a subset of' . " less than 1 sample, $n given."); } $max = $this->numRows() - 1; $subset = []; for ($i = 0; $i < $n; $i++) { $subset[] = $this->samples[rand(0, $max)]; } return self::quick($subset); }
php
public function randomSubsetWithReplacement(int $n) : self { if ($n < 1) { throw new InvalidArgumentException('Cannot generate a subset of' . " less than 1 sample, $n given."); } $max = $this->numRows() - 1; $subset = []; for ($i = 0; $i < $n; $i++) { $subset[] = $this->samples[rand(0, $max)]; } return self::quick($subset); }
[ "public", "function", "randomSubsetWithReplacement", "(", "int", "$", "n", ")", ":", "self", "{", "if", "(", "$", "n", "<", "1", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Cannot generate a subset of'", ".", "\" less than 1 sample, $n given.\"", ")", ";", "}", "$", "max", "=", "$", "this", "->", "numRows", "(", ")", "-", "1", ";", "$", "subset", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "n", ";", "$", "i", "++", ")", "{", "$", "subset", "[", "]", "=", "$", "this", "->", "samples", "[", "rand", "(", "0", ",", "$", "max", ")", "]", ";", "}", "return", "self", "::", "quick", "(", "$", "subset", ")", ";", "}" ]
Generate a random subset with replacement. @param int $n @throws \InvalidArgumentException @return self
[ "Generate", "a", "random", "subset", "with", "replacement", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L372-L388
RubixML/RubixML
src/Regressors/ExtraTreeRegressor.php
ExtraTreeRegressor.split
protected function split(Labeled $dataset) : Decision { $bestImpurity = INF; $bestColumn = $bestValue = null; $bestGroups = []; $max = $dataset->numRows() - 1; shuffle($this->columns); foreach (array_slice($this->columns, 0, $this->maxFeatures) as $column) { $sample = $dataset->row(rand(0, $max)); $value = $sample[$column]; $groups = $dataset->partition($column, $value); $impurity = $this->splitImpurity($groups); if ($impurity < $bestImpurity) { $bestColumn = $column; $bestValue = $value; $bestGroups = $groups; $bestImpurity = $impurity; } if ($impurity < $this->tolerance) { break 1; } } return new Decision($bestColumn, $bestValue, $bestGroups, $bestImpurity); }
php
protected function split(Labeled $dataset) : Decision { $bestImpurity = INF; $bestColumn = $bestValue = null; $bestGroups = []; $max = $dataset->numRows() - 1; shuffle($this->columns); foreach (array_slice($this->columns, 0, $this->maxFeatures) as $column) { $sample = $dataset->row(rand(0, $max)); $value = $sample[$column]; $groups = $dataset->partition($column, $value); $impurity = $this->splitImpurity($groups); if ($impurity < $bestImpurity) { $bestColumn = $column; $bestValue = $value; $bestGroups = $groups; $bestImpurity = $impurity; } if ($impurity < $this->tolerance) { break 1; } } return new Decision($bestColumn, $bestValue, $bestGroups, $bestImpurity); }
[ "protected", "function", "split", "(", "Labeled", "$", "dataset", ")", ":", "Decision", "{", "$", "bestImpurity", "=", "INF", ";", "$", "bestColumn", "=", "$", "bestValue", "=", "null", ";", "$", "bestGroups", "=", "[", "]", ";", "$", "max", "=", "$", "dataset", "->", "numRows", "(", ")", "-", "1", ";", "shuffle", "(", "$", "this", "->", "columns", ")", ";", "foreach", "(", "array_slice", "(", "$", "this", "->", "columns", ",", "0", ",", "$", "this", "->", "maxFeatures", ")", "as", "$", "column", ")", "{", "$", "sample", "=", "$", "dataset", "->", "row", "(", "rand", "(", "0", ",", "$", "max", ")", ")", ";", "$", "value", "=", "$", "sample", "[", "$", "column", "]", ";", "$", "groups", "=", "$", "dataset", "->", "partition", "(", "$", "column", ",", "$", "value", ")", ";", "$", "impurity", "=", "$", "this", "->", "splitImpurity", "(", "$", "groups", ")", ";", "if", "(", "$", "impurity", "<", "$", "bestImpurity", ")", "{", "$", "bestColumn", "=", "$", "column", ";", "$", "bestValue", "=", "$", "value", ";", "$", "bestGroups", "=", "$", "groups", ";", "$", "bestImpurity", "=", "$", "impurity", ";", "}", "if", "(", "$", "impurity", "<", "$", "this", "->", "tolerance", ")", "{", "break", "1", ";", "}", "}", "return", "new", "Decision", "(", "$", "bestColumn", ",", "$", "bestValue", ",", "$", "bestGroups", ",", "$", "bestImpurity", ")", ";", "}" ]
Randomized algorithm that chooses the split point with the lowest variance among a random assortment of features. @param \Rubix\ML\Datasets\Labeled $dataset @return \Rubix\ML\Graph\Nodes\Decision
[ "Randomized", "algorithm", "that", "chooses", "the", "split", "point", "with", "the", "lowest", "variance", "among", "a", "random", "assortment", "of", "features", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/ExtraTreeRegressor.php#L34-L66
RubixML/RubixML
src/GridSearch.php
GridSearch.combineGrid
public static function combineGrid(array $grid) : array { $combinations = [[]]; foreach ($grid as $i => $params) { $append = []; foreach ($combinations as $product) { foreach ($params as $param) { $product[$i] = $param; $append[] = $product; } } $combinations = $append; } return $combinations; }
php
public static function combineGrid(array $grid) : array { $combinations = [[]]; foreach ($grid as $i => $params) { $append = []; foreach ($combinations as $product) { foreach ($params as $param) { $product[$i] = $param; $append[] = $product; } } $combinations = $append; } return $combinations; }
[ "public", "static", "function", "combineGrid", "(", "array", "$", "grid", ")", ":", "array", "{", "$", "combinations", "=", "[", "[", "]", "]", ";", "foreach", "(", "$", "grid", "as", "$", "i", "=>", "$", "params", ")", "{", "$", "append", "=", "[", "]", ";", "foreach", "(", "$", "combinations", "as", "$", "product", ")", "{", "foreach", "(", "$", "params", "as", "$", "param", ")", "{", "$", "product", "[", "$", "i", "]", "=", "$", "param", ";", "$", "append", "[", "]", "=", "$", "product", ";", "}", "}", "$", "combinations", "=", "$", "append", ";", "}", "return", "$", "combinations", ";", "}" ]
Return an array of all possible combinations of parameters. i.e the Cartesian product of the supplied parameter grid. @param array $grid @return array
[ "Return", "an", "array", "of", "all", "possible", "combinations", "of", "parameters", ".", "i", ".", "e", "the", "Cartesian", "product", "of", "the", "supplied", "parameter", "grid", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/GridSearch.php#L113-L131
RubixML/RubixML
src/GridSearch.php
GridSearch.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([ 'base' => $this->base, 'metric' => $this->metric, 'validator' => $this->validator, 'workers' => $this->workers, ])); } $results = []; Loop::run(function () use (&$results, $dataset) { $pool = new DefaultPool($this->workers); $coroutines = []; foreach ($this->combinations as $params) { $estimator = new $this->base(...$params); $task = new CallableTask( [$this, 'score'], [$estimator, $dataset] ); $coroutines[] = call(function () use ($pool, $task, $params) { $score = yield $pool->enqueue($task); if ($this->logger) { $constructor = array_combine($this->args, $params) ?: []; $this->logger->info('Test complete: ' . Params::stringify([ Params::shortName($this->metric) => $score, ]) . ' Params: ' . Params::stringify($constructor)); } return [$score, $params]; }); } $results = yield all($coroutines); return yield $pool->shutdown(); }); $bestScore = -INF; $bestParams = []; foreach ($results as [$score, $params]) { if ($score > $bestScore) { $bestScore = $score; $bestParams = $params; } } $this->best = [ 'score' => $bestScore, 'params' => $bestParams, ]; if ($this->logger) { $constructor = array_combine($this->args, $bestParams) ?: []; $this->logger->info('Best params: ' . Params::stringify($constructor)); } $estimator = new $this->base(...$bestParams); $estimator->train($dataset); $this->estimator = $estimator; 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([ 'base' => $this->base, 'metric' => $this->metric, 'validator' => $this->validator, 'workers' => $this->workers, ])); } $results = []; Loop::run(function () use (&$results, $dataset) { $pool = new DefaultPool($this->workers); $coroutines = []; foreach ($this->combinations as $params) { $estimator = new $this->base(...$params); $task = new CallableTask( [$this, 'score'], [$estimator, $dataset] ); $coroutines[] = call(function () use ($pool, $task, $params) { $score = yield $pool->enqueue($task); if ($this->logger) { $constructor = array_combine($this->args, $params) ?: []; $this->logger->info('Test complete: ' . Params::stringify([ Params::shortName($this->metric) => $score, ]) . ' Params: ' . Params::stringify($constructor)); } return [$score, $params]; }); } $results = yield all($coroutines); return yield $pool->shutdown(); }); $bestScore = -INF; $bestParams = []; foreach ($results as [$score, $params]) { if ($score > $bestScore) { $bestScore = $score; $bestParams = $params; } } $this->best = [ 'score' => $bestScore, 'params' => $bestParams, ]; if ($this->logger) { $constructor = array_combine($this->args, $bestParams) ?: []; $this->logger->info('Best params: ' . Params::stringify($constructor)); } $estimator = new $this->base(...$bestParams); $estimator->train($dataset); $this->estimator = $estimator; 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", "(", "[", "'base'", "=>", "$", "this", "->", "base", ",", "'metric'", "=>", "$", "this", "->", "metric", ",", "'validator'", "=>", "$", "this", "->", "validator", ",", "'workers'", "=>", "$", "this", "->", "workers", ",", "]", ")", ")", ";", "}", "$", "results", "=", "[", "]", ";", "Loop", "::", "run", "(", "function", "(", ")", "use", "(", "&", "$", "results", ",", "$", "dataset", ")", "{", "$", "pool", "=", "new", "DefaultPool", "(", "$", "this", "->", "workers", ")", ";", "$", "coroutines", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "combinations", "as", "$", "params", ")", "{", "$", "estimator", "=", "new", "$", "this", "->", "base", "(", "...", "$", "params", ")", ";", "$", "task", "=", "new", "CallableTask", "(", "[", "$", "this", ",", "'score'", "]", ",", "[", "$", "estimator", ",", "$", "dataset", "]", ")", ";", "$", "coroutines", "[", "]", "=", "call", "(", "function", "(", ")", "use", "(", "$", "pool", ",", "$", "task", ",", "$", "params", ")", "{", "$", "score", "=", "yield", "$", "pool", "->", "enqueue", "(", "$", "task", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "constructor", "=", "array_combine", "(", "$", "this", "->", "args", ",", "$", "params", ")", "?", ":", "[", "]", ";", "$", "this", "->", "logger", "->", "info", "(", "'Test complete: '", ".", "Params", "::", "stringify", "(", "[", "Params", "::", "shortName", "(", "$", "this", "->", "metric", ")", "=>", "$", "score", ",", "]", ")", ".", "' Params: '", ".", "Params", "::", "stringify", "(", "$", "constructor", ")", ")", ";", "}", "return", "[", "$", "score", ",", "$", "params", "]", ";", "}", ")", ";", "}", "$", "results", "=", "yield", "all", "(", "$", "coroutines", ")", ";", "return", "yield", "$", "pool", "->", "shutdown", "(", ")", ";", "}", ")", ";", "$", "bestScore", "=", "-", "INF", ";", "$", "bestParams", "=", "[", "]", ";", "foreach", "(", "$", "results", "as", "[", "$", "score", ",", "$", "params", "]", ")", "{", "if", "(", "$", "score", ">", "$", "bestScore", ")", "{", "$", "bestScore", "=", "$", "score", ";", "$", "bestParams", "=", "$", "params", ";", "}", "}", "$", "this", "->", "best", "=", "[", "'score'", "=>", "$", "bestScore", ",", "'params'", "=>", "$", "bestParams", ",", "]", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "constructor", "=", "array_combine", "(", "$", "this", "->", "args", ",", "$", "bestParams", ")", "?", ":", "[", "]", ";", "$", "this", "->", "logger", "->", "info", "(", "'Best params: '", ".", "Params", "::", "stringify", "(", "$", "constructor", ")", ")", ";", "}", "$", "estimator", "=", "new", "$", "this", "->", "base", "(", "...", "$", "bestParams", ")", ";", "$", "estimator", "->", "train", "(", "$", "dataset", ")", ";", "$", "this", "->", "estimator", "=", "$", "estimator", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Training complete'", ")", ";", "}", "}" ]
Train one estimator per combination of parameters given by the grid and assign the best one as the base estimator of this instance. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException
[ "Train", "one", "estimator", "per", "combination", "of", "parameters", "given", "by", "the", "grid", "and", "assign", "the", "best", "one", "as", "the", "base", "estimator", "of", "this", "instance", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/GridSearch.php#L282-L365
RubixML/RubixML
src/GridSearch.php
GridSearch.score
public function score(Learner $estimator, Labeled $dataset) : float { return $this->validator->test($estimator, $dataset, $this->metric); }
php
public function score(Learner $estimator, Labeled $dataset) : float { return $this->validator->test($estimator, $dataset, $this->metric); }
[ "public", "function", "score", "(", "Learner", "$", "estimator", ",", "Labeled", "$", "dataset", ")", ":", "float", "{", "return", "$", "this", "->", "validator", "->", "test", "(", "$", "estimator", ",", "$", "dataset", ",", "$", "this", "->", "metric", ")", ";", "}" ]
Cross validate a learner with a given dataset and return the score. @param \Rubix\ML\Learner $estimator @param \Rubix\ML\Datasets\Labeled $dataset @return float
[ "Cross", "validate", "a", "learner", "with", "a", "given", "dataset", "and", "return", "the", "score", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/GridSearch.php#L386-L389
RubixML/RubixML
src/Transformers/ImageResizer.php
ImageResizer.transform
public function transform(array &$samples) : void { foreach ($samples as &$sample) { $vectors = []; foreach ($sample as $column => &$value) { if (is_resource($value) ? get_resource_type($value) === 'gd' : false) { $image = $this->intervention->make($value); $resize = $image->getWidth() !== $this->width and $image->getHeight() !== $this->height; if ($resize) { $image = $image->fit($this->width, $this->height); } $value = $image->getCore(); } } } }
php
public function transform(array &$samples) : void { foreach ($samples as &$sample) { $vectors = []; foreach ($sample as $column => &$value) { if (is_resource($value) ? get_resource_type($value) === 'gd' : false) { $image = $this->intervention->make($value); $resize = $image->getWidth() !== $this->width and $image->getHeight() !== $this->height; if ($resize) { $image = $image->fit($this->width, $this->height); } $value = $image->getCore(); } } } }
[ "public", "function", "transform", "(", "array", "&", "$", "samples", ")", ":", "void", "{", "foreach", "(", "$", "samples", "as", "&", "$", "sample", ")", "{", "$", "vectors", "=", "[", "]", ";", "foreach", "(", "$", "sample", "as", "$", "column", "=>", "&", "$", "value", ")", "{", "if", "(", "is_resource", "(", "$", "value", ")", "?", "get_resource_type", "(", "$", "value", ")", "===", "'gd'", ":", "false", ")", "{", "$", "image", "=", "$", "this", "->", "intervention", "->", "make", "(", "$", "value", ")", ";", "$", "resize", "=", "$", "image", "->", "getWidth", "(", ")", "!==", "$", "this", "->", "width", "and", "$", "image", "->", "getHeight", "(", ")", "!==", "$", "this", "->", "height", ";", "if", "(", "$", "resize", ")", "{", "$", "image", "=", "$", "image", "->", "fit", "(", "$", "this", "->", "width", ",", "$", "this", "->", "height", ")", ";", "}", "$", "value", "=", "$", "image", "->", "getCore", "(", ")", ";", "}", "}", "}", "}" ]
Transform the dataset in place. @param array $samples
[ "Transform", "the", "dataset", "in", "place", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/ImageResizer.php#L65-L85
RubixML/RubixML
src/Regressors/KNNRegressor.php
KNNRegressor.predict
public function predict(Dataset $dataset) : array { if (empty($this->samples) or empty($this->labels)) { throw new RuntimeException('Estimator has not been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $predictions = []; foreach ($dataset as $sample) { [$labels, $distances] = $this->nearest($sample); if ($this->weighted) { $weights = []; foreach ($distances as $i => $distance) { $weights[] = 1. / (1. + $distance); } $outcome = Stats::weightedMean($labels, $weights); } else { $outcome = Stats::mean($labels); } $predictions[] = $outcome; } return $predictions; }
php
public function predict(Dataset $dataset) : array { if (empty($this->samples) or empty($this->labels)) { throw new RuntimeException('Estimator has not been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $predictions = []; foreach ($dataset as $sample) { [$labels, $distances] = $this->nearest($sample); if ($this->weighted) { $weights = []; foreach ($distances as $i => $distance) { $weights[] = 1. / (1. + $distance); } $outcome = Stats::weightedMean($labels, $weights); } else { $outcome = Stats::mean($labels); } $predictions[] = $outcome; } return $predictions; }
[ "public", "function", "predict", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "if", "(", "empty", "(", "$", "this", "->", "samples", ")", "or", "empty", "(", "$", "this", "->", "labels", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'Estimator has not been trained.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "$", "predictions", "=", "[", "]", ";", "foreach", "(", "$", "dataset", "as", "$", "sample", ")", "{", "[", "$", "labels", ",", "$", "distances", "]", "=", "$", "this", "->", "nearest", "(", "$", "sample", ")", ";", "if", "(", "$", "this", "->", "weighted", ")", "{", "$", "weights", "=", "[", "]", ";", "foreach", "(", "$", "distances", "as", "$", "i", "=>", "$", "distance", ")", "{", "$", "weights", "[", "]", "=", "1.", "/", "(", "1.", "+", "$", "distance", ")", ";", "}", "$", "outcome", "=", "Stats", "::", "weightedMean", "(", "$", "labels", ",", "$", "weights", ")", ";", "}", "else", "{", "$", "outcome", "=", "Stats", "::", "mean", "(", "$", "labels", ")", ";", "}", "$", "predictions", "[", "]", "=", "$", "outcome", ";", "}", "return", "$", "predictions", ";", "}" ]
Make a prediction based on the nearest neighbors. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException @throws \RuntimeException @return array
[ "Make", "a", "prediction", "based", "on", "the", "nearest", "neighbors", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/KNNRegressor.php#L170-L199
RubixML/RubixML
src/CrossValidation/Reports/ResidualAnalysis.php
ResidualAnalysis.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.'); } $muHat = Stats::mean($labels); $errors = $l1 = $l2 = []; $sse = $sst = 0.; foreach ($predictions as $i => $prediction) { $label = $labels[$i]; $errors[] = $error = $label - $prediction; $l1[] = abs($error); $l2[] = $t = $error ** 2; $sse += $t; $sst += ($label - $muHat) ** 2; } [$mean, $variance] = Stats::meanVar($errors); $mse = Stats::mean($l2); $r2 = 1. - ($sse / ($sst ?: EPSILON)); return [ 'mean_absolute_error' => Stats::mean($l1), 'median_absolute_error' => Stats::median($l1), 'mean_squared_error' => $mse, 'rms_error' => sqrt($mse), 'mean_squared_log_error' => log($mse), 'r_squared' => $r2, 'error_mean' => $mean, 'error_variance' => $variance, 'error_skewness' => Stats::skewness($errors, $mean), 'error_kurtosis' => Stats::kurtosis($errors, $mean), 'error_min' => min($errors), 'error_max' => max($errors), 'cardinality' => count($predictions), ]; }
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.'); } $muHat = Stats::mean($labels); $errors = $l1 = $l2 = []; $sse = $sst = 0.; foreach ($predictions as $i => $prediction) { $label = $labels[$i]; $errors[] = $error = $label - $prediction; $l1[] = abs($error); $l2[] = $t = $error ** 2; $sse += $t; $sst += ($label - $muHat) ** 2; } [$mean, $variance] = Stats::meanVar($errors); $mse = Stats::mean($l2); $r2 = 1. - ($sse / ($sst ?: EPSILON)); return [ 'mean_absolute_error' => Stats::mean($l1), 'median_absolute_error' => Stats::median($l1), 'mean_squared_error' => $mse, 'rms_error' => sqrt($mse), 'mean_squared_log_error' => log($mse), 'r_squared' => $r2, 'error_mean' => $mean, 'error_variance' => $variance, 'error_skewness' => Stats::skewness($errors, $mean), 'error_kurtosis' => Stats::kurtosis($errors, $mean), 'error_min' => min($errors), 'error_max' => max($errors), 'cardinality' => count($predictions), ]; }
[ "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.'", ")", ";", "}", "$", "muHat", "=", "Stats", "::", "mean", "(", "$", "labels", ")", ";", "$", "errors", "=", "$", "l1", "=", "$", "l2", "=", "[", "]", ";", "$", "sse", "=", "$", "sst", "=", "0.", ";", "foreach", "(", "$", "predictions", "as", "$", "i", "=>", "$", "prediction", ")", "{", "$", "label", "=", "$", "labels", "[", "$", "i", "]", ";", "$", "errors", "[", "]", "=", "$", "error", "=", "$", "label", "-", "$", "prediction", ";", "$", "l1", "[", "]", "=", "abs", "(", "$", "error", ")", ";", "$", "l2", "[", "]", "=", "$", "t", "=", "$", "error", "**", "2", ";", "$", "sse", "+=", "$", "t", ";", "$", "sst", "+=", "(", "$", "label", "-", "$", "muHat", ")", "**", "2", ";", "}", "[", "$", "mean", ",", "$", "variance", "]", "=", "Stats", "::", "meanVar", "(", "$", "errors", ")", ";", "$", "mse", "=", "Stats", "::", "mean", "(", "$", "l2", ")", ";", "$", "r2", "=", "1.", "-", "(", "$", "sse", "/", "(", "$", "sst", "?", ":", "EPSILON", ")", ")", ";", "return", "[", "'mean_absolute_error'", "=>", "Stats", "::", "mean", "(", "$", "l1", ")", ",", "'median_absolute_error'", "=>", "Stats", "::", "median", "(", "$", "l1", ")", ",", "'mean_squared_error'", "=>", "$", "mse", ",", "'rms_error'", "=>", "sqrt", "(", "$", "mse", ")", ",", "'mean_squared_log_error'", "=>", "log", "(", "$", "mse", ")", ",", "'r_squared'", "=>", "$", "r2", ",", "'error_mean'", "=>", "$", "mean", ",", "'error_variance'", "=>", "$", "variance", ",", "'error_skewness'", "=>", "Stats", "::", "skewness", "(", "$", "errors", ",", "$", "mean", ")", ",", "'error_kurtosis'", "=>", "Stats", "::", "kurtosis", "(", "$", "errors", ",", "$", "mean", ")", ",", "'error_min'", "=>", "min", "(", "$", "errors", ")", ",", "'error_max'", "=>", "max", "(", "$", "errors", ")", ",", "'cardinality'", "=>", "count", "(", "$", "predictions", ")", ",", "]", ";", "}" ]
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/ResidualAnalysis.php#L43-L89
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.fromIterator
public static function fromIterator(iterable $samples, iterable $labels) : self { $samples = is_array($samples) ? $samples : iterator_to_array($samples, false); $labels = is_array($labels) ? $labels : iterator_to_array($labels, false); return self::build($samples, $labels); }
php
public static function fromIterator(iterable $samples, iterable $labels) : self { $samples = is_array($samples) ? $samples : iterator_to_array($samples, false); $labels = is_array($labels) ? $labels : iterator_to_array($labels, false); return self::build($samples, $labels); }
[ "public", "static", "function", "fromIterator", "(", "iterable", "$", "samples", ",", "iterable", "$", "labels", ")", ":", "self", "{", "$", "samples", "=", "is_array", "(", "$", "samples", ")", "?", "$", "samples", ":", "iterator_to_array", "(", "$", "samples", ",", "false", ")", ";", "$", "labels", "=", "is_array", "(", "$", "labels", ")", "?", "$", "labels", ":", "iterator_to_array", "(", "$", "labels", ",", "false", ")", ";", "return", "self", "::", "build", "(", "$", "samples", ",", "$", "labels", ")", ";", "}" ]
Build a dataset from an iterator. @param iterable $samples @param iterable $labels @return self
[ "Build", "a", "dataset", "from", "an", "iterator", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L67-L78
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.stack
public static function stack(array $datasets) : self { $samples = $labels = []; foreach ($datasets as $dataset) { if (!$dataset instanceof self) { throw new InvalidArgumentException('Dataset must be' . ' an instance of Labeled, ' . get_class($dataset) . ' given.'); } $samples = array_merge($samples, $dataset->samples()); $labels = array_merge($labels, $dataset->labels()); } return self::quick($samples, $labels); }
php
public static function stack(array $datasets) : self { $samples = $labels = []; foreach ($datasets as $dataset) { if (!$dataset instanceof self) { throw new InvalidArgumentException('Dataset must be' . ' an instance of Labeled, ' . get_class($dataset) . ' given.'); } $samples = array_merge($samples, $dataset->samples()); $labels = array_merge($labels, $dataset->labels()); } return self::quick($samples, $labels); }
[ "public", "static", "function", "stack", "(", "array", "$", "datasets", ")", ":", "self", "{", "$", "samples", "=", "$", "labels", "=", "[", "]", ";", "foreach", "(", "$", "datasets", "as", "$", "dataset", ")", "{", "if", "(", "!", "$", "dataset", "instanceof", "self", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Dataset must be'", ".", "' an instance of Labeled, '", ".", "get_class", "(", "$", "dataset", ")", ".", "' given.'", ")", ";", "}", "$", "samples", "=", "array_merge", "(", "$", "samples", ",", "$", "dataset", "->", "samples", "(", ")", ")", ";", "$", "labels", "=", "array_merge", "(", "$", "labels", ",", "$", "dataset", "->", "labels", "(", ")", ")", ";", "}", "return", "self", "::", "quick", "(", "$", "samples", ",", "$", "labels", ")", ";", "}" ]
Stack a number of datasets on top of each other to form a single dataset. @param array $datasets @throws \InvalidArgumentException @return self
[ "Stack", "a", "number", "of", "datasets", "on", "top", "of", "each", "other", "to", "form", "a", "single", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L88-L104
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.zip
public function zip() : array { $rows = $this->samples; foreach ($rows as $i => &$row) { $row[] = $this->labels[$i]; } return $rows; }
php
public function zip() : array { $rows = $this->samples; foreach ($rows as $i => &$row) { $row[] = $this->labels[$i]; } return $rows; }
[ "public", "function", "zip", "(", ")", ":", "array", "{", "$", "rows", "=", "$", "this", "->", "samples", ";", "foreach", "(", "$", "rows", "as", "$", "i", "=>", "&", "$", "row", ")", "{", "$", "row", "[", "]", "=", "$", "this", "->", "labels", "[", "$", "i", "]", ";", "}", "return", "$", "rows", ";", "}" ]
Return the samples and labels in a single array. @return array[]
[ "Return", "the", "samples", "and", "labels", "in", "a", "single", "array", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L151-L160
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.label
public function label(int $index) { if (!isset($this->labels[$index])) { throw new InvalidArgumentException("Row at offset $index" . ' does not exist.'); } return $this->labels[$index]; }
php
public function label(int $index) { if (!isset($this->labels[$index])) { throw new InvalidArgumentException("Row at offset $index" . ' does not exist.'); } return $this->labels[$index]; }
[ "public", "function", "label", "(", "int", "$", "index", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "labels", "[", "$", "index", "]", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Row at offset $index\"", ".", "' does not exist.'", ")", ";", "}", "return", "$", "this", "->", "labels", "[", "$", "index", "]", ";", "}" ]
Return a label given by row index. @param int $index @throws \InvalidArgumentException @return int|float|string
[ "Return", "a", "label", "given", "by", "row", "index", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L169-L177
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.labelType
public function labelType() : ?int { if (!isset($this->labels[0])) { return null; } return DataType::determine($this->labels[0]); }
php
public function labelType() : ?int { if (!isset($this->labels[0])) { return null; } return DataType::determine($this->labels[0]); }
[ "public", "function", "labelType", "(", ")", ":", "?", "int", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "labels", "[", "0", "]", ")", ")", "{", "return", "null", ";", "}", "return", "DataType", "::", "determine", "(", "$", "this", "->", "labels", "[", "0", "]", ")", ";", "}" ]
Return the integer encoded data type of the label or null if empty. @return int|null
[ "Return", "the", "integer", "encoded", "data", "type", "of", "the", "label", "or", "null", "if", "empty", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L184-L191
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.transformLabels
public function transformLabels(callable $fn) : void { $labels = array_map($fn, $this->labels); foreach ($labels as $label) { if (!is_string($label) and !is_numeric($label)) { throw new RuntimeException('Label must be a string or' . ' numeric type, ' . gettype($label) . ' found.'); } } $this->labels = $labels; }
php
public function transformLabels(callable $fn) : void { $labels = array_map($fn, $this->labels); foreach ($labels as $label) { if (!is_string($label) and !is_numeric($label)) { throw new RuntimeException('Label must be a string or' . ' numeric type, ' . gettype($label) . ' found.'); } } $this->labels = $labels; }
[ "public", "function", "transformLabels", "(", "callable", "$", "fn", ")", ":", "void", "{", "$", "labels", "=", "array_map", "(", "$", "fn", ",", "$", "this", "->", "labels", ")", ";", "foreach", "(", "$", "labels", "as", "$", "label", ")", "{", "if", "(", "!", "is_string", "(", "$", "label", ")", "and", "!", "is_numeric", "(", "$", "label", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'Label must be a string or'", ".", "' numeric type, '", ".", "gettype", "(", "$", "label", ")", ".", "' found.'", ")", ";", "}", "}", "$", "this", "->", "labels", "=", "$", "labels", ";", "}" ]
Map labels to their new values. @param callable $fn @throws \RuntimeException
[ "Map", "labels", "to", "their", "new", "values", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L199-L211
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.head
public function head(int $n = 10) : self { $samples = array_slice($this->samples, 0, $n); $labels = array_slice($this->labels, 0, $n); return self::quick($samples, $labels); }
php
public function head(int $n = 10) : self { $samples = array_slice($this->samples, 0, $n); $labels = array_slice($this->labels, 0, $n); return self::quick($samples, $labels); }
[ "public", "function", "head", "(", "int", "$", "n", "=", "10", ")", ":", "self", "{", "$", "samples", "=", "array_slice", "(", "$", "this", "->", "samples", ",", "0", ",", "$", "n", ")", ";", "$", "labels", "=", "array_slice", "(", "$", "this", "->", "labels", ",", "0", ",", "$", "n", ")", ";", "return", "self", "::", "quick", "(", "$", "samples", ",", "$", "labels", ")", ";", "}" ]
Return a dataset containing only the first n samples. @param int $n @return self
[ "Return", "a", "dataset", "containing", "only", "the", "first", "n", "samples", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L229-L235
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.leave
public function leave(int $n = 1) : self { if ($n < 0) { throw new InvalidArgumentException('Cannot leave less than 0 samples.'); } return $this->splice($n, $this->numRows()); }
php
public function leave(int $n = 1) : self { if ($n < 0) { throw new InvalidArgumentException('Cannot leave less than 0 samples.'); } return $this->splice($n, $this->numRows()); }
[ "public", "function", "leave", "(", "int", "$", "n", "=", "1", ")", ":", "self", "{", "if", "(", "$", "n", "<", "0", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Cannot leave less than 0 samples.'", ")", ";", "}", "return", "$", "this", "->", "splice", "(", "$", "n", ",", "$", "this", "->", "numRows", "(", ")", ")", ";", "}" ]
Leave n samples and labels on this dataset and return the rest in a new dataset. @param int $n @throws \InvalidArgumentException @return self
[ "Leave", "n", "samples", "and", "labels", "on", "this", "dataset", "and", "return", "the", "rest", "in", "a", "new", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L276-L283
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.prepend
public function prepend(Dataset $dataset) : self { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('Can only merge with a labeled' . 'dataset.'); } $samples = array_merge($dataset->samples(), $this->samples); $labels = array_merge($dataset->labels(), $this->labels); return self::quick($samples, $labels); }
php
public function prepend(Dataset $dataset) : self { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('Can only merge with a labeled' . 'dataset.'); } $samples = array_merge($dataset->samples(), $this->samples); $labels = array_merge($dataset->labels(), $this->labels); return self::quick($samples, $labels); }
[ "public", "function", "prepend", "(", "Dataset", "$", "dataset", ")", ":", "self", "{", "if", "(", "!", "$", "dataset", "instanceof", "Labeled", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Can only merge with a labeled'", ".", "'dataset.'", ")", ";", "}", "$", "samples", "=", "array_merge", "(", "$", "dataset", "->", "samples", "(", ")", ",", "$", "this", "->", "samples", ")", ";", "$", "labels", "=", "array_merge", "(", "$", "dataset", "->", "labels", "(", ")", ",", "$", "this", "->", "labels", ")", ";", "return", "self", "::", "quick", "(", "$", "samples", ",", "$", "labels", ")", ";", "}" ]
Prepend this dataset with another dataset. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException @return self
[ "Prepend", "this", "dataset", "with", "another", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L292-L303
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.splice
public function splice(int $offset, int $n) : self { $samples = array_splice($this->samples, $offset, $n); $labels = array_splice($this->labels, $offset, $n); return self::quick($samples, $labels); }
php
public function splice(int $offset, int $n) : self { $samples = array_splice($this->samples, $offset, $n); $labels = array_splice($this->labels, $offset, $n); return self::quick($samples, $labels); }
[ "public", "function", "splice", "(", "int", "$", "offset", ",", "int", "$", "n", ")", ":", "self", "{", "$", "samples", "=", "array_splice", "(", "$", "this", "->", "samples", ",", "$", "offset", ",", "$", "n", ")", ";", "$", "labels", "=", "array_splice", "(", "$", "this", "->", "labels", ",", "$", "offset", ",", "$", "n", ")", ";", "return", "self", "::", "quick", "(", "$", "samples", ",", "$", "labels", ")", ";", "}" ]
Remove a size n chunk of the dataset starting at offset and return it in a new dataset. @param int $offset @param int $n @return self
[ "Remove", "a", "size", "n", "chunk", "of", "the", "dataset", "starting", "at", "offset", "and", "return", "it", "in", "a", "new", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L333-L339
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.randomize
public function randomize() : self { $order = range(0, $this->numRows() - 1); shuffle($order); array_multisort($order, $this->samples, $this->labels); return $this; }
php
public function randomize() : self { $order = range(0, $this->numRows() - 1); shuffle($order); array_multisort($order, $this->samples, $this->labels); return $this; }
[ "public", "function", "randomize", "(", ")", ":", "self", "{", "$", "order", "=", "range", "(", "0", ",", "$", "this", "->", "numRows", "(", ")", "-", "1", ")", ";", "shuffle", "(", "$", "order", ")", ";", "array_multisort", "(", "$", "order", ",", "$", "this", "->", "samples", ",", "$", "this", "->", "labels", ")", ";", "return", "$", "this", ";", "}" ]
Randomize the dataset in place and return self for chaining. @return self
[ "Randomize", "the", "dataset", "in", "place", "and", "return", "self", "for", "chaining", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L346-L355
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.filterByColumn
public function filterByColumn(int $index, callable $fn) : self { $samples = $labels = []; foreach ($this->samples as $i => $sample) { if ($fn($sample[$index])) { $samples[] = $sample; $labels[] = $this->labels[$i]; } } return self::quick($samples, $labels); }
php
public function filterByColumn(int $index, callable $fn) : self { $samples = $labels = []; foreach ($this->samples as $i => $sample) { if ($fn($sample[$index])) { $samples[] = $sample; $labels[] = $this->labels[$i]; } } return self::quick($samples, $labels); }
[ "public", "function", "filterByColumn", "(", "int", "$", "index", ",", "callable", "$", "fn", ")", ":", "self", "{", "$", "samples", "=", "$", "labels", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "samples", "as", "$", "i", "=>", "$", "sample", ")", "{", "if", "(", "$", "fn", "(", "$", "sample", "[", "$", "index", "]", ")", ")", "{", "$", "samples", "[", "]", "=", "$", "sample", ";", "$", "labels", "[", "]", "=", "$", "this", "->", "labels", "[", "$", "i", "]", ";", "}", "}", "return", "self", "::", "quick", "(", "$", "samples", ",", "$", "labels", ")", ";", "}" ]
Run a filter over the dataset using the values of a given column. @param int $index @param callable $fn @return self
[ "Run", "a", "filter", "over", "the", "dataset", "using", "the", "values", "of", "a", "given", "column", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L364-L376
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.filterByLabel
public function filterByLabel(callable $fn) : self { $samples = $labels = []; foreach ($this->labels as $i => $label) { if ($fn($label)) { $samples[] = $this->samples[$i]; $labels[] = $label; } } return self::quick($samples, $labels); }
php
public function filterByLabel(callable $fn) : self { $samples = $labels = []; foreach ($this->labels as $i => $label) { if ($fn($label)) { $samples[] = $this->samples[$i]; $labels[] = $label; } } return self::quick($samples, $labels); }
[ "public", "function", "filterByLabel", "(", "callable", "$", "fn", ")", ":", "self", "{", "$", "samples", "=", "$", "labels", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "labels", "as", "$", "i", "=>", "$", "label", ")", "{", "if", "(", "$", "fn", "(", "$", "label", ")", ")", "{", "$", "samples", "[", "]", "=", "$", "this", "->", "samples", "[", "$", "i", "]", ";", "$", "labels", "[", "]", "=", "$", "label", ";", "}", "}", "return", "self", "::", "quick", "(", "$", "samples", ",", "$", "labels", ")", ";", "}" ]
Run a filter over the dataset using the labels for Decision. @param callable $fn @return self
[ "Run", "a", "filter", "over", "the", "dataset", "using", "the", "labels", "for", "Decision", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L384-L396
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.sortByColumn
public function sortByColumn(int $index, bool $descending = false) { $order = $this->column($index); array_multisort( $order, $this->samples, $this->labels, $descending ? SORT_DESC : SORT_ASC ); return $this; }
php
public function sortByColumn(int $index, bool $descending = false) { $order = $this->column($index); array_multisort( $order, $this->samples, $this->labels, $descending ? SORT_DESC : SORT_ASC ); return $this; }
[ "public", "function", "sortByColumn", "(", "int", "$", "index", ",", "bool", "$", "descending", "=", "false", ")", "{", "$", "order", "=", "$", "this", "->", "column", "(", "$", "index", ")", ";", "array_multisort", "(", "$", "order", ",", "$", "this", "->", "samples", ",", "$", "this", "->", "labels", ",", "$", "descending", "?", "SORT_DESC", ":", "SORT_ASC", ")", ";", "return", "$", "this", ";", "}" ]
Sort the dataset in place by a column in the sample matrix. @param int $index @param bool $descending @return self
[ "Sort", "the", "dataset", "in", "place", "by", "a", "column", "in", "the", "sample", "matrix", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L405-L417
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.sortByLabel
public function sortByLabel(bool $descending = false) : Dataset { array_multisort( $this->labels, $this->samples, $descending ? SORT_DESC : SORT_ASC ); return $this; }
php
public function sortByLabel(bool $descending = false) : Dataset { array_multisort( $this->labels, $this->samples, $descending ? SORT_DESC : SORT_ASC ); return $this; }
[ "public", "function", "sortByLabel", "(", "bool", "$", "descending", "=", "false", ")", ":", "Dataset", "{", "array_multisort", "(", "$", "this", "->", "labels", ",", "$", "this", "->", "samples", ",", "$", "descending", "?", "SORT_DESC", ":", "SORT_ASC", ")", ";", "return", "$", "this", ";", "}" ]
Sort the dataset in place by its labels. @param bool $descending @return \Rubix\ML\Datasets\Dataset
[ "Sort", "the", "dataset", "in", "place", "by", "its", "labels", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L425-L434
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.stratify
public function stratify() : array { $strata = []; foreach ($this->_stratify() as $label => $stratum) { $labels = array_fill(0, count($stratum), $label); $strata[$label] = self::quick($stratum, $labels); } return $strata; }
php
public function stratify() : array { $strata = []; foreach ($this->_stratify() as $label => $stratum) { $labels = array_fill(0, count($stratum), $label); $strata[$label] = self::quick($stratum, $labels); } return $strata; }
[ "public", "function", "stratify", "(", ")", ":", "array", "{", "$", "strata", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "_stratify", "(", ")", "as", "$", "label", "=>", "$", "stratum", ")", "{", "$", "labels", "=", "array_fill", "(", "0", ",", "count", "(", "$", "stratum", ")", ",", "$", "label", ")", ";", "$", "strata", "[", "$", "label", "]", "=", "self", "::", "quick", "(", "$", "stratum", ",", "$", "labels", ")", ";", "}", "return", "$", "strata", ";", "}" ]
Group samples by label and return an array of stratified datasets. i.e. n datasets consisting of samples with the same label where n is equal to the number of unique labels. @return self[]
[ "Group", "samples", "by", "label", "and", "return", "an", "array", "of", "stratified", "datasets", ".", "i", ".", "e", ".", "n", "datasets", "consisting", "of", "samples", "with", "the", "same", "label", "where", "n", "is", "equal", "to", "the", "number", "of", "unique", "labels", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L443-L454
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.split
public function split(float $ratio = 0.5) : array { if ($ratio <= 0 or $ratio >= 1) { throw new InvalidArgumentException('Split ratio must be strictly' . " between 0 and 1, $ratio given."); } $n = (int) ($ratio * $this->numRows()); $leftSamples = array_slice($this->samples, 0, $n); $leftLabels = array_slice($this->labels, 0, $n); $rightSamples = array_slice($this->samples, $n); $rightLabels = array_slice($this->labels, $n); return [ self::quick($leftSamples, $leftLabels), self::quick($rightSamples, $rightLabels), ]; }
php
public function split(float $ratio = 0.5) : array { if ($ratio <= 0 or $ratio >= 1) { throw new InvalidArgumentException('Split ratio must be strictly' . " between 0 and 1, $ratio given."); } $n = (int) ($ratio * $this->numRows()); $leftSamples = array_slice($this->samples, 0, $n); $leftLabels = array_slice($this->labels, 0, $n); $rightSamples = array_slice($this->samples, $n); $rightLabels = array_slice($this->labels, $n); return [ self::quick($leftSamples, $leftLabels), self::quick($rightSamples, $rightLabels), ]; }
[ "public", "function", "split", "(", "float", "$", "ratio", "=", "0.5", ")", ":", "array", "{", "if", "(", "$", "ratio", "<=", "0", "or", "$", "ratio", ">=", "1", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Split ratio must be strictly'", ".", "\" between 0 and 1, $ratio given.\"", ")", ";", "}", "$", "n", "=", "(", "int", ")", "(", "$", "ratio", "*", "$", "this", "->", "numRows", "(", ")", ")", ";", "$", "leftSamples", "=", "array_slice", "(", "$", "this", "->", "samples", ",", "0", ",", "$", "n", ")", ";", "$", "leftLabels", "=", "array_slice", "(", "$", "this", "->", "labels", ",", "0", ",", "$", "n", ")", ";", "$", "rightSamples", "=", "array_slice", "(", "$", "this", "->", "samples", ",", "$", "n", ")", ";", "$", "rightLabels", "=", "array_slice", "(", "$", "this", "->", "labels", ",", "$", "n", ")", ";", "return", "[", "self", "::", "quick", "(", "$", "leftSamples", ",", "$", "leftLabels", ")", ",", "self", "::", "quick", "(", "$", "rightSamples", ",", "$", "rightLabels", ")", ",", "]", ";", "}" ]
Split the dataset into two subsets with a given ratio of samples. @param float $ratio @throws \InvalidArgumentException @return self[]
[ "Split", "the", "dataset", "into", "two", "subsets", "with", "a", "given", "ratio", "of", "samples", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L463-L482
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.stratifiedSplit
public function stratifiedSplit(float $ratio = 0.5) : array { if ($ratio <= 0. or $ratio >= 1.) { throw new InvalidArgumentException('Split ratio must be' . " strictly between 0 and 1, $ratio given."); } $leftSamples = $leftLabels = $rightSamples = $rightLabels = []; foreach ($this->_stratify() as $label => $stratum) { $n = (int) floor($ratio * count($stratum)); $leftSamples = array_merge($leftSamples, array_splice($stratum, 0, $n)); $leftLabels = array_merge($leftLabels, array_fill(0, $n, $label)); $rightSamples = array_merge($rightSamples, $stratum); $rightLabels = array_merge($rightLabels, array_fill(0, count($stratum), $label)); } return [ self::quick($leftSamples, $leftLabels), self::quick($rightSamples, $rightLabels), ]; }
php
public function stratifiedSplit(float $ratio = 0.5) : array { if ($ratio <= 0. or $ratio >= 1.) { throw new InvalidArgumentException('Split ratio must be' . " strictly between 0 and 1, $ratio given."); } $leftSamples = $leftLabels = $rightSamples = $rightLabels = []; foreach ($this->_stratify() as $label => $stratum) { $n = (int) floor($ratio * count($stratum)); $leftSamples = array_merge($leftSamples, array_splice($stratum, 0, $n)); $leftLabels = array_merge($leftLabels, array_fill(0, $n, $label)); $rightSamples = array_merge($rightSamples, $stratum); $rightLabels = array_merge($rightLabels, array_fill(0, count($stratum), $label)); } return [ self::quick($leftSamples, $leftLabels), self::quick($rightSamples, $rightLabels), ]; }
[ "public", "function", "stratifiedSplit", "(", "float", "$", "ratio", "=", "0.5", ")", ":", "array", "{", "if", "(", "$", "ratio", "<=", "0.", "or", "$", "ratio", ">=", "1.", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Split ratio must be'", ".", "\" strictly between 0 and 1, $ratio given.\"", ")", ";", "}", "$", "leftSamples", "=", "$", "leftLabels", "=", "$", "rightSamples", "=", "$", "rightLabels", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "_stratify", "(", ")", "as", "$", "label", "=>", "$", "stratum", ")", "{", "$", "n", "=", "(", "int", ")", "floor", "(", "$", "ratio", "*", "count", "(", "$", "stratum", ")", ")", ";", "$", "leftSamples", "=", "array_merge", "(", "$", "leftSamples", ",", "array_splice", "(", "$", "stratum", ",", "0", ",", "$", "n", ")", ")", ";", "$", "leftLabels", "=", "array_merge", "(", "$", "leftLabels", ",", "array_fill", "(", "0", ",", "$", "n", ",", "$", "label", ")", ")", ";", "$", "rightSamples", "=", "array_merge", "(", "$", "rightSamples", ",", "$", "stratum", ")", ";", "$", "rightLabels", "=", "array_merge", "(", "$", "rightLabels", ",", "array_fill", "(", "0", ",", "count", "(", "$", "stratum", ")", ",", "$", "label", ")", ")", ";", "}", "return", "[", "self", "::", "quick", "(", "$", "leftSamples", ",", "$", "leftLabels", ")", ",", "self", "::", "quick", "(", "$", "rightSamples", ",", "$", "rightLabels", ")", ",", "]", ";", "}" ]
Split the dataset into two stratified subsets with a given ratio of samples. @param float $ratio @throws \InvalidArgumentException @return self[]
[ "Split", "the", "dataset", "into", "two", "stratified", "subsets", "with", "a", "given", "ratio", "of", "samples", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L491-L514
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.fold
public function fold(int $k = 10) : array { if ($k < 2) { throw new InvalidArgumentException('Cannot create less than' . " 2 folds, $k given."); } $n = (int) floor($this->numRows() / $k); $folds = []; for ($i = 0; $i < $k; $i++) { $offset = $i * $n; $samples = array_slice($this->samples, $offset, $n); $labels = array_slice($this->labels, $offset, $n); $folds[] = self::quick($samples, $labels); } return $folds; }
php
public function fold(int $k = 10) : array { if ($k < 2) { throw new InvalidArgumentException('Cannot create less than' . " 2 folds, $k given."); } $n = (int) floor($this->numRows() / $k); $folds = []; for ($i = 0; $i < $k; $i++) { $offset = $i * $n; $samples = array_slice($this->samples, $offset, $n); $labels = array_slice($this->labels, $offset, $n); $folds[] = self::quick($samples, $labels); } return $folds; }
[ "public", "function", "fold", "(", "int", "$", "k", "=", "10", ")", ":", "array", "{", "if", "(", "$", "k", "<", "2", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Cannot create less than'", ".", "\" 2 folds, $k given.\"", ")", ";", "}", "$", "n", "=", "(", "int", ")", "floor", "(", "$", "this", "->", "numRows", "(", ")", "/", "$", "k", ")", ";", "$", "folds", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "k", ";", "$", "i", "++", ")", "{", "$", "offset", "=", "$", "i", "*", "$", "n", ";", "$", "samples", "=", "array_slice", "(", "$", "this", "->", "samples", ",", "$", "offset", ",", "$", "n", ")", ";", "$", "labels", "=", "array_slice", "(", "$", "this", "->", "labels", ",", "$", "offset", ",", "$", "n", ")", ";", "$", "folds", "[", "]", "=", "self", "::", "quick", "(", "$", "samples", ",", "$", "labels", ")", ";", "}", "return", "$", "folds", ";", "}" ]
Fold the dataset k - 1 times to form k equal size datasets. @param int $k @throws \InvalidArgumentException @return array
[ "Fold", "the", "dataset", "k", "-", "1", "times", "to", "form", "k", "equal", "size", "datasets", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L523-L544
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.stratifiedFold
public function stratifiedFold(int $k = 10) : array { if ($k < 2) { throw new InvalidArgumentException('Cannot create less than' . " 2 folds, $k given."); } $folds = []; for ($i = 0; $i < $k; $i++) { $samples = $labels = []; foreach ($this->_stratify() as $label => $stratum) { $n = (int) floor(count($stratum) / $k); $samples = array_merge($samples, array_slice($stratum, $i * $n, $n)); $labels = array_merge($labels, array_fill(0, $n, $label)); } $folds[] = self::quick($samples, $labels); } return $folds; }
php
public function stratifiedFold(int $k = 10) : array { if ($k < 2) { throw new InvalidArgumentException('Cannot create less than' . " 2 folds, $k given."); } $folds = []; for ($i = 0; $i < $k; $i++) { $samples = $labels = []; foreach ($this->_stratify() as $label => $stratum) { $n = (int) floor(count($stratum) / $k); $samples = array_merge($samples, array_slice($stratum, $i * $n, $n)); $labels = array_merge($labels, array_fill(0, $n, $label)); } $folds[] = self::quick($samples, $labels); } return $folds; }
[ "public", "function", "stratifiedFold", "(", "int", "$", "k", "=", "10", ")", ":", "array", "{", "if", "(", "$", "k", "<", "2", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Cannot create less than'", ".", "\" 2 folds, $k given.\"", ")", ";", "}", "$", "folds", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "k", ";", "$", "i", "++", ")", "{", "$", "samples", "=", "$", "labels", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "_stratify", "(", ")", "as", "$", "label", "=>", "$", "stratum", ")", "{", "$", "n", "=", "(", "int", ")", "floor", "(", "count", "(", "$", "stratum", ")", "/", "$", "k", ")", ";", "$", "samples", "=", "array_merge", "(", "$", "samples", ",", "array_slice", "(", "$", "stratum", ",", "$", "i", "*", "$", "n", ",", "$", "n", ")", ")", ";", "$", "labels", "=", "array_merge", "(", "$", "labels", ",", "array_fill", "(", "0", ",", "$", "n", ",", "$", "label", ")", ")", ";", "}", "$", "folds", "[", "]", "=", "self", "::", "quick", "(", "$", "samples", ",", "$", "labels", ")", ";", "}", "return", "$", "folds", ";", "}" ]
Fold the dataset into k equal sized stratified datasets. @param int $k @throws \InvalidArgumentException @return array
[ "Fold", "the", "dataset", "into", "k", "equal", "sized", "stratified", "datasets", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L553-L576
RubixML/RubixML
src/Datasets/Labeled.php
Labeled._stratify
protected function _stratify() : array { $strata = []; foreach ($this->labels as $index => $label) { $strata[$label][] = $this->samples[$index]; } return $strata; }
php
protected function _stratify() : array { $strata = []; foreach ($this->labels as $index => $label) { $strata[$label][] = $this->samples[$index]; } return $strata; }
[ "protected", "function", "_stratify", "(", ")", ":", "array", "{", "$", "strata", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "labels", "as", "$", "index", "=>", "$", "label", ")", "{", "$", "strata", "[", "$", "label", "]", "[", "]", "=", "$", "this", "->", "samples", "[", "$", "index", "]", ";", "}", "return", "$", "strata", ";", "}" ]
Stratifying subroutine groups samples by label. @throws \RuntimeException @return array[]
[ "Stratifying", "subroutine", "groups", "samples", "by", "label", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L584-L593
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.batch
public function batch(int $n = 50) : array { $sChunks = array_chunk($this->samples, $n); $lChunks = array_chunk($this->labels, $n); $batches = []; foreach ($sChunks as $i => $samples) { $batches[] = self::quick($samples, $lChunks[$i]); } return $batches; }
php
public function batch(int $n = 50) : array { $sChunks = array_chunk($this->samples, $n); $lChunks = array_chunk($this->labels, $n); $batches = []; foreach ($sChunks as $i => $samples) { $batches[] = self::quick($samples, $lChunks[$i]); } return $batches; }
[ "public", "function", "batch", "(", "int", "$", "n", "=", "50", ")", ":", "array", "{", "$", "sChunks", "=", "array_chunk", "(", "$", "this", "->", "samples", ",", "$", "n", ")", ";", "$", "lChunks", "=", "array_chunk", "(", "$", "this", "->", "labels", ",", "$", "n", ")", ";", "$", "batches", "=", "[", "]", ";", "foreach", "(", "$", "sChunks", "as", "$", "i", "=>", "$", "samples", ")", "{", "$", "batches", "[", "]", "=", "self", "::", "quick", "(", "$", "samples", ",", "$", "lChunks", "[", "$", "i", "]", ")", ";", "}", "return", "$", "batches", ";", "}" ]
Generate a collection of batches of size n from the dataset. If there are not enough samples to fill an entire batch, then the dataset will contain as many samples and labels as possible. @param int $n @return array
[ "Generate", "a", "collection", "of", "batches", "of", "size", "n", "from", "the", "dataset", ".", "If", "there", "are", "not", "enough", "samples", "to", "fill", "an", "entire", "batch", "then", "the", "dataset", "will", "contain", "as", "many", "samples", "and", "labels", "as", "possible", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L603-L615
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.partition
public function partition(int $column, $value) : array { if (!is_string($value) and !is_numeric($value)) { throw new InvalidArgumentException('Value must be a string or' . ' numeric type, ' . gettype($value) . ' given.'); } $leftSamples = $leftLabels = $rightSamples = $rightLabels = []; if ($this->columnType($column) === DataType::CATEGORICAL) { foreach ($this->samples as $i => $sample) { if ($sample[$column] === $value) { $leftSamples[] = $sample; $leftLabels[] = $this->labels[$i]; } else { $rightSamples[] = $sample; $rightLabels[] = $this->labels[$i]; } } } else { foreach ($this->samples as $i => $sample) { if ($sample[$column] < $value) { $leftSamples[] = $sample; $leftLabels[] = $this->labels[$i]; } else { $rightSamples[] = $sample; $rightLabels[] = $this->labels[$i]; } } } return [ self::quick($leftSamples, $leftLabels), self::quick($rightSamples, $rightLabels), ]; }
php
public function partition(int $column, $value) : array { if (!is_string($value) and !is_numeric($value)) { throw new InvalidArgumentException('Value must be a string or' . ' numeric type, ' . gettype($value) . ' given.'); } $leftSamples = $leftLabels = $rightSamples = $rightLabels = []; if ($this->columnType($column) === DataType::CATEGORICAL) { foreach ($this->samples as $i => $sample) { if ($sample[$column] === $value) { $leftSamples[] = $sample; $leftLabels[] = $this->labels[$i]; } else { $rightSamples[] = $sample; $rightLabels[] = $this->labels[$i]; } } } else { foreach ($this->samples as $i => $sample) { if ($sample[$column] < $value) { $leftSamples[] = $sample; $leftLabels[] = $this->labels[$i]; } else { $rightSamples[] = $sample; $rightLabels[] = $this->labels[$i]; } } } return [ self::quick($leftSamples, $leftLabels), self::quick($rightSamples, $rightLabels), ]; }
[ "public", "function", "partition", "(", "int", "$", "column", ",", "$", "value", ")", ":", "array", "{", "if", "(", "!", "is_string", "(", "$", "value", ")", "and", "!", "is_numeric", "(", "$", "value", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Value must be a string or'", ".", "' numeric type, '", ".", "gettype", "(", "$", "value", ")", ".", "' given.'", ")", ";", "}", "$", "leftSamples", "=", "$", "leftLabels", "=", "$", "rightSamples", "=", "$", "rightLabels", "=", "[", "]", ";", "if", "(", "$", "this", "->", "columnType", "(", "$", "column", ")", "===", "DataType", "::", "CATEGORICAL", ")", "{", "foreach", "(", "$", "this", "->", "samples", "as", "$", "i", "=>", "$", "sample", ")", "{", "if", "(", "$", "sample", "[", "$", "column", "]", "===", "$", "value", ")", "{", "$", "leftSamples", "[", "]", "=", "$", "sample", ";", "$", "leftLabels", "[", "]", "=", "$", "this", "->", "labels", "[", "$", "i", "]", ";", "}", "else", "{", "$", "rightSamples", "[", "]", "=", "$", "sample", ";", "$", "rightLabels", "[", "]", "=", "$", "this", "->", "labels", "[", "$", "i", "]", ";", "}", "}", "}", "else", "{", "foreach", "(", "$", "this", "->", "samples", "as", "$", "i", "=>", "$", "sample", ")", "{", "if", "(", "$", "sample", "[", "$", "column", "]", "<", "$", "value", ")", "{", "$", "leftSamples", "[", "]", "=", "$", "sample", ";", "$", "leftLabels", "[", "]", "=", "$", "this", "->", "labels", "[", "$", "i", "]", ";", "}", "else", "{", "$", "rightSamples", "[", "]", "=", "$", "sample", ";", "$", "rightLabels", "[", "]", "=", "$", "this", "->", "labels", "[", "$", "i", "]", ";", "}", "}", "}", "return", "[", "self", "::", "quick", "(", "$", "leftSamples", ",", "$", "leftLabels", ")", ",", "self", "::", "quick", "(", "$", "rightSamples", ",", "$", "rightLabels", ")", ",", "]", ";", "}" ]
Partition the dataset into left and right subsets by a specified feature column. The dataset is split such that, for categorical values, the left subset contains all samples that match the value and the right side contains samples that do not match. For continuous values, the left side contains all the samples that are less than the target value, and the right side contains the samples that are greater than or equal to the value. @param int $column @param mixed $value @throws \InvalidArgumentException @return array
[ "Partition", "the", "dataset", "into", "left", "and", "right", "subsets", "by", "a", "specified", "feature", "column", ".", "The", "dataset", "is", "split", "such", "that", "for", "categorical", "values", "the", "left", "subset", "contains", "all", "samples", "that", "match", "the", "value", "and", "the", "right", "side", "contains", "samples", "that", "do", "not", "match", ".", "For", "continuous", "values", "the", "left", "side", "contains", "all", "the", "samples", "that", "are", "less", "than", "the", "target", "value", "and", "the", "right", "side", "contains", "the", "samples", "that", "are", "greater", "than", "or", "equal", "to", "the", "value", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L631-L666
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.spatialPartition
public function spatialPartition(array $leftCentroid, array $rightCentroid, Distance $kernel) { if (count($leftCentroid) !== count($rightCentroid)) { throw new InvalidArgumentException('Dimensionality mismatch between' . ' left and right centroids.'); } $leftSamples = $leftLabels = $rightSamples = $rightLabels = []; foreach ($this->samples as $i => $sample) { $lHat = $kernel->compute($sample, $leftCentroid); $rHat = $kernel->compute($sample, $rightCentroid); if ($lHat < $rHat) { $leftSamples[] = $sample; $leftLabels[] = $this->labels[$i]; } else { $rightSamples[] = $sample; $rightLabels[] = $this->labels[$i]; } } return [ self::quick($leftSamples, $leftLabels), self::quick($rightSamples, $rightLabels), ]; }
php
public function spatialPartition(array $leftCentroid, array $rightCentroid, Distance $kernel) { if (count($leftCentroid) !== count($rightCentroid)) { throw new InvalidArgumentException('Dimensionality mismatch between' . ' left and right centroids.'); } $leftSamples = $leftLabels = $rightSamples = $rightLabels = []; foreach ($this->samples as $i => $sample) { $lHat = $kernel->compute($sample, $leftCentroid); $rHat = $kernel->compute($sample, $rightCentroid); if ($lHat < $rHat) { $leftSamples[] = $sample; $leftLabels[] = $this->labels[$i]; } else { $rightSamples[] = $sample; $rightLabels[] = $this->labels[$i]; } } return [ self::quick($leftSamples, $leftLabels), self::quick($rightSamples, $rightLabels), ]; }
[ "public", "function", "spatialPartition", "(", "array", "$", "leftCentroid", ",", "array", "$", "rightCentroid", ",", "Distance", "$", "kernel", ")", "{", "if", "(", "count", "(", "$", "leftCentroid", ")", "!==", "count", "(", "$", "rightCentroid", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Dimensionality mismatch between'", ".", "' left and right centroids.'", ")", ";", "}", "$", "leftSamples", "=", "$", "leftLabels", "=", "$", "rightSamples", "=", "$", "rightLabels", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "samples", "as", "$", "i", "=>", "$", "sample", ")", "{", "$", "lHat", "=", "$", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "leftCentroid", ")", ";", "$", "rHat", "=", "$", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "rightCentroid", ")", ";", "if", "(", "$", "lHat", "<", "$", "rHat", ")", "{", "$", "leftSamples", "[", "]", "=", "$", "sample", ";", "$", "leftLabels", "[", "]", "=", "$", "this", "->", "labels", "[", "$", "i", "]", ";", "}", "else", "{", "$", "rightSamples", "[", "]", "=", "$", "sample", ";", "$", "rightLabels", "[", "]", "=", "$", "this", "->", "labels", "[", "$", "i", "]", ";", "}", "}", "return", "[", "self", "::", "quick", "(", "$", "leftSamples", ",", "$", "leftLabels", ")", ",", "self", "::", "quick", "(", "$", "rightSamples", ",", "$", "rightLabels", ")", ",", "]", ";", "}" ]
Partition the dataset into left and right subsets based on their distance between two centroids. @param array $leftCentroid @param array $rightCentroid @param \Rubix\ML\Kernels\Distance\Distance $kernel @throws \InvalidArgumentException @return array
[ "Partition", "the", "dataset", "into", "left", "and", "right", "subsets", "based", "on", "their", "distance", "between", "two", "centroids", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L678-L704
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.randomSubsetWithReplacement
public function randomSubsetWithReplacement(int $n) : self { if ($n < 1) { throw new InvalidArgumentException('Cannot generate a' . " subset of less than 1 sample, $n given."); } $max = $this->numRows() - 1; $samples = $labels = []; for ($i = 0; $i < $n; $i++) { $index = rand(0, $max); $samples[] = $this->samples[$index]; $labels[] = $this->labels[$index]; } return self::quick($samples, $labels); }
php
public function randomSubsetWithReplacement(int $n) : self { if ($n < 1) { throw new InvalidArgumentException('Cannot generate a' . " subset of less than 1 sample, $n given."); } $max = $this->numRows() - 1; $samples = $labels = []; for ($i = 0; $i < $n; $i++) { $index = rand(0, $max); $samples[] = $this->samples[$index]; $labels[] = $this->labels[$index]; } return self::quick($samples, $labels); }
[ "public", "function", "randomSubsetWithReplacement", "(", "int", "$", "n", ")", ":", "self", "{", "if", "(", "$", "n", "<", "1", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Cannot generate a'", ".", "\" subset of less than 1 sample, $n given.\"", ")", ";", "}", "$", "max", "=", "$", "this", "->", "numRows", "(", ")", "-", "1", ";", "$", "samples", "=", "$", "labels", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "n", ";", "$", "i", "++", ")", "{", "$", "index", "=", "rand", "(", "0", ",", "$", "max", ")", ";", "$", "samples", "[", "]", "=", "$", "this", "->", "samples", "[", "$", "index", "]", ";", "$", "labels", "[", "]", "=", "$", "this", "->", "labels", "[", "$", "index", "]", ";", "}", "return", "self", "::", "quick", "(", "$", "samples", ",", "$", "labels", ")", ";", "}" ]
Generate a random subset with replacement. @param int $n @throws \InvalidArgumentException @return self
[ "Generate", "a", "random", "subset", "with", "replacement", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L713-L732
RubixML/RubixML
src/Datasets/Labeled.php
Labeled.randomWeightedSubsetWithReplacement
public function randomWeightedSubsetWithReplacement(int $n, array $weights) : self { if ($n < 1) { throw new InvalidArgumentException('Cannot generate a' . " subset of less than 1 sample, $n given."); } if (count($weights) !== count($this->samples)) { throw new InvalidArgumentException('The number of weights' . ' must be equal to the number of samples in the' . ' dataset, ' . count($this->samples) . ' needed' . ' but ' . count($weights) . ' given.'); } $total = array_sum($weights); $max = (int) round($total * self::PHI); $samples = $labels = []; for ($i = 0; $i < $n; $i++) { $delta = rand(0, $max) / self::PHI; foreach ($weights as $index => $weight) { $delta -= $weight; if ($delta <= 0.) { $samples[] = $this->samples[$index]; $labels[] = $this->labels[$index]; break 1; } } } return self::quick($samples, $labels); }
php
public function randomWeightedSubsetWithReplacement(int $n, array $weights) : self { if ($n < 1) { throw new InvalidArgumentException('Cannot generate a' . " subset of less than 1 sample, $n given."); } if (count($weights) !== count($this->samples)) { throw new InvalidArgumentException('The number of weights' . ' must be equal to the number of samples in the' . ' dataset, ' . count($this->samples) . ' needed' . ' but ' . count($weights) . ' given.'); } $total = array_sum($weights); $max = (int) round($total * self::PHI); $samples = $labels = []; for ($i = 0; $i < $n; $i++) { $delta = rand(0, $max) / self::PHI; foreach ($weights as $index => $weight) { $delta -= $weight; if ($delta <= 0.) { $samples[] = $this->samples[$index]; $labels[] = $this->labels[$index]; break 1; } } } return self::quick($samples, $labels); }
[ "public", "function", "randomWeightedSubsetWithReplacement", "(", "int", "$", "n", ",", "array", "$", "weights", ")", ":", "self", "{", "if", "(", "$", "n", "<", "1", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Cannot generate a'", ".", "\" subset of less than 1 sample, $n given.\"", ")", ";", "}", "if", "(", "count", "(", "$", "weights", ")", "!==", "count", "(", "$", "this", "->", "samples", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The number of weights'", ".", "' must be equal to the number of samples in the'", ".", "' dataset, '", ".", "count", "(", "$", "this", "->", "samples", ")", ".", "' needed'", ".", "' but '", ".", "count", "(", "$", "weights", ")", ".", "' given.'", ")", ";", "}", "$", "total", "=", "array_sum", "(", "$", "weights", ")", ";", "$", "max", "=", "(", "int", ")", "round", "(", "$", "total", "*", "self", "::", "PHI", ")", ";", "$", "samples", "=", "$", "labels", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "n", ";", "$", "i", "++", ")", "{", "$", "delta", "=", "rand", "(", "0", ",", "$", "max", ")", "/", "self", "::", "PHI", ";", "foreach", "(", "$", "weights", "as", "$", "index", "=>", "$", "weight", ")", "{", "$", "delta", "-=", "$", "weight", ";", "if", "(", "$", "delta", "<=", "0.", ")", "{", "$", "samples", "[", "]", "=", "$", "this", "->", "samples", "[", "$", "index", "]", ";", "$", "labels", "[", "]", "=", "$", "this", "->", "labels", "[", "$", "index", "]", ";", "break", "1", ";", "}", "}", "}", "return", "self", "::", "quick", "(", "$", "samples", ",", "$", "labels", ")", ";", "}" ]
Generate a random weighted subset with replacement. @param int $n @param (int|float)[] $weights @throws \InvalidArgumentException @return self
[ "Generate", "a", "random", "weighted", "subset", "with", "replacement", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L742-L777
RubixML/RubixML
src/Classifiers/RadiusNeighbors.php
RadiusNeighbors.predict
public function predict(Dataset $dataset) : array { if ($this->tree->bare()) { throw new RuntimeException('The learner has not' . ' been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $predictions = []; foreach ($dataset as $sample) { [$samples, $labels, $distances] = $this->tree->range($sample, $this->radius); if (empty($labels)) { $predictions[] = self::OUTLIER; continue 1; } if ($this->weighted) { $weights = array_fill_keys($labels, 0.); foreach ($labels as $i => $label) { $weights[$label] += 1. / (1. + $distances[$i]); } } else { $weights = array_count_values($labels); } $predictions[] = argmax($weights); } return $predictions; }
php
public function predict(Dataset $dataset) : array { if ($this->tree->bare()) { throw new RuntimeException('The learner has not' . ' been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); $predictions = []; foreach ($dataset as $sample) { [$samples, $labels, $distances] = $this->tree->range($sample, $this->radius); if (empty($labels)) { $predictions[] = self::OUTLIER; continue 1; } if ($this->weighted) { $weights = array_fill_keys($labels, 0.); foreach ($labels as $i => $label) { $weights[$label] += 1. / (1. + $distances[$i]); } } else { $weights = array_count_values($labels); } $predictions[] = argmax($weights); } return $predictions; }
[ "public", "function", "predict", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "if", "(", "$", "this", "->", "tree", "->", "bare", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'The learner has not'", ".", "' been trained.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "$", "predictions", "=", "[", "]", ";", "foreach", "(", "$", "dataset", "as", "$", "sample", ")", "{", "[", "$", "samples", ",", "$", "labels", ",", "$", "distances", "]", "=", "$", "this", "->", "tree", "->", "range", "(", "$", "sample", ",", "$", "this", "->", "radius", ")", ";", "if", "(", "empty", "(", "$", "labels", ")", ")", "{", "$", "predictions", "[", "]", "=", "self", "::", "OUTLIER", ";", "continue", "1", ";", "}", "if", "(", "$", "this", "->", "weighted", ")", "{", "$", "weights", "=", "array_fill_keys", "(", "$", "labels", ",", "0.", ")", ";", "foreach", "(", "$", "labels", "as", "$", "i", "=>", "$", "label", ")", "{", "$", "weights", "[", "$", "label", "]", "+=", "1.", "/", "(", "1.", "+", "$", "distances", "[", "$", "i", "]", ")", ";", "}", "}", "else", "{", "$", "weights", "=", "array_count_values", "(", "$", "labels", ")", ";", "}", "$", "predictions", "[", "]", "=", "argmax", "(", "$", "weights", ")", ";", "}", "return", "$", "predictions", ";", "}" ]
Make predictions from a dataset. @param \Rubix\ML\Datasets\Dataset $dataset @throws \RuntimeException @throws \InvalidArgumentException @return array
[ "Make", "predictions", "from", "a", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/RadiusNeighbors.php#L164-L198
RubixML/RubixML
src/NeuralNet/Optimizers/RMSProp.php
RMSProp.step
public function step(Parameter $param, Tensor $gradient) : void { $g2 = $this->cache[$param->id()]; $g2 = $g2->multiply($this->decay) ->add($gradient->square()->multiply(1. - $this->decay)); $this->cache[$param->id()] = $g2; $step = $gradient->multiply($this->rate) ->divide($g2->sqrt()->clipLower(EPSILON)); $param->update($step); }
php
public function step(Parameter $param, Tensor $gradient) : void { $g2 = $this->cache[$param->id()]; $g2 = $g2->multiply($this->decay) ->add($gradient->square()->multiply(1. - $this->decay)); $this->cache[$param->id()] = $g2; $step = $gradient->multiply($this->rate) ->divide($g2->sqrt()->clipLower(EPSILON)); $param->update($step); }
[ "public", "function", "step", "(", "Parameter", "$", "param", ",", "Tensor", "$", "gradient", ")", ":", "void", "{", "$", "g2", "=", "$", "this", "->", "cache", "[", "$", "param", "->", "id", "(", ")", "]", ";", "$", "g2", "=", "$", "g2", "->", "multiply", "(", "$", "this", "->", "decay", ")", "->", "add", "(", "$", "gradient", "->", "square", "(", ")", "->", "multiply", "(", "1.", "-", "$", "this", "->", "decay", ")", ")", ";", "$", "this", "->", "cache", "[", "$", "param", "->", "id", "(", ")", "]", "=", "$", "g2", ";", "$", "step", "=", "$", "gradient", "->", "multiply", "(", "$", "this", "->", "rate", ")", "->", "divide", "(", "$", "g2", "->", "sqrt", "(", ")", "->", "clipLower", "(", "EPSILON", ")", ")", ";", "$", "param", "->", "update", "(", "$", "step", ")", ";", "}" ]
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/RMSProp.php#L87-L100
RubixML/RubixML
src/Clusterers/FuzzyCMeans.php
FuzzyCMeans.train
public function train(Dataset $dataset) : void { DatasetIsCompatibleWithEstimator::check($dataset, $this); if ($this->logger) { $this->logger->info('Learner init ' . Params::stringify([ 'c' => $this->c, 'fuzz' => $this->fuzz, 'kernel' => $this->kernel, 'epochs' => $this->epochs, 'min_change' => $this->minChange, 'seeder' => $this->seeder, ])); } $this->centroids = $this->seeder->seed($dataset, $this->c); $this->steps = $memberships = []; $samples = $dataset->samples(); $rotated = $dataset->columns(); $previous = INF; for ($epoch = 1; $epoch <= $this->epochs; $epoch++) { $memberships = array_map([self::class, 'membership'], $samples); foreach ($this->centroids as $cluster => &$centroid) { foreach ($rotated as $column => $values) { $sigma = $total = 0.; foreach ($memberships as $i => $probabilities) { $weight = $probabilities[$cluster] ** $this->fuzz; $sigma += $weight * $values[$i]; $total += $weight; } $centroid[$column] = $sigma / ($total ?: EPSILON); } } $inertia = $this->inertia($dataset, $memberships); $this->steps[] = $inertia; if ($this->logger) { $this->logger->info("Epoch $epoch complete, inertia=$inertia"); } if (is_nan($inertia)) { break 1; } if (abs($previous - $inertia) < $this->minChange) { break 1; } $previous = $inertia; } 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([ 'c' => $this->c, 'fuzz' => $this->fuzz, 'kernel' => $this->kernel, 'epochs' => $this->epochs, 'min_change' => $this->minChange, 'seeder' => $this->seeder, ])); } $this->centroids = $this->seeder->seed($dataset, $this->c); $this->steps = $memberships = []; $samples = $dataset->samples(); $rotated = $dataset->columns(); $previous = INF; for ($epoch = 1; $epoch <= $this->epochs; $epoch++) { $memberships = array_map([self::class, 'membership'], $samples); foreach ($this->centroids as $cluster => &$centroid) { foreach ($rotated as $column => $values) { $sigma = $total = 0.; foreach ($memberships as $i => $probabilities) { $weight = $probabilities[$cluster] ** $this->fuzz; $sigma += $weight * $values[$i]; $total += $weight; } $centroid[$column] = $sigma / ($total ?: EPSILON); } } $inertia = $this->inertia($dataset, $memberships); $this->steps[] = $inertia; if ($this->logger) { $this->logger->info("Epoch $epoch complete, inertia=$inertia"); } if (is_nan($inertia)) { break 1; } if (abs($previous - $inertia) < $this->minChange) { break 1; } $previous = $inertia; } 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", "(", "[", "'c'", "=>", "$", "this", "->", "c", ",", "'fuzz'", "=>", "$", "this", "->", "fuzz", ",", "'kernel'", "=>", "$", "this", "->", "kernel", ",", "'epochs'", "=>", "$", "this", "->", "epochs", ",", "'min_change'", "=>", "$", "this", "->", "minChange", ",", "'seeder'", "=>", "$", "this", "->", "seeder", ",", "]", ")", ")", ";", "}", "$", "this", "->", "centroids", "=", "$", "this", "->", "seeder", "->", "seed", "(", "$", "dataset", ",", "$", "this", "->", "c", ")", ";", "$", "this", "->", "steps", "=", "$", "memberships", "=", "[", "]", ";", "$", "samples", "=", "$", "dataset", "->", "samples", "(", ")", ";", "$", "rotated", "=", "$", "dataset", "->", "columns", "(", ")", ";", "$", "previous", "=", "INF", ";", "for", "(", "$", "epoch", "=", "1", ";", "$", "epoch", "<=", "$", "this", "->", "epochs", ";", "$", "epoch", "++", ")", "{", "$", "memberships", "=", "array_map", "(", "[", "self", "::", "class", ",", "'membership'", "]", ",", "$", "samples", ")", ";", "foreach", "(", "$", "this", "->", "centroids", "as", "$", "cluster", "=>", "&", "$", "centroid", ")", "{", "foreach", "(", "$", "rotated", "as", "$", "column", "=>", "$", "values", ")", "{", "$", "sigma", "=", "$", "total", "=", "0.", ";", "foreach", "(", "$", "memberships", "as", "$", "i", "=>", "$", "probabilities", ")", "{", "$", "weight", "=", "$", "probabilities", "[", "$", "cluster", "]", "**", "$", "this", "->", "fuzz", ";", "$", "sigma", "+=", "$", "weight", "*", "$", "values", "[", "$", "i", "]", ";", "$", "total", "+=", "$", "weight", ";", "}", "$", "centroid", "[", "$", "column", "]", "=", "$", "sigma", "/", "(", "$", "total", "?", ":", "EPSILON", ")", ";", "}", "}", "$", "inertia", "=", "$", "this", "->", "inertia", "(", "$", "dataset", ",", "$", "memberships", ")", ";", "$", "this", "->", "steps", "[", "]", "=", "$", "inertia", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "\"Epoch $epoch complete, inertia=$inertia\"", ")", ";", "}", "if", "(", "is_nan", "(", "$", "inertia", ")", ")", "{", "break", "1", ";", "}", "if", "(", "abs", "(", "$", "previous", "-", "$", "inertia", ")", "<", "$", "this", "->", "minChange", ")", "{", "break", "1", ";", "}", "$", "previous", "=", "$", "inertia", ";", "}", "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/FuzzyCMeans.php#L212-L276
RubixML/RubixML
src/Clusterers/FuzzyCMeans.php
FuzzyCMeans.membership
protected function membership(array $sample) : array { $membership = $deltas = []; foreach ($this->centroids as $centroid) { $deltas[] = $this->kernel->compute($sample, $centroid); } foreach ($this->centroids as $cluster => $centroid) { $alpha = $this->kernel->compute($sample, $centroid); $sigma = 0.; foreach ($deltas as $delta) { $sigma += ($alpha / ($delta ?: EPSILON)) ** $this->lambda; } $membership[$cluster] = 1. / ($sigma ?: EPSILON); } return $membership; }
php
protected function membership(array $sample) : array { $membership = $deltas = []; foreach ($this->centroids as $centroid) { $deltas[] = $this->kernel->compute($sample, $centroid); } foreach ($this->centroids as $cluster => $centroid) { $alpha = $this->kernel->compute($sample, $centroid); $sigma = 0.; foreach ($deltas as $delta) { $sigma += ($alpha / ($delta ?: EPSILON)) ** $this->lambda; } $membership[$cluster] = 1. / ($sigma ?: EPSILON); } return $membership; }
[ "protected", "function", "membership", "(", "array", "$", "sample", ")", ":", "array", "{", "$", "membership", "=", "$", "deltas", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "centroids", "as", "$", "centroid", ")", "{", "$", "deltas", "[", "]", "=", "$", "this", "->", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "centroid", ")", ";", "}", "foreach", "(", "$", "this", "->", "centroids", "as", "$", "cluster", "=>", "$", "centroid", ")", "{", "$", "alpha", "=", "$", "this", "->", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "centroid", ")", ";", "$", "sigma", "=", "0.", ";", "foreach", "(", "$", "deltas", "as", "$", "delta", ")", "{", "$", "sigma", "+=", "(", "$", "alpha", "/", "(", "$", "delta", "?", ":", "EPSILON", ")", ")", "**", "$", "this", "->", "lambda", ";", "}", "$", "membership", "[", "$", "cluster", "]", "=", "1.", "/", "(", "$", "sigma", "?", ":", "EPSILON", ")", ";", "}", "return", "$", "membership", ";", "}" ]
Return the membership of a sample to each of the c centroids. @param array $sample @return array
[ "Return", "the", "membership", "of", "a", "sample", "to", "each", "of", "the", "c", "centroids", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/FuzzyCMeans.php#L314-L335
RubixML/RubixML
src/Clusterers/FuzzyCMeans.php
FuzzyCMeans.inertia
protected function inertia(Dataset $dataset, array $memberships) : float { $inertia = 0.; foreach ($dataset as $i => $sample) { $membership = $memberships[$i]; foreach ($this->centroids as $cluster => $centroid) { $inertia += $membership[$cluster] * $this->kernel->compute($sample, $centroid); } } return $inertia; }
php
protected function inertia(Dataset $dataset, array $memberships) : float { $inertia = 0.; foreach ($dataset as $i => $sample) { $membership = $memberships[$i]; foreach ($this->centroids as $cluster => $centroid) { $inertia += $membership[$cluster] * $this->kernel->compute($sample, $centroid); } } return $inertia; }
[ "protected", "function", "inertia", "(", "Dataset", "$", "dataset", ",", "array", "$", "memberships", ")", ":", "float", "{", "$", "inertia", "=", "0.", ";", "foreach", "(", "$", "dataset", "as", "$", "i", "=>", "$", "sample", ")", "{", "$", "membership", "=", "$", "memberships", "[", "$", "i", "]", ";", "foreach", "(", "$", "this", "->", "centroids", "as", "$", "cluster", "=>", "$", "centroid", ")", "{", "$", "inertia", "+=", "$", "membership", "[", "$", "cluster", "]", "*", "$", "this", "->", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "centroid", ")", ";", "}", "}", "return", "$", "inertia", ";", "}" ]
Calculate the sum of distances between all samples and their closest centroid. @param \Rubix\ML\Datasets\Dataset $dataset @param array $memberships @return float
[ "Calculate", "the", "sum", "of", "distances", "between", "all", "samples", "and", "their", "closest", "centroid", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/FuzzyCMeans.php#L345-L359
RubixML/RubixML
src/CrossValidation/Reports/MulticlassBreakdown.php
MulticlassBreakdown.generate
public function generate(array $predictions, array $labels) : array { $n = count($predictions); if ($n !== count($labels)) { throw new InvalidArgumentException('The number of labels' . ' must equal the number of predictions.'); } $classes = array_unique(array_merge($predictions, $labels)); $k = count($classes); $truePos = $trueNeg = $falsePos = $falseNeg = array_fill_keys($classes, 0); foreach ($predictions as $i => $prediction) { $label = $labels[$i]; if ($prediction === $label) { $truePos[$prediction]++; foreach ($classes as $class) { if ($class !== $prediction) { $trueNeg[$class]++; } } } else { $falsePos[$prediction]++; $falseNeg[$label]++; } } $averages = array_fill_keys([ 'accuracy', 'precision', 'recall', 'specificity', 'negative_predictive_value', 'false_discovery_rate', 'miss_rate', 'fall_out', 'false_omission_rate', 'f1_score', 'mcc', 'informedness', 'markedness', ], 0.); $counts = array_fill_keys([ 'true_positives', 'true_negatives', 'false_positives', 'false_negatives', ], 0); $overall = array_replace($averages, $counts); $table = []; foreach ($truePos as $label => $tp) { $tn = $trueNeg[$label]; $fp = $falsePos[$label]; $fn = $falseNeg[$label]; $accuracy = ($tp + $tn) / ($tp + $tn + $fp + $fn); $precision = $tp / (($tp + $fp) ?: EPSILON); $recall = $tp / (($tp + $fn) ?: EPSILON); $specificity = $tn / (($tn + $fp) ?: EPSILON); $npv = $tn / (($tn + $fn) ?: EPSILON); $cardinality = $tp + $fn; $f1score = 2. * (($precision * $recall)) / (($precision + $recall) ?: EPSILON); $mcc = ($tp * $tn - $fp * $fn) / sqrt((($tp + $fp) * ($tp + $fn) * ($tn + $fp) * ($tn + $fn)) ?: EPSILON); $metrics = []; $metrics['accuracy'] = $accuracy; $metrics['precision'] = $precision; $metrics['recall'] = $recall; $metrics['specificity'] = $specificity; $metrics['negative_predictive_value'] = $npv; $metrics['false_discovery_rate'] = 1. - $precision; $metrics['miss_rate'] = 1. - $recall; $metrics['fall_out'] = 1. - $specificity; $metrics['false_omission_rate'] = 1. - $npv; $metrics['f1_score'] = $f1score; $metrics['mcc'] = $mcc; $metrics['informedness'] = $recall + $specificity - 1.; $metrics['markedness'] = $precision + $npv - 1.; $metrics['true_positives'] = $tp; $metrics['true_negatives'] = $tn; $metrics['false_positives'] = $fp; $metrics['false_negatives'] = $fn; $metrics['cardinality'] = $cardinality; $metrics['density'] = $cardinality / $n; $table[$label] = $metrics; $overall['accuracy'] += $accuracy; $overall['precision'] += $precision; $overall['recall'] += $recall; $overall['specificity'] += $specificity; $overall['negative_predictive_value'] += $npv; $overall['false_discovery_rate'] += 1. - $precision; $overall['miss_rate'] += 1. - $recall; $overall['fall_out'] += 1. - $specificity; $overall['false_omission_rate'] += 1. - $npv; $overall['f1_score'] += $f1score; $overall['mcc'] += $mcc; $overall['informedness'] += $recall + $specificity - 1.; $overall['markedness'] += $precision + $npv - 1.; $overall['true_positives'] += $tp; $overall['true_negatives'] += $tn; $overall['false_positives'] += $fp; $overall['false_negatives'] += $fn; } foreach (array_keys($averages) as $metric) { $overall[$metric] /= $k; } $overall['cardinality'] = $n; return [ 'overall' => $overall, 'label' => $table, ]; }
php
public function generate(array $predictions, array $labels) : array { $n = count($predictions); if ($n !== count($labels)) { throw new InvalidArgumentException('The number of labels' . ' must equal the number of predictions.'); } $classes = array_unique(array_merge($predictions, $labels)); $k = count($classes); $truePos = $trueNeg = $falsePos = $falseNeg = array_fill_keys($classes, 0); foreach ($predictions as $i => $prediction) { $label = $labels[$i]; if ($prediction === $label) { $truePos[$prediction]++; foreach ($classes as $class) { if ($class !== $prediction) { $trueNeg[$class]++; } } } else { $falsePos[$prediction]++; $falseNeg[$label]++; } } $averages = array_fill_keys([ 'accuracy', 'precision', 'recall', 'specificity', 'negative_predictive_value', 'false_discovery_rate', 'miss_rate', 'fall_out', 'false_omission_rate', 'f1_score', 'mcc', 'informedness', 'markedness', ], 0.); $counts = array_fill_keys([ 'true_positives', 'true_negatives', 'false_positives', 'false_negatives', ], 0); $overall = array_replace($averages, $counts); $table = []; foreach ($truePos as $label => $tp) { $tn = $trueNeg[$label]; $fp = $falsePos[$label]; $fn = $falseNeg[$label]; $accuracy = ($tp + $tn) / ($tp + $tn + $fp + $fn); $precision = $tp / (($tp + $fp) ?: EPSILON); $recall = $tp / (($tp + $fn) ?: EPSILON); $specificity = $tn / (($tn + $fp) ?: EPSILON); $npv = $tn / (($tn + $fn) ?: EPSILON); $cardinality = $tp + $fn; $f1score = 2. * (($precision * $recall)) / (($precision + $recall) ?: EPSILON); $mcc = ($tp * $tn - $fp * $fn) / sqrt((($tp + $fp) * ($tp + $fn) * ($tn + $fp) * ($tn + $fn)) ?: EPSILON); $metrics = []; $metrics['accuracy'] = $accuracy; $metrics['precision'] = $precision; $metrics['recall'] = $recall; $metrics['specificity'] = $specificity; $metrics['negative_predictive_value'] = $npv; $metrics['false_discovery_rate'] = 1. - $precision; $metrics['miss_rate'] = 1. - $recall; $metrics['fall_out'] = 1. - $specificity; $metrics['false_omission_rate'] = 1. - $npv; $metrics['f1_score'] = $f1score; $metrics['mcc'] = $mcc; $metrics['informedness'] = $recall + $specificity - 1.; $metrics['markedness'] = $precision + $npv - 1.; $metrics['true_positives'] = $tp; $metrics['true_negatives'] = $tn; $metrics['false_positives'] = $fp; $metrics['false_negatives'] = $fn; $metrics['cardinality'] = $cardinality; $metrics['density'] = $cardinality / $n; $table[$label] = $metrics; $overall['accuracy'] += $accuracy; $overall['precision'] += $precision; $overall['recall'] += $recall; $overall['specificity'] += $specificity; $overall['negative_predictive_value'] += $npv; $overall['false_discovery_rate'] += 1. - $precision; $overall['miss_rate'] += 1. - $recall; $overall['fall_out'] += 1. - $specificity; $overall['false_omission_rate'] += 1. - $npv; $overall['f1_score'] += $f1score; $overall['mcc'] += $mcc; $overall['informedness'] += $recall + $specificity - 1.; $overall['markedness'] += $precision + $npv - 1.; $overall['true_positives'] += $tp; $overall['true_negatives'] += $tn; $overall['false_positives'] += $fp; $overall['false_negatives'] += $fn; } foreach (array_keys($averages) as $metric) { $overall[$metric] /= $k; } $overall['cardinality'] = $n; return [ 'overall' => $overall, 'label' => $table, ]; }
[ "public", "function", "generate", "(", "array", "$", "predictions", ",", "array", "$", "labels", ")", ":", "array", "{", "$", "n", "=", "count", "(", "$", "predictions", ")", ";", "if", "(", "$", "n", "!==", "count", "(", "$", "labels", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The number of labels'", ".", "' must equal the number of predictions.'", ")", ";", "}", "$", "classes", "=", "array_unique", "(", "array_merge", "(", "$", "predictions", ",", "$", "labels", ")", ")", ";", "$", "k", "=", "count", "(", "$", "classes", ")", ";", "$", "truePos", "=", "$", "trueNeg", "=", "$", "falsePos", "=", "$", "falseNeg", "=", "array_fill_keys", "(", "$", "classes", ",", "0", ")", ";", "foreach", "(", "$", "predictions", "as", "$", "i", "=>", "$", "prediction", ")", "{", "$", "label", "=", "$", "labels", "[", "$", "i", "]", ";", "if", "(", "$", "prediction", "===", "$", "label", ")", "{", "$", "truePos", "[", "$", "prediction", "]", "++", ";", "foreach", "(", "$", "classes", "as", "$", "class", ")", "{", "if", "(", "$", "class", "!==", "$", "prediction", ")", "{", "$", "trueNeg", "[", "$", "class", "]", "++", ";", "}", "}", "}", "else", "{", "$", "falsePos", "[", "$", "prediction", "]", "++", ";", "$", "falseNeg", "[", "$", "label", "]", "++", ";", "}", "}", "$", "averages", "=", "array_fill_keys", "(", "[", "'accuracy'", ",", "'precision'", ",", "'recall'", ",", "'specificity'", ",", "'negative_predictive_value'", ",", "'false_discovery_rate'", ",", "'miss_rate'", ",", "'fall_out'", ",", "'false_omission_rate'", ",", "'f1_score'", ",", "'mcc'", ",", "'informedness'", ",", "'markedness'", ",", "]", ",", "0.", ")", ";", "$", "counts", "=", "array_fill_keys", "(", "[", "'true_positives'", ",", "'true_negatives'", ",", "'false_positives'", ",", "'false_negatives'", ",", "]", ",", "0", ")", ";", "$", "overall", "=", "array_replace", "(", "$", "averages", ",", "$", "counts", ")", ";", "$", "table", "=", "[", "]", ";", "foreach", "(", "$", "truePos", "as", "$", "label", "=>", "$", "tp", ")", "{", "$", "tn", "=", "$", "trueNeg", "[", "$", "label", "]", ";", "$", "fp", "=", "$", "falsePos", "[", "$", "label", "]", ";", "$", "fn", "=", "$", "falseNeg", "[", "$", "label", "]", ";", "$", "accuracy", "=", "(", "$", "tp", "+", "$", "tn", ")", "/", "(", "$", "tp", "+", "$", "tn", "+", "$", "fp", "+", "$", "fn", ")", ";", "$", "precision", "=", "$", "tp", "/", "(", "(", "$", "tp", "+", "$", "fp", ")", "?", ":", "EPSILON", ")", ";", "$", "recall", "=", "$", "tp", "/", "(", "(", "$", "tp", "+", "$", "fn", ")", "?", ":", "EPSILON", ")", ";", "$", "specificity", "=", "$", "tn", "/", "(", "(", "$", "tn", "+", "$", "fp", ")", "?", ":", "EPSILON", ")", ";", "$", "npv", "=", "$", "tn", "/", "(", "(", "$", "tn", "+", "$", "fn", ")", "?", ":", "EPSILON", ")", ";", "$", "cardinality", "=", "$", "tp", "+", "$", "fn", ";", "$", "f1score", "=", "2.", "*", "(", "(", "$", "precision", "*", "$", "recall", ")", ")", "/", "(", "(", "$", "precision", "+", "$", "recall", ")", "?", ":", "EPSILON", ")", ";", "$", "mcc", "=", "(", "$", "tp", "*", "$", "tn", "-", "$", "fp", "*", "$", "fn", ")", "/", "sqrt", "(", "(", "(", "$", "tp", "+", "$", "fp", ")", "*", "(", "$", "tp", "+", "$", "fn", ")", "*", "(", "$", "tn", "+", "$", "fp", ")", "*", "(", "$", "tn", "+", "$", "fn", ")", ")", "?", ":", "EPSILON", ")", ";", "$", "metrics", "=", "[", "]", ";", "$", "metrics", "[", "'accuracy'", "]", "=", "$", "accuracy", ";", "$", "metrics", "[", "'precision'", "]", "=", "$", "precision", ";", "$", "metrics", "[", "'recall'", "]", "=", "$", "recall", ";", "$", "metrics", "[", "'specificity'", "]", "=", "$", "specificity", ";", "$", "metrics", "[", "'negative_predictive_value'", "]", "=", "$", "npv", ";", "$", "metrics", "[", "'false_discovery_rate'", "]", "=", "1.", "-", "$", "precision", ";", "$", "metrics", "[", "'miss_rate'", "]", "=", "1.", "-", "$", "recall", ";", "$", "metrics", "[", "'fall_out'", "]", "=", "1.", "-", "$", "specificity", ";", "$", "metrics", "[", "'false_omission_rate'", "]", "=", "1.", "-", "$", "npv", ";", "$", "metrics", "[", "'f1_score'", "]", "=", "$", "f1score", ";", "$", "metrics", "[", "'mcc'", "]", "=", "$", "mcc", ";", "$", "metrics", "[", "'informedness'", "]", "=", "$", "recall", "+", "$", "specificity", "-", "1.", ";", "$", "metrics", "[", "'markedness'", "]", "=", "$", "precision", "+", "$", "npv", "-", "1.", ";", "$", "metrics", "[", "'true_positives'", "]", "=", "$", "tp", ";", "$", "metrics", "[", "'true_negatives'", "]", "=", "$", "tn", ";", "$", "metrics", "[", "'false_positives'", "]", "=", "$", "fp", ";", "$", "metrics", "[", "'false_negatives'", "]", "=", "$", "fn", ";", "$", "metrics", "[", "'cardinality'", "]", "=", "$", "cardinality", ";", "$", "metrics", "[", "'density'", "]", "=", "$", "cardinality", "/", "$", "n", ";", "$", "table", "[", "$", "label", "]", "=", "$", "metrics", ";", "$", "overall", "[", "'accuracy'", "]", "+=", "$", "accuracy", ";", "$", "overall", "[", "'precision'", "]", "+=", "$", "precision", ";", "$", "overall", "[", "'recall'", "]", "+=", "$", "recall", ";", "$", "overall", "[", "'specificity'", "]", "+=", "$", "specificity", ";", "$", "overall", "[", "'negative_predictive_value'", "]", "+=", "$", "npv", ";", "$", "overall", "[", "'false_discovery_rate'", "]", "+=", "1.", "-", "$", "precision", ";", "$", "overall", "[", "'miss_rate'", "]", "+=", "1.", "-", "$", "recall", ";", "$", "overall", "[", "'fall_out'", "]", "+=", "1.", "-", "$", "specificity", ";", "$", "overall", "[", "'false_omission_rate'", "]", "+=", "1.", "-", "$", "npv", ";", "$", "overall", "[", "'f1_score'", "]", "+=", "$", "f1score", ";", "$", "overall", "[", "'mcc'", "]", "+=", "$", "mcc", ";", "$", "overall", "[", "'informedness'", "]", "+=", "$", "recall", "+", "$", "specificity", "-", "1.", ";", "$", "overall", "[", "'markedness'", "]", "+=", "$", "precision", "+", "$", "npv", "-", "1.", ";", "$", "overall", "[", "'true_positives'", "]", "+=", "$", "tp", ";", "$", "overall", "[", "'true_negatives'", "]", "+=", "$", "tn", ";", "$", "overall", "[", "'false_positives'", "]", "+=", "$", "fp", ";", "$", "overall", "[", "'false_negatives'", "]", "+=", "$", "fn", ";", "}", "foreach", "(", "array_keys", "(", "$", "averages", ")", "as", "$", "metric", ")", "{", "$", "overall", "[", "$", "metric", "]", "/=", "$", "k", ";", "}", "$", "overall", "[", "'cardinality'", "]", "=", "$", "n", ";", "return", "[", "'overall'", "=>", "$", "overall", ",", "'label'", "=>", "$", "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/MulticlassBreakdown.php#L44-L162
RubixML/RubixML
src/Graph/Nodes/Hypersphere.php
Hypersphere.split
public static function split(Dataset $dataset, Distance $kernel) : self { $samples = $dataset->samples(); $center = Matrix::quick($samples) ->transpose() ->mean() ->asArray(); $distances = []; foreach ($samples as $sample) { $distances[] = $kernel->compute($sample, $center); } $radius = max($distances); $leftCentroid = $dataset->row(argmax($distances)); $distances = []; foreach ($samples as $sample) { $distances[] = $kernel->compute($sample, $leftCentroid); } $rightCentroid = $dataset->row(argmax($distances)); $subsets = $dataset->spatialPartition($leftCentroid, $rightCentroid, $kernel); return new self($center, $radius, $subsets); }
php
public static function split(Dataset $dataset, Distance $kernel) : self { $samples = $dataset->samples(); $center = Matrix::quick($samples) ->transpose() ->mean() ->asArray(); $distances = []; foreach ($samples as $sample) { $distances[] = $kernel->compute($sample, $center); } $radius = max($distances); $leftCentroid = $dataset->row(argmax($distances)); $distances = []; foreach ($samples as $sample) { $distances[] = $kernel->compute($sample, $leftCentroid); } $rightCentroid = $dataset->row(argmax($distances)); $subsets = $dataset->spatialPartition($leftCentroid, $rightCentroid, $kernel); return new self($center, $radius, $subsets); }
[ "public", "static", "function", "split", "(", "Dataset", "$", "dataset", ",", "Distance", "$", "kernel", ")", ":", "self", "{", "$", "samples", "=", "$", "dataset", "->", "samples", "(", ")", ";", "$", "center", "=", "Matrix", "::", "quick", "(", "$", "samples", ")", "->", "transpose", "(", ")", "->", "mean", "(", ")", "->", "asArray", "(", ")", ";", "$", "distances", "=", "[", "]", ";", "foreach", "(", "$", "samples", "as", "$", "sample", ")", "{", "$", "distances", "[", "]", "=", "$", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "center", ")", ";", "}", "$", "radius", "=", "max", "(", "$", "distances", ")", ";", "$", "leftCentroid", "=", "$", "dataset", "->", "row", "(", "argmax", "(", "$", "distances", ")", ")", ";", "$", "distances", "=", "[", "]", ";", "foreach", "(", "$", "samples", "as", "$", "sample", ")", "{", "$", "distances", "[", "]", "=", "$", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "leftCentroid", ")", ";", "}", "$", "rightCentroid", "=", "$", "dataset", "->", "row", "(", "argmax", "(", "$", "distances", ")", ")", ";", "$", "subsets", "=", "$", "dataset", "->", "spatialPartition", "(", "$", "leftCentroid", ",", "$", "rightCentroid", ",", "$", "kernel", ")", ";", "return", "new", "self", "(", "$", "center", ",", "$", "radius", ",", "$", "subsets", ")", ";", "}" ]
Factory method to build a centroid node from a labeled dataset using the column with the highest variance as the column for the split. @param \Rubix\ML\Datasets\Dataset $dataset @param \Rubix\ML\Kernels\Distance\Distance $kernel @return self
[ "Factory", "method", "to", "build", "a", "centroid", "node", "from", "a", "labeled", "dataset", "using", "the", "column", "with", "the", "highest", "variance", "as", "the", "column", "for", "the", "split", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/Hypersphere.php#L55-L85
RubixML/RubixML
src/Classifiers/DummyClassifier.php
DummyClassifier.train
public function train(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This estimator requires a' . ' labeled training set.'); } $this->strategy->fit($dataset->labels()); $this->trained = true; }
php
public function train(Dataset $dataset) : void { if (!$dataset instanceof Labeled) { throw new InvalidArgumentException('This estimator requires a' . ' labeled training set.'); } $this->strategy->fit($dataset->labels()); $this->trained = true; }
[ "public", "function", "train", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "if", "(", "!", "$", "dataset", "instanceof", "Labeled", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'This estimator requires a'", ".", "' labeled training set.'", ")", ";", "}", "$", "this", "->", "strategy", "->", "fit", "(", "$", "dataset", "->", "labels", "(", ")", ")", ";", "$", "this", "->", "trained", "=", "true", ";", "}" ]
Fit the training set to the given guessing strategy. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException
[ "Fit", "the", "training", "set", "to", "the", "given", "guessing", "strategy", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/DummyClassifier.php#L88-L98
RubixML/RubixML
src/Classifiers/DummyClassifier.php
DummyClassifier.predict
public function predict(Dataset $dataset) : array { if (!$this->trained) { throw new RuntimeException('The learner has not' . ' been trained.'); } $n = $dataset->numRows(); $predictions = []; for ($i = 0; $i < $n; $i++) { $predictions[] = $this->strategy->guess(); } return $predictions; }
php
public function predict(Dataset $dataset) : array { if (!$this->trained) { throw new RuntimeException('The learner has not' . ' been trained.'); } $n = $dataset->numRows(); $predictions = []; for ($i = 0; $i < $n; $i++) { $predictions[] = $this->strategy->guess(); } return $predictions; }
[ "public", "function", "predict", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "if", "(", "!", "$", "this", "->", "trained", ")", "{", "throw", "new", "RuntimeException", "(", "'The learner has not'", ".", "' been trained.'", ")", ";", "}", "$", "n", "=", "$", "dataset", "->", "numRows", "(", ")", ";", "$", "predictions", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "n", ";", "$", "i", "++", ")", "{", "$", "predictions", "[", "]", "=", "$", "this", "->", "strategy", "->", "guess", "(", ")", ";", "}", "return", "$", "predictions", ";", "}" ]
Make a prediction of a given sample dataset. @param \Rubix\ML\Datasets\Dataset $dataset @return array
[ "Make", "a", "prediction", "of", "a", "given", "sample", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/DummyClassifier.php#L106-L122
RubixML/RubixML
src/Pipeline.php
Pipeline.trained
public function trained() : bool { return ($this->estimator instanceof Learner and $this->estimator->trained() and $this->fitted) or $this->fitted; }
php
public function trained() : bool { return ($this->estimator instanceof Learner and $this->estimator->trained() and $this->fitted) or $this->fitted; }
[ "public", "function", "trained", "(", ")", ":", "bool", "{", "return", "(", "$", "this", "->", "estimator", "instanceof", "Learner", "and", "$", "this", "->", "estimator", "->", "trained", "(", ")", "and", "$", "this", "->", "fitted", ")", "or", "$", "this", "->", "fitted", ";", "}" ]
Has the learner been trained? @return bool
[ "Has", "the", "learner", "been", "trained?" ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L118-L123
RubixML/RubixML
src/Pipeline.php
Pipeline.train
public function train(Dataset $dataset) : void { $this->fit($dataset); if ($this->estimator instanceof Learner) { $this->estimator->train($dataset); } $this->fitted = true; }
php
public function train(Dataset $dataset) : void { $this->fit($dataset); if ($this->estimator instanceof Learner) { $this->estimator->train($dataset); } $this->fitted = true; }
[ "public", "function", "train", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "$", "this", "->", "fit", "(", "$", "dataset", ")", ";", "if", "(", "$", "this", "->", "estimator", "instanceof", "Learner", ")", "{", "$", "this", "->", "estimator", "->", "train", "(", "$", "dataset", ")", ";", "}", "$", "this", "->", "fitted", "=", "true", ";", "}" ]
Run the training dataset through all transformers in order and use the transformed dataset to train the estimator. @param \Rubix\ML\Datasets\Dataset $dataset
[ "Run", "the", "training", "dataset", "through", "all", "transformers", "in", "order", "and", "use", "the", "transformed", "dataset", "to", "train", "the", "estimator", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L141-L150
RubixML/RubixML
src/Pipeline.php
Pipeline.partial
public function partial(Dataset $dataset) : void { if ($this->elastic) { $this->update($dataset); } if ($this->estimator instanceof Online) { $this->estimator->partial($dataset); } }
php
public function partial(Dataset $dataset) : void { if ($this->elastic) { $this->update($dataset); } if ($this->estimator instanceof Online) { $this->estimator->partial($dataset); } }
[ "public", "function", "partial", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "if", "(", "$", "this", "->", "elastic", ")", "{", "$", "this", "->", "update", "(", "$", "dataset", ")", ";", "}", "if", "(", "$", "this", "->", "estimator", "instanceof", "Online", ")", "{", "$", "this", "->", "estimator", "->", "partial", "(", "$", "dataset", ")", ";", "}", "}" ]
Perform a partial train. @param \Rubix\ML\Datasets\Dataset $dataset
[ "Perform", "a", "partial", "train", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L157-L166
RubixML/RubixML
src/Pipeline.php
Pipeline.predict
public function predict(Dataset $dataset) : array { $this->preprocess($dataset); return $this->estimator->predict($dataset); }
php
public function predict(Dataset $dataset) : array { $this->preprocess($dataset); return $this->estimator->predict($dataset); }
[ "public", "function", "predict", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "$", "this", "->", "preprocess", "(", "$", "dataset", ")", ";", "return", "$", "this", "->", "estimator", "->", "predict", "(", "$", "dataset", ")", ";", "}" ]
Preprocess the dataset and return predictions from the estimator. @param \Rubix\ML\Datasets\Dataset $dataset @return array
[ "Preprocess", "the", "dataset", "and", "return", "predictions", "from", "the", "estimator", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L174-L179
RubixML/RubixML
src/Pipeline.php
Pipeline.proba
public function proba(Dataset $dataset) : array { $base = $this->base(); if ($base instanceof Probabilistic) { $this->preprocess($dataset); return $base->proba($dataset); } throw new RuntimeException('Base estimator must' . ' implement the probabilistic interface.'); }
php
public function proba(Dataset $dataset) : array { $base = $this->base(); if ($base instanceof Probabilistic) { $this->preprocess($dataset); return $base->proba($dataset); } throw new RuntimeException('Base estimator must' . ' implement the probabilistic interface.'); }
[ "public", "function", "proba", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "$", "base", "=", "$", "this", "->", "base", "(", ")", ";", "if", "(", "$", "base", "instanceof", "Probabilistic", ")", "{", "$", "this", "->", "preprocess", "(", "$", "dataset", ")", ";", "return", "$", "base", "->", "proba", "(", "$", "dataset", ")", ";", "}", "throw", "new", "RuntimeException", "(", "'Base estimator must'", ".", "' implement the probabilistic interface.'", ")", ";", "}" ]
Estimate probabilities for each possible outcome. @param \Rubix\ML\Datasets\Dataset $dataset @throws \RuntimeException @return array
[ "Estimate", "probabilities", "for", "each", "possible", "outcome", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L188-L200
RubixML/RubixML
src/Pipeline.php
Pipeline.fit
protected function fit(Dataset $dataset) : void { foreach ($this->transformers as $transformer) { if ($transformer instanceof Stateful) { $transformer->fit($dataset); if ($this->logger) { $this->logger->info('Fitted ' . Params::shortName($transformer)); } } $dataset->apply($transformer); if ($this->logger) { $this->logger->info('Applied ' . Params::shortName($transformer)); } } }
php
protected function fit(Dataset $dataset) : void { foreach ($this->transformers as $transformer) { if ($transformer instanceof Stateful) { $transformer->fit($dataset); if ($this->logger) { $this->logger->info('Fitted ' . Params::shortName($transformer)); } } $dataset->apply($transformer); if ($this->logger) { $this->logger->info('Applied ' . Params::shortName($transformer)); } } }
[ "protected", "function", "fit", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "foreach", "(", "$", "this", "->", "transformers", "as", "$", "transformer", ")", "{", "if", "(", "$", "transformer", "instanceof", "Stateful", ")", "{", "$", "transformer", "->", "fit", "(", "$", "dataset", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Fitted '", ".", "Params", "::", "shortName", "(", "$", "transformer", ")", ")", ";", "}", "}", "$", "dataset", "->", "apply", "(", "$", "transformer", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Applied '", ".", "Params", "::", "shortName", "(", "$", "transformer", ")", ")", ";", "}", "}", "}" ]
Fit the transformer middelware to a dataset. @param \Rubix\ML\Datasets\Dataset $dataset
[ "Fit", "the", "transformer", "middelware", "to", "a", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L207-L226
RubixML/RubixML
src/Pipeline.php
Pipeline.update
protected function update(Dataset $dataset) : void { foreach ($this->transformers as $transformer) { if ($transformer instanceof Elastic) { $transformer->update($dataset); if ($this->logger) { $this->logger->info('Updated ' . Params::shortName($transformer)); } } $dataset->apply($transformer); if ($this->logger) { $this->logger->info('Applied ' . Params::shortName($transformer)); } } }
php
protected function update(Dataset $dataset) : void { foreach ($this->transformers as $transformer) { if ($transformer instanceof Elastic) { $transformer->update($dataset); if ($this->logger) { $this->logger->info('Updated ' . Params::shortName($transformer)); } } $dataset->apply($transformer); if ($this->logger) { $this->logger->info('Applied ' . Params::shortName($transformer)); } } }
[ "protected", "function", "update", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "foreach", "(", "$", "this", "->", "transformers", "as", "$", "transformer", ")", "{", "if", "(", "$", "transformer", "instanceof", "Elastic", ")", "{", "$", "transformer", "->", "update", "(", "$", "dataset", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Updated '", ".", "Params", "::", "shortName", "(", "$", "transformer", ")", ")", ";", "}", "}", "$", "dataset", "->", "apply", "(", "$", "transformer", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Applied '", ".", "Params", "::", "shortName", "(", "$", "transformer", ")", ")", ";", "}", "}", "}" ]
Update the fitting of the transformer middleware. @param \Rubix\ML\Datasets\Dataset $dataset
[ "Update", "the", "fitting", "of", "the", "transformer", "middleware", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L233-L252
RubixML/RubixML
src/Pipeline.php
Pipeline.preprocess
protected function preprocess(Dataset $dataset) : void { foreach ($this->transformers as $transformer) { $dataset->apply($transformer); } }
php
protected function preprocess(Dataset $dataset) : void { foreach ($this->transformers as $transformer) { $dataset->apply($transformer); } }
[ "protected", "function", "preprocess", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "foreach", "(", "$", "this", "->", "transformers", "as", "$", "transformer", ")", "{", "$", "dataset", "->", "apply", "(", "$", "transformer", ")", ";", "}", "}" ]
Apply the transformer middleware over a dataset. @param \Rubix\ML\Datasets\Dataset $dataset
[ "Apply", "the", "transformer", "middleware", "over", "a", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L259-L264
RubixML/RubixML
src/Graph/Nodes/BinaryNode.php
BinaryNode.children
public function children() : Generator { if ($this->left) { yield $this->left; } if ($this->right) { yield $this->right; } }
php
public function children() : Generator { if ($this->left) { yield $this->left; } if ($this->right) { yield $this->right; } }
[ "public", "function", "children", "(", ")", ":", "Generator", "{", "if", "(", "$", "this", "->", "left", ")", "{", "yield", "$", "this", "->", "left", ";", "}", "if", "(", "$", "this", "->", "right", ")", "{", "yield", "$", "this", "->", "right", ";", "}", "}" ]
Return the children of this node in an array. @return \Generator
[ "Return", "the", "children", "of", "this", "node", "in", "an", "array", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L55-L64
RubixML/RubixML
src/Graph/Nodes/BinaryNode.php
BinaryNode.height
public function height() : int { return 1 + max( $this->left ? $this->left->height() : 0, $this->right ? $this->right->height() : 0 ); }
php
public function height() : int { return 1 + max( $this->left ? $this->left->height() : 0, $this->right ? $this->right->height() : 0 ); }
[ "public", "function", "height", "(", ")", ":", "int", "{", "return", "1", "+", "max", "(", "$", "this", "->", "left", "?", "$", "this", "->", "left", "->", "height", "(", ")", ":", "0", ",", "$", "this", "->", "right", "?", "$", "this", "->", "right", "->", "height", "(", ")", ":", "0", ")", ";", "}" ]
Recursive function to determine the height of the node. @return int
[ "Recursive", "function", "to", "determine", "the", "height", "of", "the", "node", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L92-L98
RubixML/RubixML
src/Graph/Nodes/BinaryNode.php
BinaryNode.balance
public function balance() : int { return ($this->right ? $this->right->height() : 0) - ($this->left ? $this->left->height() : 0); }
php
public function balance() : int { return ($this->right ? $this->right->height() : 0) - ($this->left ? $this->left->height() : 0); }
[ "public", "function", "balance", "(", ")", ":", "int", "{", "return", "(", "$", "this", "->", "right", "?", "$", "this", "->", "right", "->", "height", "(", ")", ":", "0", ")", "-", "(", "$", "this", "->", "left", "?", "$", "this", "->", "left", "->", "height", "(", ")", ":", "0", ")", ";", "}" ]
The balance factor of the node. Negative numbers indicate a lean to the left, positive to the right, and 0 is perfectly balanced. @return int
[ "The", "balance", "factor", "of", "the", "node", ".", "Negative", "numbers", "indicate", "a", "lean", "to", "the", "left", "positive", "to", "the", "right", "and", "0", "is", "perfectly", "balanced", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L107-L111
RubixML/RubixML
src/Graph/Nodes/BinaryNode.php
BinaryNode.attachLeft
public function attachLeft(BinaryNode $node) : void { $node->setParent($this); $this->left = $node; }
php
public function attachLeft(BinaryNode $node) : void { $node->setParent($this); $this->left = $node; }
[ "public", "function", "attachLeft", "(", "BinaryNode", "$", "node", ")", ":", "void", "{", "$", "node", "->", "setParent", "(", "$", "this", ")", ";", "$", "this", "->", "left", "=", "$", "node", ";", "}" ]
Set the left child node. @param self $node
[ "Set", "the", "left", "child", "node", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L128-L133
RubixML/RubixML
src/Graph/Nodes/BinaryNode.php
BinaryNode.attachRight
public function attachRight(BinaryNode $node) : void { $node->setParent($this); $this->right = $node; }
php
public function attachRight(BinaryNode $node) : void { $node->setParent($this); $this->right = $node; }
[ "public", "function", "attachRight", "(", "BinaryNode", "$", "node", ")", ":", "void", "{", "$", "node", "->", "setParent", "(", "$", "this", ")", ";", "$", "this", "->", "right", "=", "$", "node", ";", "}" ]
Set the right child node. @param self $node
[ "Set", "the", "right", "child", "node", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L140-L145
RubixML/RubixML
src/Graph/Nodes/BinaryNode.php
BinaryNode.detachLeft
public function detachLeft() : void { if ($this->left) { $this->left->setParent(null); $this->left = null; } }
php
public function detachLeft() : void { if ($this->left) { $this->left->setParent(null); $this->left = null; } }
[ "public", "function", "detachLeft", "(", ")", ":", "void", "{", "if", "(", "$", "this", "->", "left", ")", "{", "$", "this", "->", "left", "->", "setParent", "(", "null", ")", ";", "$", "this", "->", "left", "=", "null", ";", "}", "}" ]
Detach the left child node.
[ "Detach", "the", "left", "child", "node", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L150-L157
RubixML/RubixML
src/Graph/Nodes/BinaryNode.php
BinaryNode.detachRight
public function detachRight() : void { if ($this->right) { $this->right->setParent(null); $this->right = null; } }
php
public function detachRight() : void { if ($this->right) { $this->right->setParent(null); $this->right = null; } }
[ "public", "function", "detachRight", "(", ")", ":", "void", "{", "if", "(", "$", "this", "->", "right", ")", "{", "$", "this", "->", "right", "->", "setParent", "(", "null", ")", ";", "$", "this", "->", "right", "=", "null", ";", "}", "}" ]
Detach the right child node.
[ "Detach", "the", "right", "child", "node", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L162-L169
RubixML/RubixML
src/Clusterers/KMeans.php
KMeans.train
public function train(Dataset $dataset) : void { DatasetIsCompatibleWithEstimator::check($dataset, $this); $this->centroids = $this->seeder->seed($dataset, $this->k); $sizes = array_fill(1, $this->k, 0); $sizes[0] = $dataset->numRows(); $this->sizes = $sizes; $this->steps = []; $this->partial($dataset); }
php
public function train(Dataset $dataset) : void { DatasetIsCompatibleWithEstimator::check($dataset, $this); $this->centroids = $this->seeder->seed($dataset, $this->k); $sizes = array_fill(1, $this->k, 0); $sizes[0] = $dataset->numRows(); $this->sizes = $sizes; $this->steps = []; $this->partial($dataset); }
[ "public", "function", "train", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "$", "this", "->", "centroids", "=", "$", "this", "->", "seeder", "->", "seed", "(", "$", "dataset", ",", "$", "this", "->", "k", ")", ";", "$", "sizes", "=", "array_fill", "(", "1", ",", "$", "this", "->", "k", ",", "0", ")", ";", "$", "sizes", "[", "0", "]", "=", "$", "dataset", "->", "numRows", "(", ")", ";", "$", "this", "->", "sizes", "=", "$", "sizes", ";", "$", "this", "->", "steps", "=", "[", "]", ";", "$", "this", "->", "partial", "(", "$", "dataset", ")", ";", "}" ]
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/KMeans.php#L233-L247
RubixML/RubixML
src/Clusterers/KMeans.php
KMeans.partial
public function partial(Dataset $dataset) : void { if (empty($this->centroids) or empty($this->sizes)) { $this->train($dataset); return; } DatasetIsCompatibleWithEstimator::check($dataset, $this); if ($this->logger) { $this->logger->info('Learner init ' . Params::stringify([ 'k' => $this->k, 'batch_size' => $this->batchSize, 'kernel' => $this->kernel, 'epochs' => $this->epochs, 'min_change' => $this->minChange, 'seeder' => $this->seeder, ])); } $n = $dataset->numRows(); $samples = $dataset->samples(); $labels = array_fill(0, $n, 0); $order = range(0, $n - 1); $randomize = $n > $this->batchSize ? true : false; $previous = INF; for ($epoch = 1; $epoch <= $this->epochs; $epoch++) { if ($randomize) { shuffle($order); array_multisort($order, $samples, $labels); } $sBatches = array_chunk($samples, $this->batchSize, true); $lBatches = array_chunk($labels, $this->batchSize, true); foreach ($sBatches as $i => $batch) { $assignments = array_map([self::class, 'assign'], $batch); $lHat = $lBatches[$i]; foreach ($assignments as $j => $cluster) { $expected = $lHat[$j]; if ($cluster !== $expected) { $labels[$j] = $cluster; $this->sizes[$expected]--; $this->sizes[$cluster]++; } } $strata = Labeled::quick($batch, $lHat)->stratify(); foreach ($strata as $cluster => $stratum) { $centroid = $this->centroids[$cluster]; $size = $this->sizes[$cluster]; $step = Matrix::quick($stratum->samples()) ->transpose() ->mean() ->asArray(); $weight = 1. / ($size ?: EPSILON); foreach ($centroid as $i => &$mean) { $mean = (1. - $weight) * $mean + $weight * $step[$i]; } $this->centroids[$cluster] = $centroid; } } $inertia = $this->inertia($samples); $this->steps[] = $inertia; if ($this->logger) { $this->logger->info("Epoch $epoch complete, inertia=$inertia"); } if (is_nan($inertia)) { break 1; } if (abs($previous - $inertia) < $this->minChange) { break 1; } $previous = $inertia; } if ($this->logger) { $this->logger->info('Training complete'); } }
php
public function partial(Dataset $dataset) : void { if (empty($this->centroids) or empty($this->sizes)) { $this->train($dataset); return; } DatasetIsCompatibleWithEstimator::check($dataset, $this); if ($this->logger) { $this->logger->info('Learner init ' . Params::stringify([ 'k' => $this->k, 'batch_size' => $this->batchSize, 'kernel' => $this->kernel, 'epochs' => $this->epochs, 'min_change' => $this->minChange, 'seeder' => $this->seeder, ])); } $n = $dataset->numRows(); $samples = $dataset->samples(); $labels = array_fill(0, $n, 0); $order = range(0, $n - 1); $randomize = $n > $this->batchSize ? true : false; $previous = INF; for ($epoch = 1; $epoch <= $this->epochs; $epoch++) { if ($randomize) { shuffle($order); array_multisort($order, $samples, $labels); } $sBatches = array_chunk($samples, $this->batchSize, true); $lBatches = array_chunk($labels, $this->batchSize, true); foreach ($sBatches as $i => $batch) { $assignments = array_map([self::class, 'assign'], $batch); $lHat = $lBatches[$i]; foreach ($assignments as $j => $cluster) { $expected = $lHat[$j]; if ($cluster !== $expected) { $labels[$j] = $cluster; $this->sizes[$expected]--; $this->sizes[$cluster]++; } } $strata = Labeled::quick($batch, $lHat)->stratify(); foreach ($strata as $cluster => $stratum) { $centroid = $this->centroids[$cluster]; $size = $this->sizes[$cluster]; $step = Matrix::quick($stratum->samples()) ->transpose() ->mean() ->asArray(); $weight = 1. / ($size ?: EPSILON); foreach ($centroid as $i => &$mean) { $mean = (1. - $weight) * $mean + $weight * $step[$i]; } $this->centroids[$cluster] = $centroid; } } $inertia = $this->inertia($samples); $this->steps[] = $inertia; if ($this->logger) { $this->logger->info("Epoch $epoch complete, inertia=$inertia"); } if (is_nan($inertia)) { break 1; } if (abs($previous - $inertia) < $this->minChange) { break 1; } $previous = $inertia; } if ($this->logger) { $this->logger->info('Training complete'); } }
[ "public", "function", "partial", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "if", "(", "empty", "(", "$", "this", "->", "centroids", ")", "or", "empty", "(", "$", "this", "->", "sizes", ")", ")", "{", "$", "this", "->", "train", "(", "$", "dataset", ")", ";", "return", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Learner init '", ".", "Params", "::", "stringify", "(", "[", "'k'", "=>", "$", "this", "->", "k", ",", "'batch_size'", "=>", "$", "this", "->", "batchSize", ",", "'kernel'", "=>", "$", "this", "->", "kernel", ",", "'epochs'", "=>", "$", "this", "->", "epochs", ",", "'min_change'", "=>", "$", "this", "->", "minChange", ",", "'seeder'", "=>", "$", "this", "->", "seeder", ",", "]", ")", ")", ";", "}", "$", "n", "=", "$", "dataset", "->", "numRows", "(", ")", ";", "$", "samples", "=", "$", "dataset", "->", "samples", "(", ")", ";", "$", "labels", "=", "array_fill", "(", "0", ",", "$", "n", ",", "0", ")", ";", "$", "order", "=", "range", "(", "0", ",", "$", "n", "-", "1", ")", ";", "$", "randomize", "=", "$", "n", ">", "$", "this", "->", "batchSize", "?", "true", ":", "false", ";", "$", "previous", "=", "INF", ";", "for", "(", "$", "epoch", "=", "1", ";", "$", "epoch", "<=", "$", "this", "->", "epochs", ";", "$", "epoch", "++", ")", "{", "if", "(", "$", "randomize", ")", "{", "shuffle", "(", "$", "order", ")", ";", "array_multisort", "(", "$", "order", ",", "$", "samples", ",", "$", "labels", ")", ";", "}", "$", "sBatches", "=", "array_chunk", "(", "$", "samples", ",", "$", "this", "->", "batchSize", ",", "true", ")", ";", "$", "lBatches", "=", "array_chunk", "(", "$", "labels", ",", "$", "this", "->", "batchSize", ",", "true", ")", ";", "foreach", "(", "$", "sBatches", "as", "$", "i", "=>", "$", "batch", ")", "{", "$", "assignments", "=", "array_map", "(", "[", "self", "::", "class", ",", "'assign'", "]", ",", "$", "batch", ")", ";", "$", "lHat", "=", "$", "lBatches", "[", "$", "i", "]", ";", "foreach", "(", "$", "assignments", "as", "$", "j", "=>", "$", "cluster", ")", "{", "$", "expected", "=", "$", "lHat", "[", "$", "j", "]", ";", "if", "(", "$", "cluster", "!==", "$", "expected", ")", "{", "$", "labels", "[", "$", "j", "]", "=", "$", "cluster", ";", "$", "this", "->", "sizes", "[", "$", "expected", "]", "--", ";", "$", "this", "->", "sizes", "[", "$", "cluster", "]", "++", ";", "}", "}", "$", "strata", "=", "Labeled", "::", "quick", "(", "$", "batch", ",", "$", "lHat", ")", "->", "stratify", "(", ")", ";", "foreach", "(", "$", "strata", "as", "$", "cluster", "=>", "$", "stratum", ")", "{", "$", "centroid", "=", "$", "this", "->", "centroids", "[", "$", "cluster", "]", ";", "$", "size", "=", "$", "this", "->", "sizes", "[", "$", "cluster", "]", ";", "$", "step", "=", "Matrix", "::", "quick", "(", "$", "stratum", "->", "samples", "(", ")", ")", "->", "transpose", "(", ")", "->", "mean", "(", ")", "->", "asArray", "(", ")", ";", "$", "weight", "=", "1.", "/", "(", "$", "size", "?", ":", "EPSILON", ")", ";", "foreach", "(", "$", "centroid", "as", "$", "i", "=>", "&", "$", "mean", ")", "{", "$", "mean", "=", "(", "1.", "-", "$", "weight", ")", "*", "$", "mean", "+", "$", "weight", "*", "$", "step", "[", "$", "i", "]", ";", "}", "$", "this", "->", "centroids", "[", "$", "cluster", "]", "=", "$", "centroid", ";", "}", "}", "$", "inertia", "=", "$", "this", "->", "inertia", "(", "$", "samples", ")", ";", "$", "this", "->", "steps", "[", "]", "=", "$", "inertia", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "\"Epoch $epoch complete, inertia=$inertia\"", ")", ";", "}", "if", "(", "is_nan", "(", "$", "inertia", ")", ")", "{", "break", "1", ";", "}", "if", "(", "abs", "(", "$", "previous", "-", "$", "inertia", ")", "<", "$", "this", "->", "minChange", ")", "{", "break", "1", ";", "}", "$", "previous", "=", "$", "inertia", ";", "}", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Training complete'", ")", ";", "}", "}" ]
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/Clusterers/KMeans.php#L255-L356
RubixML/RubixML
src/Clusterers/KMeans.php
KMeans.predict
public function predict(Dataset $dataset) : array { if (!$this->centroids) { throw new RuntimeException('Estimator has not been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); return array_map([self::class, 'assign'], $dataset->samples()); }
php
public function predict(Dataset $dataset) : array { if (!$this->centroids) { throw new RuntimeException('Estimator has not been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); return array_map([self::class, 'assign'], $dataset->samples()); }
[ "public", "function", "predict", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "if", "(", "!", "$", "this", "->", "centroids", ")", "{", "throw", "new", "RuntimeException", "(", "'Estimator has not been trained.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "return", "array_map", "(", "[", "self", "::", "class", ",", "'assign'", "]", ",", "$", "dataset", "->", "samples", "(", ")", ")", ";", "}" ]
Cluster the dataset by assigning a label to each sample. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException @throws \RuntimeException @return array
[ "Cluster", "the", "dataset", "by", "assigning", "a", "label", "to", "each", "sample", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/KMeans.php#L366-L375
RubixML/RubixML
src/Clusterers/KMeans.php
KMeans.inertia
protected function inertia(array $samples) : float { $inertia = 0.; foreach ($samples as $sample) { foreach ($this->centroids as $centroid) { $inertia += $this->kernel->compute($sample, $centroid); } } return $inertia; }
php
protected function inertia(array $samples) : float { $inertia = 0.; foreach ($samples as $sample) { foreach ($this->centroids as $centroid) { $inertia += $this->kernel->compute($sample, $centroid); } } return $inertia; }
[ "protected", "function", "inertia", "(", "array", "$", "samples", ")", ":", "float", "{", "$", "inertia", "=", "0.", ";", "foreach", "(", "$", "samples", "as", "$", "sample", ")", "{", "foreach", "(", "$", "this", "->", "centroids", "as", "$", "centroid", ")", "{", "$", "inertia", "+=", "$", "this", "->", "kernel", "->", "compute", "(", "$", "sample", ",", "$", "centroid", ")", ";", "}", "}", "return", "$", "inertia", ";", "}" ]
Calculate the sum of distances between all samples and their closest centroid. @param array $samples @return float
[ "Calculate", "the", "sum", "of", "distances", "between", "all", "samples", "and", "their", "closest", "centroid", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/KMeans.php#L449-L460
RubixML/RubixML
src/Other/Loggers/Screen.php
Screen.log
public function log($level, $message, array $context = []) : void { $prefix = ''; if ($this->timestamps) { $prefix .= '[' . date(self::TIMESTAMP_FORMAT) . '] '; } $prefix .= $this->channel . '.' . strtoupper((string) $level) . ': '; echo $prefix . $message . PHP_EOL; }
php
public function log($level, $message, array $context = []) : void { $prefix = ''; if ($this->timestamps) { $prefix .= '[' . date(self::TIMESTAMP_FORMAT) . '] '; } $prefix .= $this->channel . '.' . strtoupper((string) $level) . ': '; echo $prefix . $message . PHP_EOL; }
[ "public", "function", "log", "(", "$", "level", ",", "$", "message", ",", "array", "$", "context", "=", "[", "]", ")", ":", "void", "{", "$", "prefix", "=", "''", ";", "if", "(", "$", "this", "->", "timestamps", ")", "{", "$", "prefix", ".=", "'['", ".", "date", "(", "self", "::", "TIMESTAMP_FORMAT", ")", ".", "'] '", ";", "}", "$", "prefix", ".=", "$", "this", "->", "channel", ".", "'.'", ".", "strtoupper", "(", "(", "string", ")", "$", "level", ")", ".", "': '", ";", "echo", "$", "prefix", ".", "$", "message", ".", "PHP_EOL", ";", "}" ]
Logs with an arbitrary level. @param mixed $level @param string $message @param array $context
[ "Logs", "with", "an", "arbitrary", "level", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Loggers/Screen.php#L49-L60
RubixML/RubixML
src/NeuralNet/CostFunctions/LeastSquares.php
LeastSquares.compute
public function compute(Tensor $expected, Tensor $output) : float { return $output->subtract($expected)->square()->sum()->mean(); }
php
public function compute(Tensor $expected, Tensor $output) : float { return $output->subtract($expected)->square()->sum()->mean(); }
[ "public", "function", "compute", "(", "Tensor", "$", "expected", ",", "Tensor", "$", "output", ")", ":", "float", "{", "return", "$", "output", "->", "subtract", "(", "$", "expected", ")", "->", "square", "(", ")", "->", "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/LeastSquares.php#L36-L39
RubixML/RubixML
src/AnomalyDetectors/KDLOF.php
KDLOF.train
public function train(Dataset $dataset) : void { DatasetIsCompatibleWithEstimator::check($dataset, $this); $samples = $dataset->samples(); $dataset = Labeled::quick($samples, array_keys($samples)); $this->tree->grow($dataset); $this->kdistances = $this->lrds = []; $indices = $distances = []; foreach ($dataset as $sample) { [$iHat, $dHat] = $this->tree->nearest($sample, $this->k); $distances[] = $dHat; $indices[] = $iHat; $this->kdistances[] = end($dHat); } foreach ($distances as $i => $row) { $this->lrds[] = $this->localReachabilityDensity($indices[$i], $row); } $lofs = []; foreach ($dataset as $sample) { $lofs[] = $this->localOutlierFactor($sample); } $shift = Stats::percentile($lofs, 100. * $this->contamination); $this->offset = self::THRESHOLD + $shift; }
php
public function train(Dataset $dataset) : void { DatasetIsCompatibleWithEstimator::check($dataset, $this); $samples = $dataset->samples(); $dataset = Labeled::quick($samples, array_keys($samples)); $this->tree->grow($dataset); $this->kdistances = $this->lrds = []; $indices = $distances = []; foreach ($dataset as $sample) { [$iHat, $dHat] = $this->tree->nearest($sample, $this->k); $distances[] = $dHat; $indices[] = $iHat; $this->kdistances[] = end($dHat); } foreach ($distances as $i => $row) { $this->lrds[] = $this->localReachabilityDensity($indices[$i], $row); } $lofs = []; foreach ($dataset as $sample) { $lofs[] = $this->localOutlierFactor($sample); } $shift = Stats::percentile($lofs, 100. * $this->contamination); $this->offset = self::THRESHOLD + $shift; }
[ "public", "function", "train", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "$", "samples", "=", "$", "dataset", "->", "samples", "(", ")", ";", "$", "dataset", "=", "Labeled", "::", "quick", "(", "$", "samples", ",", "array_keys", "(", "$", "samples", ")", ")", ";", "$", "this", "->", "tree", "->", "grow", "(", "$", "dataset", ")", ";", "$", "this", "->", "kdistances", "=", "$", "this", "->", "lrds", "=", "[", "]", ";", "$", "indices", "=", "$", "distances", "=", "[", "]", ";", "foreach", "(", "$", "dataset", "as", "$", "sample", ")", "{", "[", "$", "iHat", ",", "$", "dHat", "]", "=", "$", "this", "->", "tree", "->", "nearest", "(", "$", "sample", ",", "$", "this", "->", "k", ")", ";", "$", "distances", "[", "]", "=", "$", "dHat", ";", "$", "indices", "[", "]", "=", "$", "iHat", ";", "$", "this", "->", "kdistances", "[", "]", "=", "end", "(", "$", "dHat", ")", ";", "}", "foreach", "(", "$", "distances", "as", "$", "i", "=>", "$", "row", ")", "{", "$", "this", "->", "lrds", "[", "]", "=", "$", "this", "->", "localReachabilityDensity", "(", "$", "indices", "[", "$", "i", "]", ",", "$", "row", ")", ";", "}", "$", "lofs", "=", "[", "]", ";", "foreach", "(", "$", "dataset", "as", "$", "sample", ")", "{", "$", "lofs", "[", "]", "=", "$", "this", "->", "localOutlierFactor", "(", "$", "sample", ")", ";", "}", "$", "shift", "=", "Stats", "::", "percentile", "(", "$", "lofs", ",", "100.", "*", "$", "this", "->", "contamination", ")", ";", "$", "this", "->", "offset", "=", "self", "::", "THRESHOLD", "+", "$", "shift", ";", "}" ]
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/KDLOF.php#L164-L200
RubixML/RubixML
src/AnomalyDetectors/KDLOF.php
KDLOF.rank
public function rank(Dataset $dataset) : array { if ($this->tree->bare()) { throw new RuntimeException('The learner has not' . ' been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); return array_map([self::class, 'localOutlierFactor'], $dataset->samples()); }
php
public function rank(Dataset $dataset) : array { if ($this->tree->bare()) { throw new RuntimeException('The learner has not' . ' been trained.'); } DatasetIsCompatibleWithEstimator::check($dataset, $this); return array_map([self::class, 'localOutlierFactor'], $dataset->samples()); }
[ "public", "function", "rank", "(", "Dataset", "$", "dataset", ")", ":", "array", "{", "if", "(", "$", "this", "->", "tree", "->", "bare", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'The learner has not'", ".", "' been trained.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "return", "array_map", "(", "[", "self", "::", "class", ",", "'localOutlierFactor'", "]", ",", "$", "dataset", "->", "samples", "(", ")", ")", ";", "}" ]
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/KDLOF.php#L223-L233
RubixML/RubixML
src/AnomalyDetectors/KDLOF.php
KDLOF.localOutlierFactor
protected function localOutlierFactor(array $sample) : float { if (empty($this->lrds)) { throw new RuntimeException('Local reachability distances have' . ' not been computed, must train estimator first.'); } [$indices, $distances] = $this->tree->nearest($sample, $this->k); $lrd = $this->localReachabilityDensity($indices, $distances); $lrds = []; foreach ($indices as $index) { $lrds[] = $this->lrds[$index]; } $ratios = []; foreach ($lrds as $lHat) { $ratios[] = $lHat / $lrd; } return Stats::mean($ratios); }
php
protected function localOutlierFactor(array $sample) : float { if (empty($this->lrds)) { throw new RuntimeException('Local reachability distances have' . ' not been computed, must train estimator first.'); } [$indices, $distances] = $this->tree->nearest($sample, $this->k); $lrd = $this->localReachabilityDensity($indices, $distances); $lrds = []; foreach ($indices as $index) { $lrds[] = $this->lrds[$index]; } $ratios = []; foreach ($lrds as $lHat) { $ratios[] = $lHat / $lrd; } return Stats::mean($ratios); }
[ "protected", "function", "localOutlierFactor", "(", "array", "$", "sample", ")", ":", "float", "{", "if", "(", "empty", "(", "$", "this", "->", "lrds", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'Local reachability distances have'", ".", "' not been computed, must train estimator first.'", ")", ";", "}", "[", "$", "indices", ",", "$", "distances", "]", "=", "$", "this", "->", "tree", "->", "nearest", "(", "$", "sample", ",", "$", "this", "->", "k", ")", ";", "$", "lrd", "=", "$", "this", "->", "localReachabilityDensity", "(", "$", "indices", ",", "$", "distances", ")", ";", "$", "lrds", "=", "[", "]", ";", "foreach", "(", "$", "indices", "as", "$", "index", ")", "{", "$", "lrds", "[", "]", "=", "$", "this", "->", "lrds", "[", "$", "index", "]", ";", "}", "$", "ratios", "=", "[", "]", ";", "foreach", "(", "$", "lrds", "as", "$", "lHat", ")", "{", "$", "ratios", "[", "]", "=", "$", "lHat", "/", "$", "lrd", ";", "}", "return", "Stats", "::", "mean", "(", "$", "ratios", ")", ";", "}" ]
Calculate the local outlier factor of a given sample. @param array $sample @throws \RuntimeException @return float
[ "Calculate", "the", "local", "outlier", "factor", "of", "a", "given", "sample", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/AnomalyDetectors/KDLOF.php#L242-L266
RubixML/RubixML
src/AnomalyDetectors/KDLOF.php
KDLOF.localReachabilityDensity
protected function localReachabilityDensity(array $indices, array $distances) : float { if (empty($this->kdistances)) { throw new RuntimeException('K distances have not been computed,' . ' must train estimator first.'); } $kdistances = []; foreach ($indices as $index) { $kdistances[] = $this->kdistances[$index]; } $rds = array_map('max', $distances, $kdistances); $mean = Stats::mean($rds); return 1. / ($mean ?: EPSILON); }
php
protected function localReachabilityDensity(array $indices, array $distances) : float { if (empty($this->kdistances)) { throw new RuntimeException('K distances have not been computed,' . ' must train estimator first.'); } $kdistances = []; foreach ($indices as $index) { $kdistances[] = $this->kdistances[$index]; } $rds = array_map('max', $distances, $kdistances); $mean = Stats::mean($rds); return 1. / ($mean ?: EPSILON); }
[ "protected", "function", "localReachabilityDensity", "(", "array", "$", "indices", ",", "array", "$", "distances", ")", ":", "float", "{", "if", "(", "empty", "(", "$", "this", "->", "kdistances", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'K distances have not been computed,'", ".", "' must train estimator first.'", ")", ";", "}", "$", "kdistances", "=", "[", "]", ";", "foreach", "(", "$", "indices", "as", "$", "index", ")", "{", "$", "kdistances", "[", "]", "=", "$", "this", "->", "kdistances", "[", "$", "index", "]", ";", "}", "$", "rds", "=", "array_map", "(", "'max'", ",", "$", "distances", ",", "$", "kdistances", ")", ";", "$", "mean", "=", "Stats", "::", "mean", "(", "$", "rds", ")", ";", "return", "1.", "/", "(", "$", "mean", "?", ":", "EPSILON", ")", ";", "}" ]
Calculate the local reachability density of a sample given its distances to its k nearest neighbors. @param array $indices @param array $distances @throws \RuntimeException @return float
[ "Calculate", "the", "local", "reachability", "density", "of", "a", "sample", "given", "its", "distances", "to", "its", "k", "nearest", "neighbors", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/AnomalyDetectors/KDLOF.php#L277-L295
RubixML/RubixML
src/Kernels/SVM/Polynomial.php
Polynomial.options
public function options() : array { return [ svm::OPT_KERNEL_TYPE => svm::KERNEL_POLY, svm::OPT_DEGREE => $this->degree, svm::OPT_GAMMA => $this->gamma, svm::OPT_COEF_ZERO => $this->coef0, ]; }
php
public function options() : array { return [ svm::OPT_KERNEL_TYPE => svm::KERNEL_POLY, svm::OPT_DEGREE => $this->degree, svm::OPT_GAMMA => $this->gamma, svm::OPT_COEF_ZERO => $this->coef0, ]; }
[ "public", "function", "options", "(", ")", ":", "array", "{", "return", "[", "svm", "::", "OPT_KERNEL_TYPE", "=>", "svm", "::", "KERNEL_POLY", ",", "svm", "::", "OPT_DEGREE", "=>", "$", "this", "->", "degree", ",", "svm", "::", "OPT_GAMMA", "=>", "$", "this", "->", "gamma", ",", "svm", "::", "OPT_COEF_ZERO", "=>", "$", "this", "->", "coef0", ",", "]", ";", "}" ]
Return the options for the libsvm runtime. @return array
[ "Return", "the", "options", "for", "the", "libsvm", "runtime", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Kernels/SVM/Polynomial.php#L71-L79
RubixML/RubixML
src/Graph/Nodes/Neighborhood.php
Neighborhood.terminate
public static function terminate(Labeled $dataset) : self { $samples = $dataset->samples(); $labels = $dataset->labels(); $min = $max = []; foreach ($dataset->columns() as $values) { $min[] = min($values); $max[] = max($values); } return new self($samples, $labels, $min, $max); }
php
public static function terminate(Labeled $dataset) : self { $samples = $dataset->samples(); $labels = $dataset->labels(); $min = $max = []; foreach ($dataset->columns() as $values) { $min[] = min($values); $max[] = max($values); } return new self($samples, $labels, $min, $max); }
[ "public", "static", "function", "terminate", "(", "Labeled", "$", "dataset", ")", ":", "self", "{", "$", "samples", "=", "$", "dataset", "->", "samples", "(", ")", ";", "$", "labels", "=", "$", "dataset", "->", "labels", "(", ")", ";", "$", "min", "=", "$", "max", "=", "[", "]", ";", "foreach", "(", "$", "dataset", "->", "columns", "(", ")", "as", "$", "values", ")", "{", "$", "min", "[", "]", "=", "min", "(", "$", "values", ")", ";", "$", "max", "[", "]", "=", "max", "(", "$", "values", ")", ";", "}", "return", "new", "self", "(", "$", "samples", ",", "$", "labels", ",", "$", "min", ",", "$", "max", ")", ";", "}" ]
Terminate a branch with a dataset. @param \Rubix\ML\Datasets\Labeled $dataset @return self
[ "Terminate", "a", "branch", "with", "a", "dataset", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/Neighborhood.php#L57-L70
RubixML/RubixML
src/PersistentModel.php
PersistentModel.load
public static function load(Persister $persister) : self { $learner = $persister->load(); if (!$learner instanceof Learner) { throw new InvalidArgumentException('Peristable must be a' . ' learner.'); } return new self($learner, $persister); }
php
public static function load(Persister $persister) : self { $learner = $persister->load(); if (!$learner instanceof Learner) { throw new InvalidArgumentException('Peristable must be a' . ' learner.'); } return new self($learner, $persister); }
[ "public", "static", "function", "load", "(", "Persister", "$", "persister", ")", ":", "self", "{", "$", "learner", "=", "$", "persister", "->", "load", "(", ")", ";", "if", "(", "!", "$", "learner", "instanceof", "Learner", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Peristable must be a'", ".", "' learner.'", ")", ";", "}", "return", "new", "self", "(", "$", "learner", ",", "$", "persister", ")", ";", "}" ]
Factory method to restore the model from persistence. @param \Rubix\ML\Persisters\Persister $persister @throws \InvalidArgumentException @return self
[ "Factory", "method", "to", "restore", "the", "model", "from", "persistence", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/PersistentModel.php#L46-L56
RubixML/RubixML
src/PersistentModel.php
PersistentModel.save
public function save() : void { if ($this->base instanceof Persistable) { $this->persister->save($this->base); if ($this->logger) { $this->logger->info('Model saved successully'); } } }
php
public function save() : void { if ($this->base instanceof Persistable) { $this->persister->save($this->base); if ($this->logger) { $this->logger->info('Model saved successully'); } } }
[ "public", "function", "save", "(", ")", ":", "void", "{", "if", "(", "$", "this", "->", "base", "instanceof", "Persistable", ")", "{", "$", "this", "->", "persister", "->", "save", "(", "$", "this", "->", "base", ")", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'Model saved successully'", ")", ";", "}", "}", "}" ]
Save the model using the user-provided persister.
[ "Save", "the", "model", "using", "the", "user", "-", "provided", "persister", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/PersistentModel.php#L157-L166
RubixML/RubixML
src/CrossValidation/Reports/ConfusionMatrix.php
ConfusionMatrix.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(array_merge($predictions, $labels)); $matrix = array_fill_keys($classes, array_fill_keys($classes, 0)); foreach ($predictions as $i => $prediction) { $matrix[$prediction][$labels[$i]]++; } return $matrix; }
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(array_merge($predictions, $labels)); $matrix = array_fill_keys($classes, array_fill_keys($classes, 0)); foreach ($predictions as $i => $prediction) { $matrix[$prediction][$labels[$i]]++; } return $matrix; }
[ "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", "(", "array_merge", "(", "$", "predictions", ",", "$", "labels", ")", ")", ";", "$", "matrix", "=", "array_fill_keys", "(", "$", "classes", ",", "array_fill_keys", "(", "$", "classes", ",", "0", ")", ")", ";", "foreach", "(", "$", "predictions", "as", "$", "i", "=>", "$", "prediction", ")", "{", "$", "matrix", "[", "$", "prediction", "]", "[", "$", "labels", "[", "$", "i", "]", "]", "++", ";", "}", "return", "$", "matrix", ";", "}" ]
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/ConfusionMatrix.php#L43-L59
RubixML/RubixML
src/NeuralNet/Layers/Dense.php
Dense.initialize
public function initialize(int $fanIn) : int { $fanOut = $this->neurons; $w = $this->weightInitializer->initialize($fanIn, $fanOut); $b = $this->biasInitializer->initialize(1, $fanOut)->columnAsVector(0); $this->weights = new MatrixParam($w); $this->biases = new VectorParam($b); return $fanOut; }
php
public function initialize(int $fanIn) : int { $fanOut = $this->neurons; $w = $this->weightInitializer->initialize($fanIn, $fanOut); $b = $this->biasInitializer->initialize(1, $fanOut)->columnAsVector(0); $this->weights = new MatrixParam($w); $this->biases = new VectorParam($b); return $fanOut; }
[ "public", "function", "initialize", "(", "int", "$", "fanIn", ")", ":", "int", "{", "$", "fanOut", "=", "$", "this", "->", "neurons", ";", "$", "w", "=", "$", "this", "->", "weightInitializer", "->", "initialize", "(", "$", "fanIn", ",", "$", "fanOut", ")", ";", "$", "b", "=", "$", "this", "->", "biasInitializer", "->", "initialize", "(", "1", ",", "$", "fanOut", ")", "->", "columnAsVector", "(", "0", ")", ";", "$", "this", "->", "weights", "=", "new", "MatrixParam", "(", "$", "w", ")", ";", "$", "this", "->", "biases", "=", "new", "VectorParam", "(", "$", "b", ")", ";", "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/Dense.php#L125-L136
RubixML/RubixML
src/NeuralNet/Layers/Dense.php
Dense.back
public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred { if (!$this->weights or !$this->biases) { throw new RuntimeException('Layer is not initialized'); } if (!$this->input) { throw new RuntimeException('Must perform forward pass before' . ' backpropagating.'); } $dOut = $prevGradient->result(); $dW = $dOut->matmul($this->input->transpose()); $dB = $dOut->sum(); $w = $this->weights->w(); $optimizer->step($this->weights, $dW); $optimizer->step($this->biases, $dB); unset($this->input); return new Deferred(function () use ($w, $dOut) { return $w->transpose()->matmul($dOut); }); }
php
public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred { if (!$this->weights or !$this->biases) { throw new RuntimeException('Layer is not initialized'); } if (!$this->input) { throw new RuntimeException('Must perform forward pass before' . ' backpropagating.'); } $dOut = $prevGradient->result(); $dW = $dOut->matmul($this->input->transpose()); $dB = $dOut->sum(); $w = $this->weights->w(); $optimizer->step($this->weights, $dW); $optimizer->step($this->biases, $dB); unset($this->input); return new Deferred(function () use ($w, $dOut) { return $w->transpose()->matmul($dOut); }); }
[ "public", "function", "back", "(", "Deferred", "$", "prevGradient", ",", "Optimizer", "$", "optimizer", ")", ":", "Deferred", "{", "if", "(", "!", "$", "this", "->", "weights", "or", "!", "$", "this", "->", "biases", ")", "{", "throw", "new", "RuntimeException", "(", "'Layer is not initialized'", ")", ";", "}", "if", "(", "!", "$", "this", "->", "input", ")", "{", "throw", "new", "RuntimeException", "(", "'Must perform forward pass before'", ".", "' backpropagating.'", ")", ";", "}", "$", "dOut", "=", "$", "prevGradient", "->", "result", "(", ")", ";", "$", "dW", "=", "$", "dOut", "->", "matmul", "(", "$", "this", "->", "input", "->", "transpose", "(", ")", ")", ";", "$", "dB", "=", "$", "dOut", "->", "sum", "(", ")", ";", "$", "w", "=", "$", "this", "->", "weights", "->", "w", "(", ")", ";", "$", "optimizer", "->", "step", "(", "$", "this", "->", "weights", ",", "$", "dW", ")", ";", "$", "optimizer", "->", "step", "(", "$", "this", "->", "biases", ",", "$", "dB", ")", ";", "unset", "(", "$", "this", "->", "input", ")", ";", "return", "new", "Deferred", "(", "function", "(", ")", "use", "(", "$", "w", ",", "$", "dOut", ")", "{", "return", "$", "w", "->", "transpose", "(", ")", "->", "matmul", "(", "$", "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/Dense.php#L182-L208
RubixML/RubixML
src/Persisters/RedisDB.php
RedisDB.save
public function save(Persistable $persistable) : void { $data = $this->serializer->serialize($persistable); $success = $this->connector->set($this->key, $data); if (!$success) { throw new RuntimeException('Failed to save persistable' . ' to the database.'); } }
php
public function save(Persistable $persistable) : void { $data = $this->serializer->serialize($persistable); $success = $this->connector->set($this->key, $data); if (!$success) { throw new RuntimeException('Failed to save persistable' . ' to the database.'); } }
[ "public", "function", "save", "(", "Persistable", "$", "persistable", ")", ":", "void", "{", "$", "data", "=", "$", "this", "->", "serializer", "->", "serialize", "(", "$", "persistable", ")", ";", "$", "success", "=", "$", "this", "->", "connector", "->", "set", "(", "$", "this", "->", "key", ",", "$", "data", ")", ";", "if", "(", "!", "$", "success", ")", "{", "throw", "new", "RuntimeException", "(", "'Failed to save persistable'", ".", "' to the database.'", ")", ";", "}", "}" ]
Save the persitable object. @param \Rubix\ML\Persistable $persistable @throws \RuntimeException
[ "Save", "the", "persitable", "object", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Persisters/RedisDB.php#L116-L126
RubixML/RubixML
src/Persisters/RedisDB.php
RedisDB.load
public function load() : Persistable { $data = $this->connector->get($this->key) ?: ''; $persistable = $this->serializer->unserialize($data); if (!$persistable instanceof Persistable) { throw new RuntimeException('Persistable could not be' . ' reconstituted.'); } return $persistable; }
php
public function load() : Persistable { $data = $this->connector->get($this->key) ?: ''; $persistable = $this->serializer->unserialize($data); if (!$persistable instanceof Persistable) { throw new RuntimeException('Persistable could not be' . ' reconstituted.'); } return $persistable; }
[ "public", "function", "load", "(", ")", ":", "Persistable", "{", "$", "data", "=", "$", "this", "->", "connector", "->", "get", "(", "$", "this", "->", "key", ")", "?", ":", "''", ";", "$", "persistable", "=", "$", "this", "->", "serializer", "->", "unserialize", "(", "$", "data", ")", ";", "if", "(", "!", "$", "persistable", "instanceof", "Persistable", ")", "{", "throw", "new", "RuntimeException", "(", "'Persistable could not be'", ".", "' reconstituted.'", ")", ";", "}", "return", "$", "persistable", ";", "}" ]
Load the last model that was saved. @throws \RuntimeException @return \Rubix\ML\Persistable
[ "Load", "the", "last", "model", "that", "was", "saved", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Persisters/RedisDB.php#L134-L146
RubixML/RubixML
src/Other/Strategies/WildGuess.php
WildGuess.fit
public function fit(array $values) : void { if (empty($values)) { throw new InvalidArgumentException('Strategy must be fit with' . ' at least 1 value.'); } $this->min = min($values); $this->max = max($values); }
php
public function fit(array $values) : void { if (empty($values)) { throw new InvalidArgumentException('Strategy must be fit with' . ' at least 1 value.'); } $this->min = min($values); $this->max = max($values); }
[ "public", "function", "fit", "(", "array", "$", "values", ")", ":", "void", "{", "if", "(", "empty", "(", "$", "values", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Strategy must be fit with'", ".", "' at least 1 value.'", ")", ";", "}", "$", "this", "->", "min", "=", "min", "(", "$", "values", ")", ";", "$", "this", "->", "max", "=", "max", "(", "$", "values", ")", ";", "}" ]
Fit the guessing strategy to a set of values. @param array $values @throws \InvalidArgumentException
[ "Fit", "the", "guessing", "strategy", "to", "a", "set", "of", "values", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Strategies/WildGuess.php#L62-L71
RubixML/RubixML
src/Other/Strategies/WildGuess.php
WildGuess.guess
public function guess() : float { if ($this->min === null or $this->max === null) { throw new RuntimeException('Strategy has not been fitted.'); } $min = (int) round($this->min * $this->precision); $max = (int) round($this->max * $this->precision); return rand($min, $max) / $this->precision; }
php
public function guess() : float { if ($this->min === null or $this->max === null) { throw new RuntimeException('Strategy has not been fitted.'); } $min = (int) round($this->min * $this->precision); $max = (int) round($this->max * $this->precision); return rand($min, $max) / $this->precision; }
[ "public", "function", "guess", "(", ")", ":", "float", "{", "if", "(", "$", "this", "->", "min", "===", "null", "or", "$", "this", "->", "max", "===", "null", ")", "{", "throw", "new", "RuntimeException", "(", "'Strategy has not been fitted.'", ")", ";", "}", "$", "min", "=", "(", "int", ")", "round", "(", "$", "this", "->", "min", "*", "$", "this", "->", "precision", ")", ";", "$", "max", "=", "(", "int", ")", "round", "(", "$", "this", "->", "max", "*", "$", "this", "->", "precision", ")", ";", "return", "rand", "(", "$", "min", ",", "$", "max", ")", "/", "$", "this", "->", "precision", ";", "}" ]
Make a continuous guess. @throws \RuntimeException @return float
[ "Make", "a", "continuous", "guess", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Strategies/WildGuess.php#L79-L89
RubixML/RubixML
src/CrossValidation/Metrics/MCC.php
MCC.mcc
public static function mcc(int $tp, int $tn, int $fp, int $fn) : float { return ($tp * $tn - $fp * $fn) / (sqrt(($tp + $fp) * ($tp + $fn) * ($tn + $fp) * ($tn + $fn)) ?: EPSILON); }
php
public static function mcc(int $tp, int $tn, int $fp, int $fn) : float { return ($tp * $tn - $fp * $fn) / (sqrt(($tp + $fp) * ($tp + $fn) * ($tn + $fp) * ($tn + $fn)) ?: EPSILON); }
[ "public", "static", "function", "mcc", "(", "int", "$", "tp", ",", "int", "$", "tn", ",", "int", "$", "fp", ",", "int", "$", "fn", ")", ":", "float", "{", "return", "(", "$", "tp", "*", "$", "tn", "-", "$", "fp", "*", "$", "fn", ")", "/", "(", "sqrt", "(", "(", "$", "tp", "+", "$", "fp", ")", "*", "(", "$", "tp", "+", "$", "fn", ")", "*", "(", "$", "tn", "+", "$", "fp", ")", "*", "(", "$", "tn", "+", "$", "fn", ")", ")", "?", ":", "EPSILON", ")", ";", "}" ]
Compute the class mcc score. @param int $tp @param int $tn @param int $fp @param int $fn @return float
[ "Compute", "the", "class", "mcc", "score", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CrossValidation/Metrics/MCC.php#L42-L47
RubixML/RubixML
src/CrossValidation/Metrics/MCC.php
MCC.score
public function score(array $predictions, array $labels) : float { if (empty($predictions)) { return 0.; } if (count($predictions) !== count($labels)) { throw new InvalidArgumentException('The number of labels' . ' must equal the number of predictions.'); } $classes = array_unique(array_merge($predictions, $labels)); $truePos = $trueNeg = $falsePos = $falseNeg = array_fill_keys($classes, 0); foreach ($predictions as $i => $prediction) { $label = $labels[$i]; if ($prediction === $label) { $truePos[$prediction]++; foreach ($classes as $class) { if ($class !== $prediction) { $trueNeg[$class]++; } } } else { $falsePos[$prediction]++; $falseNeg[$label]++; } } return Stats::mean( array_map([$this, 'mcc'], $truePos, $trueNeg, $falsePos, $falseNeg) ); }
php
public function score(array $predictions, array $labels) : float { if (empty($predictions)) { return 0.; } if (count($predictions) !== count($labels)) { throw new InvalidArgumentException('The number of labels' . ' must equal the number of predictions.'); } $classes = array_unique(array_merge($predictions, $labels)); $truePos = $trueNeg = $falsePos = $falseNeg = array_fill_keys($classes, 0); foreach ($predictions as $i => $prediction) { $label = $labels[$i]; if ($prediction === $label) { $truePos[$prediction]++; foreach ($classes as $class) { if ($class !== $prediction) { $trueNeg[$class]++; } } } else { $falsePos[$prediction]++; $falseNeg[$label]++; } } return Stats::mean( array_map([$this, 'mcc'], $truePos, $trueNeg, $falsePos, $falseNeg) ); }
[ "public", "function", "score", "(", "array", "$", "predictions", ",", "array", "$", "labels", ")", ":", "float", "{", "if", "(", "empty", "(", "$", "predictions", ")", ")", "{", "return", "0.", ";", "}", "if", "(", "count", "(", "$", "predictions", ")", "!==", "count", "(", "$", "labels", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The number of labels'", ".", "' must equal the number of predictions.'", ")", ";", "}", "$", "classes", "=", "array_unique", "(", "array_merge", "(", "$", "predictions", ",", "$", "labels", ")", ")", ";", "$", "truePos", "=", "$", "trueNeg", "=", "$", "falsePos", "=", "$", "falseNeg", "=", "array_fill_keys", "(", "$", "classes", ",", "0", ")", ";", "foreach", "(", "$", "predictions", "as", "$", "i", "=>", "$", "prediction", ")", "{", "$", "label", "=", "$", "labels", "[", "$", "i", "]", ";", "if", "(", "$", "prediction", "===", "$", "label", ")", "{", "$", "truePos", "[", "$", "prediction", "]", "++", ";", "foreach", "(", "$", "classes", "as", "$", "class", ")", "{", "if", "(", "$", "class", "!==", "$", "prediction", ")", "{", "$", "trueNeg", "[", "$", "class", "]", "++", ";", "}", "}", "}", "else", "{", "$", "falsePos", "[", "$", "prediction", "]", "++", ";", "$", "falseNeg", "[", "$", "label", "]", "++", ";", "}", "}", "return", "Stats", "::", "mean", "(", "array_map", "(", "[", "$", "this", ",", "'mcc'", "]", ",", "$", "truePos", ",", "$", "trueNeg", ",", "$", "falsePos", ",", "$", "falseNeg", ")", ")", ";", "}" ]
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/MCC.php#L80-L115
RubixML/RubixML
src/Regressors/Ridge.php
Ridge.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); $samples = $dataset->samples(); $labels = $dataset->labels(); $biases = Matrix::ones($dataset->numRows(), 1); $x = Matrix::build($samples)->augmentLeft($biases); $y = Vector::build($labels); $alphas = array_fill(0, $x->n() - 1, $this->alpha); $penalty = Matrix::diagonal(array_merge([0.], $alphas)); $xT = $x->transpose(); $coefficients = $xT->matmul($x) ->add($penalty) ->inverse() ->dot($xT->dot($y)) ->asArray(); $this->bias = (float) array_shift($coefficients); $this->weights = Vector::quick($coefficients); }
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); $samples = $dataset->samples(); $labels = $dataset->labels(); $biases = Matrix::ones($dataset->numRows(), 1); $x = Matrix::build($samples)->augmentLeft($biases); $y = Vector::build($labels); $alphas = array_fill(0, $x->n() - 1, $this->alpha); $penalty = Matrix::diagonal(array_merge([0.], $alphas)); $xT = $x->transpose(); $coefficients = $xT->matmul($x) ->add($penalty) ->inverse() ->dot($xT->dot($y)) ->asArray(); $this->bias = (float) array_shift($coefficients); $this->weights = Vector::quick($coefficients); }
[ "public", "function", "train", "(", "Dataset", "$", "dataset", ")", ":", "void", "{", "if", "(", "!", "$", "dataset", "instanceof", "Labeled", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'This estimator requires a'", ".", "' labeled training set.'", ")", ";", "}", "DatasetIsCompatibleWithEstimator", "::", "check", "(", "$", "dataset", ",", "$", "this", ")", ";", "$", "samples", "=", "$", "dataset", "->", "samples", "(", ")", ";", "$", "labels", "=", "$", "dataset", "->", "labels", "(", ")", ";", "$", "biases", "=", "Matrix", "::", "ones", "(", "$", "dataset", "->", "numRows", "(", ")", ",", "1", ")", ";", "$", "x", "=", "Matrix", "::", "build", "(", "$", "samples", ")", "->", "augmentLeft", "(", "$", "biases", ")", ";", "$", "y", "=", "Vector", "::", "build", "(", "$", "labels", ")", ";", "$", "alphas", "=", "array_fill", "(", "0", ",", "$", "x", "->", "n", "(", ")", "-", "1", ",", "$", "this", "->", "alpha", ")", ";", "$", "penalty", "=", "Matrix", "::", "diagonal", "(", "array_merge", "(", "[", "0.", "]", ",", "$", "alphas", ")", ")", ";", "$", "xT", "=", "$", "x", "->", "transpose", "(", ")", ";", "$", "coefficients", "=", "$", "xT", "->", "matmul", "(", "$", "x", ")", "->", "add", "(", "$", "penalty", ")", "->", "inverse", "(", ")", "->", "dot", "(", "$", "xT", "->", "dot", "(", "$", "y", ")", ")", "->", "asArray", "(", ")", ";", "$", "this", "->", "bias", "=", "(", "float", ")", "array_shift", "(", "$", "coefficients", ")", ";", "$", "this", "->", "weights", "=", "Vector", "::", "quick", "(", "$", "coefficients", ")", ";", "}" ]
Calculate the coefficients of the training data. i.e. compute the line that best fits the training data. @param \Rubix\ML\Datasets\Dataset $dataset @throws \InvalidArgumentException
[ "Calculate", "the", "coefficients", "of", "the", "training", "data", ".", "i", ".", "e", ".", "compute", "the", "line", "that", "best", "fits", "the", "training", "data", "." ]
train
https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/Ridge.php#L124-L155