repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
eyecatchup/SEOstats | SEOstats/Helper/Url.php | Url.isRfc | public static function isRfc($url)
{
if(isset($url) && 1 < strlen($url)) {
$host = self::parseHost($url);
$scheme = strtolower(parse_url($url, PHP_URL_SCHEME));
if (false !== $host && ($scheme == 'http' || $scheme == 'https')) {
$pattern = '([A-Za-z][A-Za-z0-9+.-]{1,120}:[A-Za-z0-9/](([A-Za-z0-9$_.+!*,;/?:@&~=-])';
$pattern .= '|%[A-Fa-f0-9]{2}){1,333}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*,;/?:@&~=%-]{0,1000}))?)';
return (bool) preg_match($pattern, $url);
}
}
return false;
} | php | public static function isRfc($url)
{
if(isset($url) && 1 < strlen($url)) {
$host = self::parseHost($url);
$scheme = strtolower(parse_url($url, PHP_URL_SCHEME));
if (false !== $host && ($scheme == 'http' || $scheme == 'https')) {
$pattern = '([A-Za-z][A-Za-z0-9+.-]{1,120}:[A-Za-z0-9/](([A-Za-z0-9$_.+!*,;/?:@&~=-])';
$pattern .= '|%[A-Fa-f0-9]{2}){1,333}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*,;/?:@&~=%-]{0,1000}))?)';
return (bool) preg_match($pattern, $url);
}
}
return false;
} | [
"public",
"static",
"function",
"isRfc",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"url",
")",
"&&",
"1",
"<",
"strlen",
"(",
"$",
"url",
")",
")",
"{",
"$",
"host",
"=",
"self",
"::",
"parseHost",
"(",
"$",
"url",
")",
";",
"$",
"scheme",
"=",
"strtolower",
"(",
"parse_url",
"(",
"$",
"url",
",",
"PHP_URL_SCHEME",
")",
")",
";",
"if",
"(",
"false",
"!==",
"$",
"host",
"&&",
"(",
"$",
"scheme",
"==",
"'http'",
"||",
"$",
"scheme",
"==",
"'https'",
")",
")",
"{",
"$",
"pattern",
"=",
"'([A-Za-z][A-Za-z0-9+.-]{1,120}:[A-Za-z0-9/](([A-Za-z0-9$_.+!*,;/?:@&~=-])'",
";",
"$",
"pattern",
".=",
"'|%[A-Fa-f0-9]{2}){1,333}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*,;/?:@&~=%-]{0,1000}))?)'",
";",
"return",
"(",
"bool",
")",
"preg_match",
"(",
"$",
"pattern",
",",
"$",
"url",
")",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Validates the initialized object URL syntax.
@access private
@param string $url String, containing the initialized object URL.
@return string Returns string, containing the validation result. | [
"Validates",
"the",
"initialized",
"object",
"URL",
"syntax",
"."
] | bd3117f3ee10d6bf3c3cadd0461c15b91b15428b | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Helper/Url.php#L29-L41 | train |
eyecatchup/SEOstats | SEOstats/Services/3rdparty/JSON.php | Services_JSON.utf162utf8 | function utf162utf8($utf16)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
switch(true) {
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
// ignoring UTF-32 for now, sorry
return '';
} | php | function utf162utf8($utf16)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
switch(true) {
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
// ignoring UTF-32 for now, sorry
return '';
} | [
"function",
"utf162utf8",
"(",
"$",
"utf16",
")",
"{",
"// oh please oh please oh please oh please oh please",
"if",
"(",
"function_exists",
"(",
"'mb_convert_encoding'",
")",
")",
"{",
"return",
"mb_convert_encoding",
"(",
"$",
"utf16",
",",
"'UTF-8'",
",",
"'UTF-16'",
")",
";",
"}",
"$",
"bytes",
"=",
"(",
"ord",
"(",
"$",
"utf16",
"{",
"0",
"}",
")",
"<<",
"8",
")",
"|",
"ord",
"(",
"$",
"utf16",
"{",
"1",
"}",
")",
";",
"switch",
"(",
"true",
")",
"{",
"case",
"(",
"(",
"0x7F",
"&",
"$",
"bytes",
")",
"==",
"$",
"bytes",
")",
":",
"// this case should never be reached, because we are in ASCII range",
"// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8",
"return",
"chr",
"(",
"0x7F",
"&",
"$",
"bytes",
")",
";",
"case",
"(",
"0x07FF",
"&",
"$",
"bytes",
")",
"==",
"$",
"bytes",
":",
"// return a 2-byte UTF-8 character",
"// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8",
"return",
"chr",
"(",
"0xC0",
"|",
"(",
"(",
"$",
"bytes",
">>",
"6",
")",
"&",
"0x1F",
")",
")",
".",
"chr",
"(",
"0x80",
"|",
"(",
"$",
"bytes",
"&",
"0x3F",
")",
")",
";",
"case",
"(",
"0xFFFF",
"&",
"$",
"bytes",
")",
"==",
"$",
"bytes",
":",
"// return a 3-byte UTF-8 character",
"// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8",
"return",
"chr",
"(",
"0xE0",
"|",
"(",
"(",
"$",
"bytes",
">>",
"12",
")",
"&",
"0x0F",
")",
")",
".",
"chr",
"(",
"0x80",
"|",
"(",
"(",
"$",
"bytes",
">>",
"6",
")",
"&",
"0x3F",
")",
")",
".",
"chr",
"(",
"0x80",
"|",
"(",
"$",
"bytes",
"&",
"0x3F",
")",
")",
";",
"}",
"// ignoring UTF-32 for now, sorry",
"return",
"''",
";",
"}"
] | convert a string from one UTF-16 char to one UTF-8 char
Normally should be handled by mb_convert_encoding, but
provides a slower PHP-only method for installations
that lack the multibye string extension.
@param string $utf16 UTF-16 character
@return string UTF-8 character
@access private | [
"convert",
"a",
"string",
"from",
"one",
"UTF",
"-",
"16",
"char",
"to",
"one",
"UTF",
"-",
"8",
"char"
] | bd3117f3ee10d6bf3c3cadd0461c15b91b15428b | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Services/3rdparty/JSON.php#L149-L180 | train |
eyecatchup/SEOstats | SEOstats/Helper/Json.php | Json.decode | public static function decode($str, $assoc = false)
{
if (!function_exists('json_decode')) {
$j = self::getJsonService();
return $j->decode($str);
}
else {
return $assoc ? json_decode($str, true) : json_decode($str);
}
} | php | public static function decode($str, $assoc = false)
{
if (!function_exists('json_decode')) {
$j = self::getJsonService();
return $j->decode($str);
}
else {
return $assoc ? json_decode($str, true) : json_decode($str);
}
} | [
"public",
"static",
"function",
"decode",
"(",
"$",
"str",
",",
"$",
"assoc",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"function_exists",
"(",
"'json_decode'",
")",
")",
"{",
"$",
"j",
"=",
"self",
"::",
"getJsonService",
"(",
")",
";",
"return",
"$",
"j",
"->",
"decode",
"(",
"$",
"str",
")",
";",
"}",
"else",
"{",
"return",
"$",
"assoc",
"?",
"json_decode",
"(",
"$",
"str",
",",
"true",
")",
":",
"json_decode",
"(",
"$",
"str",
")",
";",
"}",
"}"
] | Decodes a JSON string into appropriate variable.
@param string $str JSON-formatted string
@param boolean $accos When true, returned objects will be converted into associative arrays.
@return mixed number, boolean, string, array, or object corresponding to given JSON input string.
Note that decode() always returns strings in ASCII or UTF-8 format! | [
"Decodes",
"a",
"JSON",
"string",
"into",
"appropriate",
"variable",
"."
] | bd3117f3ee10d6bf3c3cadd0461c15b91b15428b | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Helper/Json.php#L24-L33 | train |
eyecatchup/SEOstats | SEOstats/Services/Google.php | Google.getPageRank | public static function getPageRank($url = false)
{
// Composer autoloads classes out of the SEOstats namespace.
// The custom autolader, however, does not. So we need to include it first.
if(!class_exists('\GTB_PageRank')) {
require_once realpath(__DIR__ . '/3rdparty/GTB_PageRank.php');
}
$gtb = new \GTB_PageRank(parent::getUrl($url));
$result = $gtb->getPageRank();
return $result != "" ? $result : static::noDataDefaultValue();
} | php | public static function getPageRank($url = false)
{
// Composer autoloads classes out of the SEOstats namespace.
// The custom autolader, however, does not. So we need to include it first.
if(!class_exists('\GTB_PageRank')) {
require_once realpath(__DIR__ . '/3rdparty/GTB_PageRank.php');
}
$gtb = new \GTB_PageRank(parent::getUrl($url));
$result = $gtb->getPageRank();
return $result != "" ? $result : static::noDataDefaultValue();
} | [
"public",
"static",
"function",
"getPageRank",
"(",
"$",
"url",
"=",
"false",
")",
"{",
"// Composer autoloads classes out of the SEOstats namespace.",
"// The custom autolader, however, does not. So we need to include it first.",
"if",
"(",
"!",
"class_exists",
"(",
"'\\GTB_PageRank'",
")",
")",
"{",
"require_once",
"realpath",
"(",
"__DIR__",
".",
"'/3rdparty/GTB_PageRank.php'",
")",
";",
"}",
"$",
"gtb",
"=",
"new",
"\\",
"GTB_PageRank",
"(",
"parent",
"::",
"getUrl",
"(",
"$",
"url",
")",
")",
";",
"$",
"result",
"=",
"$",
"gtb",
"->",
"getPageRank",
"(",
")",
";",
"return",
"$",
"result",
"!=",
"\"\"",
"?",
"$",
"result",
":",
"static",
"::",
"noDataDefaultValue",
"(",
")",
";",
"}"
] | Gets the Google Pagerank
@param string $url String, containing the query URL.
@return integer Returns the Google PageRank. | [
"Gets",
"the",
"Google",
"Pagerank"
] | bd3117f3ee10d6bf3c3cadd0461c15b91b15428b | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Services/Google.php#L27-L39 | train |
eyecatchup/SEOstats | SEOstats/Services/Google.php | Google.getSearchResultsTotal | public static function getSearchResultsTotal($url = false)
{
$url = parent::getUrl($url);
$url = sprintf(Config\Services::GOOGLE_APISEARCH_URL, 1, $url);
$ret = static::_getPage($url);
$obj = Helper\Json::decode($ret);
return !isset($obj->responseData->cursor->estimatedResultCount)
? parent::noDataDefaultValue()
: intval($obj->responseData->cursor->estimatedResultCount);
} | php | public static function getSearchResultsTotal($url = false)
{
$url = parent::getUrl($url);
$url = sprintf(Config\Services::GOOGLE_APISEARCH_URL, 1, $url);
$ret = static::_getPage($url);
$obj = Helper\Json::decode($ret);
return !isset($obj->responseData->cursor->estimatedResultCount)
? parent::noDataDefaultValue()
: intval($obj->responseData->cursor->estimatedResultCount);
} | [
"public",
"static",
"function",
"getSearchResultsTotal",
"(",
"$",
"url",
"=",
"false",
")",
"{",
"$",
"url",
"=",
"parent",
"::",
"getUrl",
"(",
"$",
"url",
")",
";",
"$",
"url",
"=",
"sprintf",
"(",
"Config",
"\\",
"Services",
"::",
"GOOGLE_APISEARCH_URL",
",",
"1",
",",
"$",
"url",
")",
";",
"$",
"ret",
"=",
"static",
"::",
"_getPage",
"(",
"$",
"url",
")",
";",
"$",
"obj",
"=",
"Helper",
"\\",
"Json",
"::",
"decode",
"(",
"$",
"ret",
")",
";",
"return",
"!",
"isset",
"(",
"$",
"obj",
"->",
"responseData",
"->",
"cursor",
"->",
"estimatedResultCount",
")",
"?",
"parent",
"::",
"noDataDefaultValue",
"(",
")",
":",
"intval",
"(",
"$",
"obj",
"->",
"responseData",
"->",
"cursor",
"->",
"estimatedResultCount",
")",
";",
"}"
] | Returns total amount of results for any Google search,
requesting the deprecated Websearch API.
@param string $url String, containing the query URL.
@return integer Returns the total search result count. | [
"Returns",
"total",
"amount",
"of",
"results",
"for",
"any",
"Google",
"search",
"requesting",
"the",
"deprecated",
"Websearch",
"API",
"."
] | bd3117f3ee10d6bf3c3cadd0461c15b91b15428b | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Services/Google.php#L76-L87 | train |
eyecatchup/SEOstats | SEOstats/Services/Sistrix.php | Sistrix.getVisibilityIndex | public static function getVisibilityIndex($url = false)
{
$url = parent::getUrl($url);
$domain = Helper\Url::parseHost($url);
$dataUrl = sprintf(Config\Services::SISTRIX_VI_URL, urlencode($domain));
$html = static::_getPage($dataUrl);
@preg_match_all('#<h3>(.*?)<\/h3>#si', $html, $matches);
return isset($matches[1][0]) ? $matches[1][0] : parent::noDataDefaultValue();
} | php | public static function getVisibilityIndex($url = false)
{
$url = parent::getUrl($url);
$domain = Helper\Url::parseHost($url);
$dataUrl = sprintf(Config\Services::SISTRIX_VI_URL, urlencode($domain));
$html = static::_getPage($dataUrl);
@preg_match_all('#<h3>(.*?)<\/h3>#si', $html, $matches);
return isset($matches[1][0]) ? $matches[1][0] : parent::noDataDefaultValue();
} | [
"public",
"static",
"function",
"getVisibilityIndex",
"(",
"$",
"url",
"=",
"false",
")",
"{",
"$",
"url",
"=",
"parent",
"::",
"getUrl",
"(",
"$",
"url",
")",
";",
"$",
"domain",
"=",
"Helper",
"\\",
"Url",
"::",
"parseHost",
"(",
"$",
"url",
")",
";",
"$",
"dataUrl",
"=",
"sprintf",
"(",
"Config",
"\\",
"Services",
"::",
"SISTRIX_VI_URL",
",",
"urlencode",
"(",
"$",
"domain",
")",
")",
";",
"$",
"html",
"=",
"static",
"::",
"_getPage",
"(",
"$",
"dataUrl",
")",
";",
"@",
"preg_match_all",
"(",
"'#<h3>(.*?)<\\/h3>#si'",
",",
"$",
"html",
",",
"$",
"matches",
")",
";",
"return",
"isset",
"(",
"$",
"matches",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"?",
"$",
"matches",
"[",
"1",
"]",
"[",
"0",
"]",
":",
"parent",
"::",
"noDataDefaultValue",
"(",
")",
";",
"}"
] | Returns the Sistrix visibility index
@access public
@param url string The URL to check.
@return integer Returns the Sistrix visibility index.
@link http://www.sistrix.com/blog/870-sistrix-visibilityindex.html | [
"Returns",
"the",
"Sistrix",
"visibility",
"index"
] | bd3117f3ee10d6bf3c3cadd0461c15b91b15428b | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Services/Sistrix.php#L43-L53 | train |
eyecatchup/SEOstats | SEOstats/Services/Sistrix.php | Sistrix.getVisibilityIndexByApi | public static function getVisibilityIndexByApi($url = false, $db = false)
{
self::guardApiKey();
self::guardApiCredits();
$url = parent::getUrl($url);
$domain = static::getDomainFromUrl($url);
$database = static::getValidDatabase($db);
$dataUrl = sprintf(Config\Services::SISTRIX_API_VI_URL, Config\ApiKeys::getSistrixApiAccessKey(), urlencode($domain), $database);
$json = static::_getPage($dataUrl);
if(empty($json)) {
return parent::noDataDefaultValue();
}
$json_decoded = (Helper\Json::decode($json, true));
if (!isset($json_decoded['answer'][0]['sichtbarkeitsindex'][0]['value'])) {
return parent::noDataDefaultValue();
}
return $json_decoded['answer'][0]['sichtbarkeitsindex'][0]['value'];
} | php | public static function getVisibilityIndexByApi($url = false, $db = false)
{
self::guardApiKey();
self::guardApiCredits();
$url = parent::getUrl($url);
$domain = static::getDomainFromUrl($url);
$database = static::getValidDatabase($db);
$dataUrl = sprintf(Config\Services::SISTRIX_API_VI_URL, Config\ApiKeys::getSistrixApiAccessKey(), urlencode($domain), $database);
$json = static::_getPage($dataUrl);
if(empty($json)) {
return parent::noDataDefaultValue();
}
$json_decoded = (Helper\Json::decode($json, true));
if (!isset($json_decoded['answer'][0]['sichtbarkeitsindex'][0]['value'])) {
return parent::noDataDefaultValue();
}
return $json_decoded['answer'][0]['sichtbarkeitsindex'][0]['value'];
} | [
"public",
"static",
"function",
"getVisibilityIndexByApi",
"(",
"$",
"url",
"=",
"false",
",",
"$",
"db",
"=",
"false",
")",
"{",
"self",
"::",
"guardApiKey",
"(",
")",
";",
"self",
"::",
"guardApiCredits",
"(",
")",
";",
"$",
"url",
"=",
"parent",
"::",
"getUrl",
"(",
"$",
"url",
")",
";",
"$",
"domain",
"=",
"static",
"::",
"getDomainFromUrl",
"(",
"$",
"url",
")",
";",
"$",
"database",
"=",
"static",
"::",
"getValidDatabase",
"(",
"$",
"db",
")",
";",
"$",
"dataUrl",
"=",
"sprintf",
"(",
"Config",
"\\",
"Services",
"::",
"SISTRIX_API_VI_URL",
",",
"Config",
"\\",
"ApiKeys",
"::",
"getSistrixApiAccessKey",
"(",
")",
",",
"urlencode",
"(",
"$",
"domain",
")",
",",
"$",
"database",
")",
";",
"$",
"json",
"=",
"static",
"::",
"_getPage",
"(",
"$",
"dataUrl",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"json",
")",
")",
"{",
"return",
"parent",
"::",
"noDataDefaultValue",
"(",
")",
";",
"}",
"$",
"json_decoded",
"=",
"(",
"Helper",
"\\",
"Json",
"::",
"decode",
"(",
"$",
"json",
",",
"true",
")",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"json_decoded",
"[",
"'answer'",
"]",
"[",
"0",
"]",
"[",
"'sichtbarkeitsindex'",
"]",
"[",
"0",
"]",
"[",
"'value'",
"]",
")",
")",
"{",
"return",
"parent",
"::",
"noDataDefaultValue",
"(",
")",
";",
"}",
"return",
"$",
"json_decoded",
"[",
"'answer'",
"]",
"[",
"0",
"]",
"[",
"'sichtbarkeitsindex'",
"]",
"[",
"0",
"]",
"[",
"'value'",
"]",
";",
"}"
] | Returns the Sistrix visibility index by using the SISTRIX API
@access public
@param url string The URL to check.
@return integer Returns the Sistrix visibility index.
@link http://www.sistrix.com/blog/870-sistrix-visibilityindex.html | [
"Returns",
"the",
"Sistrix",
"visibility",
"index",
"by",
"using",
"the",
"SISTRIX",
"API"
] | bd3117f3ee10d6bf3c3cadd0461c15b91b15428b | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Services/Sistrix.php#L63-L85 | train |
eyecatchup/SEOstats | SEOstats/Helper/HttpRequest.php | HttpRequest.getHttpCode | public static function getHttpCode($url)
{
$ua = self::getUserAgent();
$curlopt_proxy = self::getProxy();
$curlopt_proxyuserpwd = self::getProxyUserPwd();
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_USERAGENT => $ua,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_MAXREDIRS => 2,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_NOBODY => 1,
));
if($curlopt_proxy) {
curl_setopt($ch, CURLOPT_PROXY, $curlopt_proxy);
}
if($curlopt_proxyuserpwd) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $curlopt_proxyuserpwd);
}
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return (int)$httpCode;
} | php | public static function getHttpCode($url)
{
$ua = self::getUserAgent();
$curlopt_proxy = self::getProxy();
$curlopt_proxyuserpwd = self::getProxyUserPwd();
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_USERAGENT => $ua,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_MAXREDIRS => 2,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_NOBODY => 1,
));
if($curlopt_proxy) {
curl_setopt($ch, CURLOPT_PROXY, $curlopt_proxy);
}
if($curlopt_proxyuserpwd) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $curlopt_proxyuserpwd);
}
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return (int)$httpCode;
} | [
"public",
"static",
"function",
"getHttpCode",
"(",
"$",
"url",
")",
"{",
"$",
"ua",
"=",
"self",
"::",
"getUserAgent",
"(",
")",
";",
"$",
"curlopt_proxy",
"=",
"self",
"::",
"getProxy",
"(",
")",
";",
"$",
"curlopt_proxyuserpwd",
"=",
"self",
"::",
"getProxyUserPwd",
"(",
")",
";",
"$",
"ch",
"=",
"curl_init",
"(",
"$",
"url",
")",
";",
"curl_setopt_array",
"(",
"$",
"ch",
",",
"array",
"(",
"CURLOPT_USERAGENT",
"=>",
"$",
"ua",
",",
"CURLOPT_RETURNTRANSFER",
"=>",
"1",
",",
"CURLOPT_CONNECTTIMEOUT",
"=>",
"10",
",",
"CURLOPT_FOLLOWLOCATION",
"=>",
"1",
",",
"CURLOPT_MAXREDIRS",
"=>",
"2",
",",
"CURLOPT_SSL_VERIFYPEER",
"=>",
"0",
",",
"CURLOPT_NOBODY",
"=>",
"1",
",",
")",
")",
";",
"if",
"(",
"$",
"curlopt_proxy",
")",
"{",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_PROXY",
",",
"$",
"curlopt_proxy",
")",
";",
"}",
"if",
"(",
"$",
"curlopt_proxyuserpwd",
")",
"{",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_PROXYUSERPWD",
",",
"$",
"curlopt_proxyuserpwd",
")",
";",
"}",
"curl_exec",
"(",
"$",
"ch",
")",
";",
"$",
"httpCode",
"=",
"curl_getinfo",
"(",
"$",
"ch",
",",
"CURLINFO_HTTP_CODE",
")",
";",
"curl_close",
"(",
"$",
"ch",
")",
";",
"return",
"(",
"int",
")",
"$",
"httpCode",
";",
"}"
] | HTTP HEAD request with curl.
@access private
@param String $a The request URL
@return Integer Returns the HTTP status code received in
response to a GET request of the input URL. | [
"HTTP",
"HEAD",
"request",
"with",
"curl",
"."
] | bd3117f3ee10d6bf3c3cadd0461c15b91b15428b | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Helper/HttpRequest.php#L76-L104 | train |
eyecatchup/SEOstats | SEOstats/Services/Alexa.php | Alexa.getDailyRank | public static function getDailyRank($url = false)
{
self::setRankingKeys($url);
if (0 == self::$_rankKeys['1d']) {
return parent::noDataDefaultValue();
}
$xpath = self::_getXPath($url);
$nodes = @$xpath->query("//*[@id='rank']/table/tr[" . self::$_rankKeys['1d'] . "]/td[1]");
return !$nodes->item(0) ? parent::noDataDefaultValue() :
self::retInt( strip_tags($nodes->item(0)->nodeValue) );
} | php | public static function getDailyRank($url = false)
{
self::setRankingKeys($url);
if (0 == self::$_rankKeys['1d']) {
return parent::noDataDefaultValue();
}
$xpath = self::_getXPath($url);
$nodes = @$xpath->query("//*[@id='rank']/table/tr[" . self::$_rankKeys['1d'] . "]/td[1]");
return !$nodes->item(0) ? parent::noDataDefaultValue() :
self::retInt( strip_tags($nodes->item(0)->nodeValue) );
} | [
"public",
"static",
"function",
"getDailyRank",
"(",
"$",
"url",
"=",
"false",
")",
"{",
"self",
"::",
"setRankingKeys",
"(",
"$",
"url",
")",
";",
"if",
"(",
"0",
"==",
"self",
"::",
"$",
"_rankKeys",
"[",
"'1d'",
"]",
")",
"{",
"return",
"parent",
"::",
"noDataDefaultValue",
"(",
")",
";",
"}",
"$",
"xpath",
"=",
"self",
"::",
"_getXPath",
"(",
"$",
"url",
")",
";",
"$",
"nodes",
"=",
"@",
"$",
"xpath",
"->",
"query",
"(",
"\"//*[@id='rank']/table/tr[\"",
".",
"self",
"::",
"$",
"_rankKeys",
"[",
"'1d'",
"]",
".",
"\"]/td[1]\"",
")",
";",
"return",
"!",
"$",
"nodes",
"->",
"item",
"(",
"0",
")",
"?",
"parent",
"::",
"noDataDefaultValue",
"(",
")",
":",
"self",
"::",
"retInt",
"(",
"strip_tags",
"(",
"$",
"nodes",
"->",
"item",
"(",
"0",
")",
"->",
"nodeValue",
")",
")",
";",
"}"
] | Get yesterday's rank
@return int | [
"Get",
"yesterday",
"s",
"rank"
] | bd3117f3ee10d6bf3c3cadd0461c15b91b15428b | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Services/Alexa.php#L37-L49 | train |
eyecatchup/SEOstats | SEOstats/Services/Alexa.php | Alexa.getGlobalRank | public static function getGlobalRank($url = false)
{
/*
self::setRankingKeys($url);
if (0 == self::$_rankKeys['3m']) {
return parent::noDataDefaultValue();
}
*/
$xpath = self::_getXPath($url);
$xpathQueryList = array(
"//*[@id='traffic-rank-content']/div/span[2]/div[1]/span/span/div/strong",
"//*[@id='traffic-rank-content']/div/span[2]/div[1]/span/span/div/strong/a"
);
return static::parseDomByXpathsToIntegerWithoutTags($xpath, $xpathQueryList);
} | php | public static function getGlobalRank($url = false)
{
/*
self::setRankingKeys($url);
if (0 == self::$_rankKeys['3m']) {
return parent::noDataDefaultValue();
}
*/
$xpath = self::_getXPath($url);
$xpathQueryList = array(
"//*[@id='traffic-rank-content']/div/span[2]/div[1]/span/span/div/strong",
"//*[@id='traffic-rank-content']/div/span[2]/div[1]/span/span/div/strong/a"
);
return static::parseDomByXpathsToIntegerWithoutTags($xpath, $xpathQueryList);
} | [
"public",
"static",
"function",
"getGlobalRank",
"(",
"$",
"url",
"=",
"false",
")",
"{",
"/*\n self::setRankingKeys($url);\n if (0 == self::$_rankKeys['3m']) {\n return parent::noDataDefaultValue();\n }\n */",
"$",
"xpath",
"=",
"self",
"::",
"_getXPath",
"(",
"$",
"url",
")",
";",
"$",
"xpathQueryList",
"=",
"array",
"(",
"\"//*[@id='traffic-rank-content']/div/span[2]/div[1]/span/span/div/strong\"",
",",
"\"//*[@id='traffic-rank-content']/div/span[2]/div[1]/span/span/div/strong/a\"",
")",
";",
"return",
"static",
"::",
"parseDomByXpathsToIntegerWithoutTags",
"(",
"$",
"xpath",
",",
"$",
"xpathQueryList",
")",
";",
"}"
] | Get the average rank over the last 3 months
@return int | [
"Get",
"the",
"average",
"rank",
"over",
"the",
"last",
"3",
"months"
] | bd3117f3ee10d6bf3c3cadd0461c15b91b15428b | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Services/Alexa.php#L112-L129 | train |
eyecatchup/SEOstats | SEOstats/Services/Alexa.php | Alexa.setRankingKeys | public static function setRankingKeys($url = false)
{
$xpath = self::_getXPath($url);
$nodes = @$xpath->query("//*[@id='rank']/table/tr");
if (5 == $nodes->length) {
self::$_rankKeys = array(
'1d' => 2,
'7d' => 3,
'1m' => 4,
'3m' => 5,
);
}
else if (4 == $nodes->length) {
self::$_rankKeys = array(
'1d' => 0,
'7d' => 2,
'1m' => 3,
'3m' => 4,
);
}
else if (3 == $nodes->length) {
self::$_rankKeys = array(
'1d' => 0,
'7d' => 0,
'1m' => 2,
'3m' => 3,
);
}
else if (2 == $nodes->length) {
self::$_rankKeys = array(
'1d' => 0,
'7d' => 0,
'1m' => 0,
'3m' => 2,
);
}
} | php | public static function setRankingKeys($url = false)
{
$xpath = self::_getXPath($url);
$nodes = @$xpath->query("//*[@id='rank']/table/tr");
if (5 == $nodes->length) {
self::$_rankKeys = array(
'1d' => 2,
'7d' => 3,
'1m' => 4,
'3m' => 5,
);
}
else if (4 == $nodes->length) {
self::$_rankKeys = array(
'1d' => 0,
'7d' => 2,
'1m' => 3,
'3m' => 4,
);
}
else if (3 == $nodes->length) {
self::$_rankKeys = array(
'1d' => 0,
'7d' => 0,
'1m' => 2,
'3m' => 3,
);
}
else if (2 == $nodes->length) {
self::$_rankKeys = array(
'1d' => 0,
'7d' => 0,
'1m' => 0,
'3m' => 2,
);
}
} | [
"public",
"static",
"function",
"setRankingKeys",
"(",
"$",
"url",
"=",
"false",
")",
"{",
"$",
"xpath",
"=",
"self",
"::",
"_getXPath",
"(",
"$",
"url",
")",
";",
"$",
"nodes",
"=",
"@",
"$",
"xpath",
"->",
"query",
"(",
"\"//*[@id='rank']/table/tr\"",
")",
";",
"if",
"(",
"5",
"==",
"$",
"nodes",
"->",
"length",
")",
"{",
"self",
"::",
"$",
"_rankKeys",
"=",
"array",
"(",
"'1d'",
"=>",
"2",
",",
"'7d'",
"=>",
"3",
",",
"'1m'",
"=>",
"4",
",",
"'3m'",
"=>",
"5",
",",
")",
";",
"}",
"else",
"if",
"(",
"4",
"==",
"$",
"nodes",
"->",
"length",
")",
"{",
"self",
"::",
"$",
"_rankKeys",
"=",
"array",
"(",
"'1d'",
"=>",
"0",
",",
"'7d'",
"=>",
"2",
",",
"'1m'",
"=>",
"3",
",",
"'3m'",
"=>",
"4",
",",
")",
";",
"}",
"else",
"if",
"(",
"3",
"==",
"$",
"nodes",
"->",
"length",
")",
"{",
"self",
"::",
"$",
"_rankKeys",
"=",
"array",
"(",
"'1d'",
"=>",
"0",
",",
"'7d'",
"=>",
"0",
",",
"'1m'",
"=>",
"2",
",",
"'3m'",
"=>",
"3",
",",
")",
";",
"}",
"else",
"if",
"(",
"2",
"==",
"$",
"nodes",
"->",
"length",
")",
"{",
"self",
"::",
"$",
"_rankKeys",
"=",
"array",
"(",
"'1d'",
"=>",
"0",
",",
"'7d'",
"=>",
"0",
",",
"'1m'",
"=>",
"0",
",",
"'3m'",
"=>",
"2",
",",
")",
";",
"}",
"}"
] | Get the average rank over the week
@return int | [
"Get",
"the",
"average",
"rank",
"over",
"the",
"week"
] | bd3117f3ee10d6bf3c3cadd0461c15b91b15428b | https://github.com/eyecatchup/SEOstats/blob/bd3117f3ee10d6bf3c3cadd0461c15b91b15428b/SEOstats/Services/Alexa.php#L135-L172 | train |
RubixML/RubixML | src/Clusterers/GaussianMixture.php | GaussianMixture.priors | public function priors() : array
{
$priors = [];
if (is_array($this->priors)) {
$total = logsumexp($this->priors);
foreach ($this->priors as $class => $probability) {
$priors[$class] = exp($probability - $total);
}
}
return $priors;
} | php | public function priors() : array
{
$priors = [];
if (is_array($this->priors)) {
$total = logsumexp($this->priors);
foreach ($this->priors as $class => $probability) {
$priors[$class] = exp($probability - $total);
}
}
return $priors;
} | [
"public",
"function",
"priors",
"(",
")",
":",
"array",
"{",
"$",
"priors",
"=",
"[",
"]",
";",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"priors",
")",
")",
"{",
"$",
"total",
"=",
"logsumexp",
"(",
"$",
"this",
"->",
"priors",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"priors",
"as",
"$",
"class",
"=>",
"$",
"probability",
")",
"{",
"$",
"priors",
"[",
"$",
"class",
"]",
"=",
"exp",
"(",
"$",
"probability",
"-",
"$",
"total",
")",
";",
"}",
"}",
"return",
"$",
"priors",
";",
"}"
] | Return the cluster prior probabilities.
@return float[] | [
"Return",
"the",
"cluster",
"prior",
"probabilities",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/GaussianMixture.php#L187-L200 | train |
RubixML/RubixML | src/Clusterers/GaussianMixture.php | GaussianMixture.initialize | protected function initialize(Dataset $dataset) : array
{
$centroids = $this->seeder->seed($dataset, $this->k);
$kernel = new Euclidean();
$clusters = array_fill(0, $this->k, []);
foreach ($dataset as $sample) {
$bestDistance = INF;
$bestCluster = -1;
foreach ($centroids as $cluster => $centroid) {
$distance = $kernel->compute($sample, $centroid);
if ($distance < $bestDistance) {
$bestDistance = $distance;
$bestCluster = $cluster;
}
}
$clusters[$bestCluster][] = $sample;
}
$means = $variances = [];
foreach ($clusters as $cluster => $samples) {
$mHat = $vHat = [];
$columns = array_map(null, ...$samples);
foreach ($columns as $values) {
[$mean, $variance] = Stats::meanVar($values);
$mHat[] = $mean;
$vHat[] = $variance;
}
$means[$cluster] = $mHat;
$variances[$cluster] = $vHat;
}
return [$means, $variances];
} | php | protected function initialize(Dataset $dataset) : array
{
$centroids = $this->seeder->seed($dataset, $this->k);
$kernel = new Euclidean();
$clusters = array_fill(0, $this->k, []);
foreach ($dataset as $sample) {
$bestDistance = INF;
$bestCluster = -1;
foreach ($centroids as $cluster => $centroid) {
$distance = $kernel->compute($sample, $centroid);
if ($distance < $bestDistance) {
$bestDistance = $distance;
$bestCluster = $cluster;
}
}
$clusters[$bestCluster][] = $sample;
}
$means = $variances = [];
foreach ($clusters as $cluster => $samples) {
$mHat = $vHat = [];
$columns = array_map(null, ...$samples);
foreach ($columns as $values) {
[$mean, $variance] = Stats::meanVar($values);
$mHat[] = $mean;
$vHat[] = $variance;
}
$means[$cluster] = $mHat;
$variances[$cluster] = $vHat;
}
return [$means, $variances];
} | [
"protected",
"function",
"initialize",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"array",
"{",
"$",
"centroids",
"=",
"$",
"this",
"->",
"seeder",
"->",
"seed",
"(",
"$",
"dataset",
",",
"$",
"this",
"->",
"k",
")",
";",
"$",
"kernel",
"=",
"new",
"Euclidean",
"(",
")",
";",
"$",
"clusters",
"=",
"array_fill",
"(",
"0",
",",
"$",
"this",
"->",
"k",
",",
"[",
"]",
")",
";",
"foreach",
"(",
"$",
"dataset",
"as",
"$",
"sample",
")",
"{",
"$",
"bestDistance",
"=",
"INF",
";",
"$",
"bestCluster",
"=",
"-",
"1",
";",
"foreach",
"(",
"$",
"centroids",
"as",
"$",
"cluster",
"=>",
"$",
"centroid",
")",
"{",
"$",
"distance",
"=",
"$",
"kernel",
"->",
"compute",
"(",
"$",
"sample",
",",
"$",
"centroid",
")",
";",
"if",
"(",
"$",
"distance",
"<",
"$",
"bestDistance",
")",
"{",
"$",
"bestDistance",
"=",
"$",
"distance",
";",
"$",
"bestCluster",
"=",
"$",
"cluster",
";",
"}",
"}",
"$",
"clusters",
"[",
"$",
"bestCluster",
"]",
"[",
"]",
"=",
"$",
"sample",
";",
"}",
"$",
"means",
"=",
"$",
"variances",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"clusters",
"as",
"$",
"cluster",
"=>",
"$",
"samples",
")",
"{",
"$",
"mHat",
"=",
"$",
"vHat",
"=",
"[",
"]",
";",
"$",
"columns",
"=",
"array_map",
"(",
"null",
",",
"...",
"$",
"samples",
")",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"values",
")",
"{",
"[",
"$",
"mean",
",",
"$",
"variance",
"]",
"=",
"Stats",
"::",
"meanVar",
"(",
"$",
"values",
")",
";",
"$",
"mHat",
"[",
"]",
"=",
"$",
"mean",
";",
"$",
"vHat",
"[",
"]",
"=",
"$",
"variance",
";",
"}",
"$",
"means",
"[",
"$",
"cluster",
"]",
"=",
"$",
"mHat",
";",
"$",
"variances",
"[",
"$",
"cluster",
"]",
"=",
"$",
"vHat",
";",
"}",
"return",
"[",
"$",
"means",
",",
"$",
"variances",
"]",
";",
"}"
] | Initialize the gaussian components by calculating the means and
variances of k initial cluster centroids generated by the seeder.
@param \Rubix\ML\Datasets\Dataset $dataset
@return array[] | [
"Initialize",
"the",
"gaussian",
"components",
"by",
"calculating",
"the",
"means",
"and",
"variances",
"of",
"k",
"initial",
"cluster",
"centroids",
"generated",
"by",
"the",
"seeder",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/GaussianMixture.php#L437-L480 | train |
RubixML/RubixML | src/NeuralNet/Layers/PReLU.php | PReLU.compute | protected function compute(Matrix $z) : Matrix
{
if (!$this->alpha) {
throw new RuntimeException('Layer is not initialized.');
}
$alphas = $this->alpha->w();
$computed = [];
foreach ($z as $i => $row) {
$alpha = $alphas[$i];
$activations = [];
foreach ($row as $value) {
$activations[] = $value > 0.
? $value
: $alpha * $value;
}
$computed[] = $activations;
}
return Matrix::quick($computed);
} | php | protected function compute(Matrix $z) : Matrix
{
if (!$this->alpha) {
throw new RuntimeException('Layer is not initialized.');
}
$alphas = $this->alpha->w();
$computed = [];
foreach ($z as $i => $row) {
$alpha = $alphas[$i];
$activations = [];
foreach ($row as $value) {
$activations[] = $value > 0.
? $value
: $alpha * $value;
}
$computed[] = $activations;
}
return Matrix::quick($computed);
} | [
"protected",
"function",
"compute",
"(",
"Matrix",
"$",
"z",
")",
":",
"Matrix",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"alpha",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer is not initialized.'",
")",
";",
"}",
"$",
"alphas",
"=",
"$",
"this",
"->",
"alpha",
"->",
"w",
"(",
")",
";",
"$",
"computed",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"z",
"as",
"$",
"i",
"=>",
"$",
"row",
")",
"{",
"$",
"alpha",
"=",
"$",
"alphas",
"[",
"$",
"i",
"]",
";",
"$",
"activations",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"row",
"as",
"$",
"value",
")",
"{",
"$",
"activations",
"[",
"]",
"=",
"$",
"value",
">",
"0.",
"?",
"$",
"value",
":",
"$",
"alpha",
"*",
"$",
"value",
";",
"}",
"$",
"computed",
"[",
"]",
"=",
"$",
"activations",
";",
"}",
"return",
"Matrix",
"::",
"quick",
"(",
"$",
"computed",
")",
";",
"}"
] | Compute the leaky ReLU activation function and return a matrix.
@param \Rubix\Tensor\Matrix $z
@throws \RuntimeException
@return \Rubix\Tensor\Matrix | [
"Compute",
"the",
"leaky",
"ReLU",
"activation",
"function",
"and",
"return",
"a",
"matrix",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/PReLU.php#L185-L210 | train |
RubixML/RubixML | src/NeuralNet/Layers/PReLU.php | PReLU.differentiate | protected function differentiate(Matrix $z) : Matrix
{
if (!$this->alpha) {
throw new RuntimeException('Layer has not been initlaized.');
}
$alphas = $this->alpha->w();
$gradient = [];
foreach ($z as $i => $row) {
$alpha = $alphas[$i];
$temp = [];
foreach ($row as $value) {
$temp[] = $value > 0. ? 1. : $alpha;
}
$gradient[] = $temp;
}
return Matrix::quick($gradient);
} | php | protected function differentiate(Matrix $z) : Matrix
{
if (!$this->alpha) {
throw new RuntimeException('Layer has not been initlaized.');
}
$alphas = $this->alpha->w();
$gradient = [];
foreach ($z as $i => $row) {
$alpha = $alphas[$i];
$temp = [];
foreach ($row as $value) {
$temp[] = $value > 0. ? 1. : $alpha;
}
$gradient[] = $temp;
}
return Matrix::quick($gradient);
} | [
"protected",
"function",
"differentiate",
"(",
"Matrix",
"$",
"z",
")",
":",
"Matrix",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"alpha",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer has not been initlaized.'",
")",
";",
"}",
"$",
"alphas",
"=",
"$",
"this",
"->",
"alpha",
"->",
"w",
"(",
")",
";",
"$",
"gradient",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"z",
"as",
"$",
"i",
"=>",
"$",
"row",
")",
"{",
"$",
"alpha",
"=",
"$",
"alphas",
"[",
"$",
"i",
"]",
";",
"$",
"temp",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"row",
"as",
"$",
"value",
")",
"{",
"$",
"temp",
"[",
"]",
"=",
"$",
"value",
">",
"0.",
"?",
"1.",
":",
"$",
"alpha",
";",
"}",
"$",
"gradient",
"[",
"]",
"=",
"$",
"temp",
";",
"}",
"return",
"Matrix",
"::",
"quick",
"(",
"$",
"gradient",
")",
";",
"}"
] | Calculate the partial derivatives of the activation function.
@param \Rubix\Tensor\Matrix $z
@throws \RuntimeException
@return \Rubix\Tensor\Matrix | [
"Calculate",
"the",
"partial",
"derivatives",
"of",
"the",
"activation",
"function",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/PReLU.php#L219-L242 | train |
RubixML/RubixML | src/CrossValidation/Metrics/RandIndex.php | RandIndex.comb | public static function comb(int $n, int $k = 2) : int
{
return $k === 0 ? 1 : (int) (($n * self::comb($n - 1, $k - 1)) / $k);
} | php | public static function comb(int $n, int $k = 2) : int
{
return $k === 0 ? 1 : (int) (($n * self::comb($n - 1, $k - 1)) / $k);
} | [
"public",
"static",
"function",
"comb",
"(",
"int",
"$",
"n",
",",
"int",
"$",
"k",
"=",
"2",
")",
":",
"int",
"{",
"return",
"$",
"k",
"===",
"0",
"?",
"1",
":",
"(",
"int",
")",
"(",
"(",
"$",
"n",
"*",
"self",
"::",
"comb",
"(",
"$",
"n",
"-",
"1",
",",
"$",
"k",
"-",
"1",
")",
")",
"/",
"$",
"k",
")",
";",
"}"
] | Compute n choose k.
@param int $n
@param int $k
@return int | [
"Compute",
"n",
"choose",
"k",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CrossValidation/Metrics/RandIndex.php#L36-L39 | train |
RubixML/RubixML | src/Other/Helpers/Params.php | Params.ints | public static function ints(int $min, int $max, int $n = 10) : array
{
if (($max - $min) < 0) {
throw new InvalidArgumentException('Maximum cannot be'
. ' less than minimum.');
}
if ($n < 1) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 1 parameter.');
}
if ($n > ($max - $min + 1)) {
throw new InvalidArgumentException('Cannot generate more'
. ' unique integers than in range.');
}
$distribution = [];
while (count($distribution) < $n) {
$r = rand($min, $max);
if (!in_array($r, $distribution)) {
$distribution[] = $r;
}
}
return $distribution;
} | php | public static function ints(int $min, int $max, int $n = 10) : array
{
if (($max - $min) < 0) {
throw new InvalidArgumentException('Maximum cannot be'
. ' less than minimum.');
}
if ($n < 1) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 1 parameter.');
}
if ($n > ($max - $min + 1)) {
throw new InvalidArgumentException('Cannot generate more'
. ' unique integers than in range.');
}
$distribution = [];
while (count($distribution) < $n) {
$r = rand($min, $max);
if (!in_array($r, $distribution)) {
$distribution[] = $r;
}
}
return $distribution;
} | [
"public",
"static",
"function",
"ints",
"(",
"int",
"$",
"min",
",",
"int",
"$",
"max",
",",
"int",
"$",
"n",
"=",
"10",
")",
":",
"array",
"{",
"if",
"(",
"(",
"$",
"max",
"-",
"$",
"min",
")",
"<",
"0",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Maximum cannot be'",
".",
"' less than minimum.'",
")",
";",
"}",
"if",
"(",
"$",
"n",
"<",
"1",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Cannot generate less'",
".",
"' than 1 parameter.'",
")",
";",
"}",
"if",
"(",
"$",
"n",
">",
"(",
"$",
"max",
"-",
"$",
"min",
"+",
"1",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Cannot generate more'",
".",
"' unique integers than in range.'",
")",
";",
"}",
"$",
"distribution",
"=",
"[",
"]",
";",
"while",
"(",
"count",
"(",
"$",
"distribution",
")",
"<",
"$",
"n",
")",
"{",
"$",
"r",
"=",
"rand",
"(",
"$",
"min",
",",
"$",
"max",
")",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"r",
",",
"$",
"distribution",
")",
")",
"{",
"$",
"distribution",
"[",
"]",
"=",
"$",
"r",
";",
"}",
"}",
"return",
"$",
"distribution",
";",
"}"
] | Generate a random unique integer distribution.
@param int $min
@param int $max
@param int $n
@throws \InvalidArgumentException
@return int[] | [
"Generate",
"a",
"random",
"unique",
"integer",
"distribution",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Params.php#L32-L60 | train |
RubixML/RubixML | src/Other/Helpers/Params.php | Params.floats | public static function floats(float $min, float $max, int $n = 10) : array
{
if (($max - $min) < 0.) {
throw new InvalidArgumentException('Maximum cannot be'
. ' less than minimum.');
}
if ($n < 1) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 1 parameter.');
}
$min = (int) round($min * self::PHI);
$max = (int) round($max * self::PHI);
$distribution = [];
for ($i = 0; $i < $n; $i++) {
$distribution[] = rand($min, $max) / self::PHI;
}
return $distribution;
} | php | public static function floats(float $min, float $max, int $n = 10) : array
{
if (($max - $min) < 0.) {
throw new InvalidArgumentException('Maximum cannot be'
. ' less than minimum.');
}
if ($n < 1) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 1 parameter.');
}
$min = (int) round($min * self::PHI);
$max = (int) round($max * self::PHI);
$distribution = [];
for ($i = 0; $i < $n; $i++) {
$distribution[] = rand($min, $max) / self::PHI;
}
return $distribution;
} | [
"public",
"static",
"function",
"floats",
"(",
"float",
"$",
"min",
",",
"float",
"$",
"max",
",",
"int",
"$",
"n",
"=",
"10",
")",
":",
"array",
"{",
"if",
"(",
"(",
"$",
"max",
"-",
"$",
"min",
")",
"<",
"0.",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Maximum cannot be'",
".",
"' less than minimum.'",
")",
";",
"}",
"if",
"(",
"$",
"n",
"<",
"1",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Cannot generate less'",
".",
"' than 1 parameter.'",
")",
";",
"}",
"$",
"min",
"=",
"(",
"int",
")",
"round",
"(",
"$",
"min",
"*",
"self",
"::",
"PHI",
")",
";",
"$",
"max",
"=",
"(",
"int",
")",
"round",
"(",
"$",
"max",
"*",
"self",
"::",
"PHI",
")",
";",
"$",
"distribution",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"n",
";",
"$",
"i",
"++",
")",
"{",
"$",
"distribution",
"[",
"]",
"=",
"rand",
"(",
"$",
"min",
",",
"$",
"max",
")",
"/",
"self",
"::",
"PHI",
";",
"}",
"return",
"$",
"distribution",
";",
"}"
] | Generate a random distribution of floating point parameters.
@param float $min
@param float $max
@param int $n
@throws \InvalidArgumentException
@return float[] | [
"Generate",
"a",
"random",
"distribution",
"of",
"floating",
"point",
"parameters",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Params.php#L71-L93 | train |
RubixML/RubixML | src/Other/Helpers/Params.php | Params.grid | public static function grid(float $min, float $max, int $n = 10) : array
{
if ($min > $max) {
throw new InvalidArgumentException('Max cannot be less'
. ' then min.');
}
if ($n < 2) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 2 parameters.');
}
$interval = ($max - $min) / ($n - 1);
return range($min, $max, $interval);
} | php | public static function grid(float $min, float $max, int $n = 10) : array
{
if ($min > $max) {
throw new InvalidArgumentException('Max cannot be less'
. ' then min.');
}
if ($n < 2) {
throw new InvalidArgumentException('Cannot generate less'
. ' than 2 parameters.');
}
$interval = ($max - $min) / ($n - 1);
return range($min, $max, $interval);
} | [
"public",
"static",
"function",
"grid",
"(",
"float",
"$",
"min",
",",
"float",
"$",
"max",
",",
"int",
"$",
"n",
"=",
"10",
")",
":",
"array",
"{",
"if",
"(",
"$",
"min",
">",
"$",
"max",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Max cannot be less'",
".",
"' then min.'",
")",
";",
"}",
"if",
"(",
"$",
"n",
"<",
"2",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Cannot generate less'",
".",
"' than 2 parameters.'",
")",
";",
"}",
"$",
"interval",
"=",
"(",
"$",
"max",
"-",
"$",
"min",
")",
"/",
"(",
"$",
"n",
"-",
"1",
")",
";",
"return",
"range",
"(",
"$",
"min",
",",
"$",
"max",
",",
"$",
"interval",
")",
";",
"}"
] | Generate a grid of evenly distributed parameters.
@param float $min
@param float $max
@param int $n
@throws \InvalidArgumentException
@return float[] | [
"Generate",
"a",
"grid",
"of",
"evenly",
"distributed",
"parameters",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Params.php#L104-L119 | train |
RubixML/RubixML | src/Other/Helpers/Params.php | Params.args | public static function args($object) : array
{
if (!is_object($object)) {
throw new InvalidArgumentException('Argument must be'
. ' an object ' . gettype($object) . ' found.');
}
$reflector = new ReflectionClass($object);
$constructor = $reflector->getConstructor();
if ($constructor instanceof ReflectionMethod) {
$args = array_column($constructor->getParameters(), 'name');
} else {
$args = [];
}
return $args;
} | php | public static function args($object) : array
{
if (!is_object($object)) {
throw new InvalidArgumentException('Argument must be'
. ' an object ' . gettype($object) . ' found.');
}
$reflector = new ReflectionClass($object);
$constructor = $reflector->getConstructor();
if ($constructor instanceof ReflectionMethod) {
$args = array_column($constructor->getParameters(), 'name');
} else {
$args = [];
}
return $args;
} | [
"public",
"static",
"function",
"args",
"(",
"$",
"object",
")",
":",
"array",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"object",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Argument must be'",
".",
"' an object '",
".",
"gettype",
"(",
"$",
"object",
")",
".",
"' found.'",
")",
";",
"}",
"$",
"reflector",
"=",
"new",
"ReflectionClass",
"(",
"$",
"object",
")",
";",
"$",
"constructor",
"=",
"$",
"reflector",
"->",
"getConstructor",
"(",
")",
";",
"if",
"(",
"$",
"constructor",
"instanceof",
"ReflectionMethod",
")",
"{",
"$",
"args",
"=",
"array_column",
"(",
"$",
"constructor",
"->",
"getParameters",
"(",
")",
",",
"'name'",
")",
";",
"}",
"else",
"{",
"$",
"args",
"=",
"[",
"]",
";",
"}",
"return",
"$",
"args",
";",
"}"
] | Extract the arguments from the model constructor for display.
@param object $object
@throws \InvalidArgumentException
@return string[] | [
"Extract",
"the",
"arguments",
"from",
"the",
"model",
"constructor",
"for",
"display",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Params.php#L128-L146 | train |
RubixML/RubixML | src/Other/Helpers/Params.php | Params.stringify | public static function stringify(array $constructor, string $equator = '=', string $separator = ' ') : string
{
$strings = [];
foreach ($constructor as $arg => $param) {
if (is_object($param)) {
$param = self::shortName($param);
}
if (is_array($param)) {
$temp = array_combine(array_keys($param), $param) ?: [];
$param = '[' . self::stringify($temp) . ']';
}
$strings[] = (string) $arg . $equator . (string) $param;
}
return implode($separator, $strings);
} | php | public static function stringify(array $constructor, string $equator = '=', string $separator = ' ') : string
{
$strings = [];
foreach ($constructor as $arg => $param) {
if (is_object($param)) {
$param = self::shortName($param);
}
if (is_array($param)) {
$temp = array_combine(array_keys($param), $param) ?: [];
$param = '[' . self::stringify($temp) . ']';
}
$strings[] = (string) $arg . $equator . (string) $param;
}
return implode($separator, $strings);
} | [
"public",
"static",
"function",
"stringify",
"(",
"array",
"$",
"constructor",
",",
"string",
"$",
"equator",
"=",
"'='",
",",
"string",
"$",
"separator",
"=",
"' '",
")",
":",
"string",
"{",
"$",
"strings",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"constructor",
"as",
"$",
"arg",
"=>",
"$",
"param",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"param",
")",
")",
"{",
"$",
"param",
"=",
"self",
"::",
"shortName",
"(",
"$",
"param",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"param",
")",
")",
"{",
"$",
"temp",
"=",
"array_combine",
"(",
"array_keys",
"(",
"$",
"param",
")",
",",
"$",
"param",
")",
"?",
":",
"[",
"]",
";",
"$",
"param",
"=",
"'['",
".",
"self",
"::",
"stringify",
"(",
"$",
"temp",
")",
".",
"']'",
";",
"}",
"$",
"strings",
"[",
"]",
"=",
"(",
"string",
")",
"$",
"arg",
".",
"$",
"equator",
".",
"(",
"string",
")",
"$",
"param",
";",
"}",
"return",
"implode",
"(",
"$",
"separator",
",",
"$",
"strings",
")",
";",
"}"
] | Return a string representation of the constructor arguments from
an associative constructor array.
@param array $constructor
@param string $equator
@param string $separator
@return string | [
"Return",
"a",
"string",
"representation",
"of",
"the",
"constructor",
"arguments",
"from",
"an",
"associative",
"constructor",
"array",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Params.php#L157-L176 | train |
RubixML/RubixML | src/CommitteeMachine.php | CommitteeMachine.train | public function train(Dataset $dataset) : void
{
if ($this->type === self::CLASSIFIER or $this->type === self::REGRESSOR) {
if (!$dataset instanceof Labeled) {
throw new InvalidArgumentException('This estimator requires a'
. ' labeled training set.');
}
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
if ($this->logger) {
$this->logger->info('Learner init ' . Params::stringify([
'experts' => $this->experts,
'influences' => $this->influences,
'workers' => $this->workers,
]));
}
Loop::run(function () use ($dataset) {
$pool = new DefaultPool($this->workers);
$coroutines = [];
foreach ($this->experts as $index => $estimator) {
$task = new CallableTask(
[$this, '_train'],
[$estimator, $dataset]
);
$coroutines[] = call(function () use ($pool, $task, $index) {
$estimator = yield $pool->enqueue($task);
if ($this->logger) {
$this->logger->info(Params::stringify([
$index => $estimator,
]) . ' finished training');
}
return $estimator;
});
}
$this->experts = yield all($coroutines);
return yield $pool->shutdown();
});
if ($this->type === self::CLASSIFIER and $dataset instanceof Labeled) {
$this->classes = $dataset->possibleOutcomes();
}
if ($this->logger) {
$this->logger->info('Training complete');
}
} | php | public function train(Dataset $dataset) : void
{
if ($this->type === self::CLASSIFIER or $this->type === self::REGRESSOR) {
if (!$dataset instanceof Labeled) {
throw new InvalidArgumentException('This estimator requires a'
. ' labeled training set.');
}
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
if ($this->logger) {
$this->logger->info('Learner init ' . Params::stringify([
'experts' => $this->experts,
'influences' => $this->influences,
'workers' => $this->workers,
]));
}
Loop::run(function () use ($dataset) {
$pool = new DefaultPool($this->workers);
$coroutines = [];
foreach ($this->experts as $index => $estimator) {
$task = new CallableTask(
[$this, '_train'],
[$estimator, $dataset]
);
$coroutines[] = call(function () use ($pool, $task, $index) {
$estimator = yield $pool->enqueue($task);
if ($this->logger) {
$this->logger->info(Params::stringify([
$index => $estimator,
]) . ' finished training');
}
return $estimator;
});
}
$this->experts = yield all($coroutines);
return yield $pool->shutdown();
});
if ($this->type === self::CLASSIFIER and $dataset instanceof Labeled) {
$this->classes = $dataset->possibleOutcomes();
}
if ($this->logger) {
$this->logger->info('Training complete');
}
} | [
"public",
"function",
"train",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"type",
"===",
"self",
"::",
"CLASSIFIER",
"or",
"$",
"this",
"->",
"type",
"===",
"self",
"::",
"REGRESSOR",
")",
"{",
"if",
"(",
"!",
"$",
"dataset",
"instanceof",
"Labeled",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'This estimator requires a'",
".",
"' labeled training set.'",
")",
";",
"}",
"}",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Learner init '",
".",
"Params",
"::",
"stringify",
"(",
"[",
"'experts'",
"=>",
"$",
"this",
"->",
"experts",
",",
"'influences'",
"=>",
"$",
"this",
"->",
"influences",
",",
"'workers'",
"=>",
"$",
"this",
"->",
"workers",
",",
"]",
")",
")",
";",
"}",
"Loop",
"::",
"run",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"dataset",
")",
"{",
"$",
"pool",
"=",
"new",
"DefaultPool",
"(",
"$",
"this",
"->",
"workers",
")",
";",
"$",
"coroutines",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"experts",
"as",
"$",
"index",
"=>",
"$",
"estimator",
")",
"{",
"$",
"task",
"=",
"new",
"CallableTask",
"(",
"[",
"$",
"this",
",",
"'_train'",
"]",
",",
"[",
"$",
"estimator",
",",
"$",
"dataset",
"]",
")",
";",
"$",
"coroutines",
"[",
"]",
"=",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"pool",
",",
"$",
"task",
",",
"$",
"index",
")",
"{",
"$",
"estimator",
"=",
"yield",
"$",
"pool",
"->",
"enqueue",
"(",
"$",
"task",
")",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"Params",
"::",
"stringify",
"(",
"[",
"$",
"index",
"=>",
"$",
"estimator",
",",
"]",
")",
".",
"' finished training'",
")",
";",
"}",
"return",
"$",
"estimator",
";",
"}",
")",
";",
"}",
"$",
"this",
"->",
"experts",
"=",
"yield",
"all",
"(",
"$",
"coroutines",
")",
";",
"return",
"yield",
"$",
"pool",
"->",
"shutdown",
"(",
")",
";",
"}",
")",
";",
"if",
"(",
"$",
"this",
"->",
"type",
"===",
"self",
"::",
"CLASSIFIER",
"and",
"$",
"dataset",
"instanceof",
"Labeled",
")",
"{",
"$",
"this",
"->",
"classes",
"=",
"$",
"dataset",
"->",
"possibleOutcomes",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Training complete'",
")",
";",
"}",
"}"
] | Train all the experts with the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Train",
"all",
"the",
"experts",
"with",
"the",
"dataset",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CommitteeMachine.php#L215-L270 | train |
RubixML/RubixML | src/CommitteeMachine.php | CommitteeMachine.decideClass | public function decideClass(array $votes)
{
$scores = array_fill_keys($this->classes, 0.);
foreach ($votes as $i => $vote) {
$scores[$vote] += $this->influences[$i];
}
return argmax($scores);
} | php | public function decideClass(array $votes)
{
$scores = array_fill_keys($this->classes, 0.);
foreach ($votes as $i => $vote) {
$scores[$vote] += $this->influences[$i];
}
return argmax($scores);
} | [
"public",
"function",
"decideClass",
"(",
"array",
"$",
"votes",
")",
"{",
"$",
"scores",
"=",
"array_fill_keys",
"(",
"$",
"this",
"->",
"classes",
",",
"0.",
")",
";",
"foreach",
"(",
"$",
"votes",
"as",
"$",
"i",
"=>",
"$",
"vote",
")",
"{",
"$",
"scores",
"[",
"$",
"vote",
"]",
"+=",
"$",
"this",
"->",
"influences",
"[",
"$",
"i",
"]",
";",
"}",
"return",
"argmax",
"(",
"$",
"scores",
")",
";",
"}"
] | Decide on a class outcome.
@param (int|string)[] $votes
@return int|string | [
"Decide",
"on",
"a",
"class",
"outcome",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CommitteeMachine.php#L306-L315 | train |
RubixML/RubixML | src/CommitteeMachine.php | CommitteeMachine.decideAnomaly | public function decideAnomaly(array $votes) : int
{
$scores = array_fill(0, 2, 0.);
foreach ($votes as $i => $vote) {
$scores[$vote] += $this->influences[$i];
}
return argmax($scores);
} | php | public function decideAnomaly(array $votes) : int
{
$scores = array_fill(0, 2, 0.);
foreach ($votes as $i => $vote) {
$scores[$vote] += $this->influences[$i];
}
return argmax($scores);
} | [
"public",
"function",
"decideAnomaly",
"(",
"array",
"$",
"votes",
")",
":",
"int",
"{",
"$",
"scores",
"=",
"array_fill",
"(",
"0",
",",
"2",
",",
"0.",
")",
";",
"foreach",
"(",
"$",
"votes",
"as",
"$",
"i",
"=>",
"$",
"vote",
")",
"{",
"$",
"scores",
"[",
"$",
"vote",
"]",
"+=",
"$",
"this",
"->",
"influences",
"[",
"$",
"i",
"]",
";",
"}",
"return",
"argmax",
"(",
"$",
"scores",
")",
";",
"}"
] | Decide on an anomaly outcome.
@param int[] $votes
@return int | [
"Decide",
"on",
"an",
"anomaly",
"outcome",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CommitteeMachine.php#L334-L343 | train |
RubixML/RubixML | src/CommitteeMachine.php | CommitteeMachine._train | public function _train(Learner $estimator, Dataset $dataset) : Learner
{
$estimator->train($dataset);
return $estimator;
} | php | public function _train(Learner $estimator, Dataset $dataset) : Learner
{
$estimator->train($dataset);
return $estimator;
} | [
"public",
"function",
"_train",
"(",
"Learner",
"$",
"estimator",
",",
"Dataset",
"$",
"dataset",
")",
":",
"Learner",
"{",
"$",
"estimator",
"->",
"train",
"(",
"$",
"dataset",
")",
";",
"return",
"$",
"estimator",
";",
"}"
] | Train an learner using a dataset and return it.
@param \Rubix\ML\Learner $estimator
@param \Rubix\ML\Datasets\Dataset $dataset
@return \Rubix\ML\Learner | [
"Train",
"an",
"learner",
"using",
"a",
"dataset",
"and",
"return",
"it",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CommitteeMachine.php#L352-L357 | train |
RubixML/RubixML | src/NeuralNet/Deferred.php | Deferred.result | public function result() : Matrix
{
if (!$this->result) {
$this->result = call_user_func($this->computation);
}
return $this->result;
} | php | public function result() : Matrix
{
if (!$this->result) {
$this->result = call_user_func($this->computation);
}
return $this->result;
} | [
"public",
"function",
"result",
"(",
")",
":",
"Matrix",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"result",
")",
"{",
"$",
"this",
"->",
"result",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"computation",
")",
";",
"}",
"return",
"$",
"this",
"->",
"result",
";",
"}"
] | Return the result of the computation.
@return \Rubix\Tensor\Matrix | [
"Return",
"the",
"result",
"of",
"the",
"computation",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Deferred.php#L49-L56 | train |
RubixML/RubixML | src/Classifiers/GaussianNB.php | GaussianNB.train | public function train(Dataset $dataset) : void
{
if (!$dataset instanceof Labeled) {
throw new InvalidArgumentException('This Estimator requires a'
. ' Labeled training set.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$classes = $dataset->possibleOutcomes();
$this->classes = $classes;
$this->weights = array_fill_keys($classes, 0);
$this->means = $this->variances = array_fill_keys($classes, []);
foreach ($dataset->stratify() as $class => $stratum) {
$means = $variances = [];
foreach ($stratum->columns() as $values) {
[$mean, $variance] = Stats::meanVar($values);
$means[] = $mean;
$variances[] = $variance ?: EPSILON;
}
$this->means[$class] = $means;
$this->variances[$class] = $variances;
$this->weights[$class] += $stratum->numRows();
}
if ($this->fitPriors) {
$this->priors = [];
$total = array_sum($this->weights) ?: EPSILON;
foreach ($this->weights as $class => $weight) {
$this->priors[$class] = log($weight / $total);
}
}
} | php | public function train(Dataset $dataset) : void
{
if (!$dataset instanceof Labeled) {
throw new InvalidArgumentException('This Estimator requires a'
. ' Labeled training set.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$classes = $dataset->possibleOutcomes();
$this->classes = $classes;
$this->weights = array_fill_keys($classes, 0);
$this->means = $this->variances = array_fill_keys($classes, []);
foreach ($dataset->stratify() as $class => $stratum) {
$means = $variances = [];
foreach ($stratum->columns() as $values) {
[$mean, $variance] = Stats::meanVar($values);
$means[] = $mean;
$variances[] = $variance ?: EPSILON;
}
$this->means[$class] = $means;
$this->variances[$class] = $variances;
$this->weights[$class] += $stratum->numRows();
}
if ($this->fitPriors) {
$this->priors = [];
$total = array_sum($this->weights) ?: EPSILON;
foreach ($this->weights as $class => $weight) {
$this->priors[$class] = log($weight / $total);
}
}
} | [
"public",
"function",
"train",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"if",
"(",
"!",
"$",
"dataset",
"instanceof",
"Labeled",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'This Estimator requires a'",
".",
"' Labeled training set.'",
")",
";",
"}",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"$",
"classes",
"=",
"$",
"dataset",
"->",
"possibleOutcomes",
"(",
")",
";",
"$",
"this",
"->",
"classes",
"=",
"$",
"classes",
";",
"$",
"this",
"->",
"weights",
"=",
"array_fill_keys",
"(",
"$",
"classes",
",",
"0",
")",
";",
"$",
"this",
"->",
"means",
"=",
"$",
"this",
"->",
"variances",
"=",
"array_fill_keys",
"(",
"$",
"classes",
",",
"[",
"]",
")",
";",
"foreach",
"(",
"$",
"dataset",
"->",
"stratify",
"(",
")",
"as",
"$",
"class",
"=>",
"$",
"stratum",
")",
"{",
"$",
"means",
"=",
"$",
"variances",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"stratum",
"->",
"columns",
"(",
")",
"as",
"$",
"values",
")",
"{",
"[",
"$",
"mean",
",",
"$",
"variance",
"]",
"=",
"Stats",
"::",
"meanVar",
"(",
"$",
"values",
")",
";",
"$",
"means",
"[",
"]",
"=",
"$",
"mean",
";",
"$",
"variances",
"[",
"]",
"=",
"$",
"variance",
"?",
":",
"EPSILON",
";",
"}",
"$",
"this",
"->",
"means",
"[",
"$",
"class",
"]",
"=",
"$",
"means",
";",
"$",
"this",
"->",
"variances",
"[",
"$",
"class",
"]",
"=",
"$",
"variances",
";",
"$",
"this",
"->",
"weights",
"[",
"$",
"class",
"]",
"+=",
"$",
"stratum",
"->",
"numRows",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"fitPriors",
")",
"{",
"$",
"this",
"->",
"priors",
"=",
"[",
"]",
";",
"$",
"total",
"=",
"array_sum",
"(",
"$",
"this",
"->",
"weights",
")",
"?",
":",
"EPSILON",
";",
"foreach",
"(",
"$",
"this",
"->",
"weights",
"as",
"$",
"class",
"=>",
"$",
"weight",
")",
"{",
"$",
"this",
"->",
"priors",
"[",
"$",
"class",
"]",
"=",
"log",
"(",
"$",
"weight",
"/",
"$",
"total",
")",
";",
"}",
"}",
"}"
] | Compute the necessary statistics to estimate a probability density for
each feature column.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Compute",
"the",
"necessary",
"statistics",
"to",
"estimate",
"a",
"probability",
"density",
"for",
"each",
"feature",
"column",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/GaussianNB.php#L207-L248 | train |
RubixML/RubixML | src/Classifiers/GaussianNB.php | GaussianNB.partial | public function partial(Dataset $dataset) : void
{
if (empty($this->weights) or empty($this->means) or empty($this->variances)) {
$this->train($dataset);
return;
}
if (!$dataset instanceof Labeled) {
throw new InvalidArgumentException('This Estimator requires a'
. ' Labeled training set.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
foreach ($dataset->stratify() as $class => $stratum) {
$means = $this->means[$class];
$variances = $this->variances[$class];
$oldWeight = $this->weights[$class];
$oldMeans = $this->means[$class];
$oldVariances = $this->variances[$class];
$n = $stratum->numRows();
foreach ($stratum->columns() as $column => $values) {
[$mean, $variance] = Stats::meanVar($values);
$means[$column] = (($n * $mean)
+ ($oldWeight * $oldMeans[$column]))
/ ($oldWeight + $n);
$vHat = ($oldWeight
* $oldVariances[$column] + ($n * $variance)
+ ($oldWeight / ($n * ($oldWeight + $n)))
* ($n * $oldMeans[$column] - $n * $mean) ** 2)
/ ($oldWeight + $n);
$variances[$column] = $vHat ?: EPSILON;
}
$this->means[$class] = $means;
$this->variances[$class] = $variances;
$this->weights[$class] += $n;
}
if ($this->fitPriors) {
$total = array_sum($this->weights) ?: EPSILON;
foreach ($this->weights as $class => $weight) {
$this->priors[$class] = log($weight / $total);
}
}
} | php | public function partial(Dataset $dataset) : void
{
if (empty($this->weights) or empty($this->means) or empty($this->variances)) {
$this->train($dataset);
return;
}
if (!$dataset instanceof Labeled) {
throw new InvalidArgumentException('This Estimator requires a'
. ' Labeled training set.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
foreach ($dataset->stratify() as $class => $stratum) {
$means = $this->means[$class];
$variances = $this->variances[$class];
$oldWeight = $this->weights[$class];
$oldMeans = $this->means[$class];
$oldVariances = $this->variances[$class];
$n = $stratum->numRows();
foreach ($stratum->columns() as $column => $values) {
[$mean, $variance] = Stats::meanVar($values);
$means[$column] = (($n * $mean)
+ ($oldWeight * $oldMeans[$column]))
/ ($oldWeight + $n);
$vHat = ($oldWeight
* $oldVariances[$column] + ($n * $variance)
+ ($oldWeight / ($n * ($oldWeight + $n)))
* ($n * $oldMeans[$column] - $n * $mean) ** 2)
/ ($oldWeight + $n);
$variances[$column] = $vHat ?: EPSILON;
}
$this->means[$class] = $means;
$this->variances[$class] = $variances;
$this->weights[$class] += $n;
}
if ($this->fitPriors) {
$total = array_sum($this->weights) ?: EPSILON;
foreach ($this->weights as $class => $weight) {
$this->priors[$class] = log($weight / $total);
}
}
} | [
"public",
"function",
"partial",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"weights",
")",
"or",
"empty",
"(",
"$",
"this",
"->",
"means",
")",
"or",
"empty",
"(",
"$",
"this",
"->",
"variances",
")",
")",
"{",
"$",
"this",
"->",
"train",
"(",
"$",
"dataset",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"$",
"dataset",
"instanceof",
"Labeled",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'This Estimator requires a'",
".",
"' Labeled training set.'",
")",
";",
"}",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"foreach",
"(",
"$",
"dataset",
"->",
"stratify",
"(",
")",
"as",
"$",
"class",
"=>",
"$",
"stratum",
")",
"{",
"$",
"means",
"=",
"$",
"this",
"->",
"means",
"[",
"$",
"class",
"]",
";",
"$",
"variances",
"=",
"$",
"this",
"->",
"variances",
"[",
"$",
"class",
"]",
";",
"$",
"oldWeight",
"=",
"$",
"this",
"->",
"weights",
"[",
"$",
"class",
"]",
";",
"$",
"oldMeans",
"=",
"$",
"this",
"->",
"means",
"[",
"$",
"class",
"]",
";",
"$",
"oldVariances",
"=",
"$",
"this",
"->",
"variances",
"[",
"$",
"class",
"]",
";",
"$",
"n",
"=",
"$",
"stratum",
"->",
"numRows",
"(",
")",
";",
"foreach",
"(",
"$",
"stratum",
"->",
"columns",
"(",
")",
"as",
"$",
"column",
"=>",
"$",
"values",
")",
"{",
"[",
"$",
"mean",
",",
"$",
"variance",
"]",
"=",
"Stats",
"::",
"meanVar",
"(",
"$",
"values",
")",
";",
"$",
"means",
"[",
"$",
"column",
"]",
"=",
"(",
"(",
"$",
"n",
"*",
"$",
"mean",
")",
"+",
"(",
"$",
"oldWeight",
"*",
"$",
"oldMeans",
"[",
"$",
"column",
"]",
")",
")",
"/",
"(",
"$",
"oldWeight",
"+",
"$",
"n",
")",
";",
"$",
"vHat",
"=",
"(",
"$",
"oldWeight",
"*",
"$",
"oldVariances",
"[",
"$",
"column",
"]",
"+",
"(",
"$",
"n",
"*",
"$",
"variance",
")",
"+",
"(",
"$",
"oldWeight",
"/",
"(",
"$",
"n",
"*",
"(",
"$",
"oldWeight",
"+",
"$",
"n",
")",
")",
")",
"*",
"(",
"$",
"n",
"*",
"$",
"oldMeans",
"[",
"$",
"column",
"]",
"-",
"$",
"n",
"*",
"$",
"mean",
")",
"**",
"2",
")",
"/",
"(",
"$",
"oldWeight",
"+",
"$",
"n",
")",
";",
"$",
"variances",
"[",
"$",
"column",
"]",
"=",
"$",
"vHat",
"?",
":",
"EPSILON",
";",
"}",
"$",
"this",
"->",
"means",
"[",
"$",
"class",
"]",
"=",
"$",
"means",
";",
"$",
"this",
"->",
"variances",
"[",
"$",
"class",
"]",
"=",
"$",
"variances",
";",
"$",
"this",
"->",
"weights",
"[",
"$",
"class",
"]",
"+=",
"$",
"n",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"fitPriors",
")",
"{",
"$",
"total",
"=",
"array_sum",
"(",
"$",
"this",
"->",
"weights",
")",
"?",
":",
"EPSILON",
";",
"foreach",
"(",
"$",
"this",
"->",
"weights",
"as",
"$",
"class",
"=>",
"$",
"weight",
")",
"{",
"$",
"this",
"->",
"priors",
"[",
"$",
"class",
"]",
"=",
"log",
"(",
"$",
"weight",
"/",
"$",
"total",
")",
";",
"}",
"}",
"}"
] | Uupdate the rolling means and variances of each feature column using an
online updating algorithm.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Uupdate",
"the",
"rolling",
"means",
"and",
"variances",
"of",
"each",
"feature",
"column",
"using",
"an",
"online",
"updating",
"algorithm",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/GaussianNB.php#L257-L311 | train |
RubixML/RubixML | src/NeuralNet/Layers/BatchNorm.php | BatchNorm.back | public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred
{
if (!$this->beta or !$this->gamma) {
throw new RuntimeException('Layer has not been initilaized.');
}
if (!$this->stdInv or !$this->xHat) {
throw new RuntimeException('Must perform forward pass before'
. ' backpropagating.');
}
$dOut = $prevGradient->result();
$dBeta = $dOut->sum();
$dGamma = $dOut->multiply($this->xHat)->sum();
$gamma = $this->gamma->w();
$optimizer->step($this->beta, $dBeta);
$optimizer->step($this->gamma, $dGamma);
$stdInv = $this->stdInv;
$xHat = $this->xHat;
unset($this->stdInv, $this->xHat);
return new Deferred(function () use ($dOut, $gamma, $stdInv, $xHat) {
$dXHat = $dOut->multiply($gamma);
$xHatSigma = $dXHat->multiply($xHat)->sum();
$dXHatSigma = $dXHat->sum();
return $dXHat->multiply($dOut->m())
->subtract($dXHatSigma)
->subtract($xHat->multiply($xHatSigma))
->multiply($stdInv->divide($dOut->m()));
});
} | php | public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred
{
if (!$this->beta or !$this->gamma) {
throw new RuntimeException('Layer has not been initilaized.');
}
if (!$this->stdInv or !$this->xHat) {
throw new RuntimeException('Must perform forward pass before'
. ' backpropagating.');
}
$dOut = $prevGradient->result();
$dBeta = $dOut->sum();
$dGamma = $dOut->multiply($this->xHat)->sum();
$gamma = $this->gamma->w();
$optimizer->step($this->beta, $dBeta);
$optimizer->step($this->gamma, $dGamma);
$stdInv = $this->stdInv;
$xHat = $this->xHat;
unset($this->stdInv, $this->xHat);
return new Deferred(function () use ($dOut, $gamma, $stdInv, $xHat) {
$dXHat = $dOut->multiply($gamma);
$xHatSigma = $dXHat->multiply($xHat)->sum();
$dXHatSigma = $dXHat->sum();
return $dXHat->multiply($dOut->m())
->subtract($dXHatSigma)
->subtract($xHat->multiply($xHatSigma))
->multiply($stdInv->divide($dOut->m()));
});
} | [
"public",
"function",
"back",
"(",
"Deferred",
"$",
"prevGradient",
",",
"Optimizer",
"$",
"optimizer",
")",
":",
"Deferred",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"beta",
"or",
"!",
"$",
"this",
"->",
"gamma",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Layer has not been initilaized.'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"stdInv",
"or",
"!",
"$",
"this",
"->",
"xHat",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Must perform forward pass before'",
".",
"' backpropagating.'",
")",
";",
"}",
"$",
"dOut",
"=",
"$",
"prevGradient",
"->",
"result",
"(",
")",
";",
"$",
"dBeta",
"=",
"$",
"dOut",
"->",
"sum",
"(",
")",
";",
"$",
"dGamma",
"=",
"$",
"dOut",
"->",
"multiply",
"(",
"$",
"this",
"->",
"xHat",
")",
"->",
"sum",
"(",
")",
";",
"$",
"gamma",
"=",
"$",
"this",
"->",
"gamma",
"->",
"w",
"(",
")",
";",
"$",
"optimizer",
"->",
"step",
"(",
"$",
"this",
"->",
"beta",
",",
"$",
"dBeta",
")",
";",
"$",
"optimizer",
"->",
"step",
"(",
"$",
"this",
"->",
"gamma",
",",
"$",
"dGamma",
")",
";",
"$",
"stdInv",
"=",
"$",
"this",
"->",
"stdInv",
";",
"$",
"xHat",
"=",
"$",
"this",
"->",
"xHat",
";",
"unset",
"(",
"$",
"this",
"->",
"stdInv",
",",
"$",
"this",
"->",
"xHat",
")",
";",
"return",
"new",
"Deferred",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"dOut",
",",
"$",
"gamma",
",",
"$",
"stdInv",
",",
"$",
"xHat",
")",
"{",
"$",
"dXHat",
"=",
"$",
"dOut",
"->",
"multiply",
"(",
"$",
"gamma",
")",
";",
"$",
"xHatSigma",
"=",
"$",
"dXHat",
"->",
"multiply",
"(",
"$",
"xHat",
")",
"->",
"sum",
"(",
")",
";",
"$",
"dXHatSigma",
"=",
"$",
"dXHat",
"->",
"sum",
"(",
")",
";",
"return",
"$",
"dXHat",
"->",
"multiply",
"(",
"$",
"dOut",
"->",
"m",
"(",
")",
")",
"->",
"subtract",
"(",
"$",
"dXHatSigma",
")",
"->",
"subtract",
"(",
"$",
"xHat",
"->",
"multiply",
"(",
"$",
"xHatSigma",
")",
")",
"->",
"multiply",
"(",
"$",
"stdInv",
"->",
"divide",
"(",
"$",
"dOut",
"->",
"m",
"(",
")",
")",
")",
";",
"}",
")",
";",
"}"
] | Calculate the errors and gradients of the layer and update the parameters.
@param \Rubix\ML\NeuralNet\Deferred $prevGradient
@param \Rubix\ML\NeuralNet\Optimizers\Optimizer $optimizer
@throws \RuntimeException
@return \Rubix\ML\NeuralNet\Deferred | [
"Calculate",
"the",
"errors",
"and",
"gradients",
"of",
"the",
"layer",
"and",
"update",
"the",
"parameters",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/BatchNorm.php#L255-L293 | train |
RubixML/RubixML | src/Classifiers/ClassificationTree.php | ClassificationTree.terminate | protected function terminate(Labeled $dataset) : BinaryNode
{
$n = $dataset->numRows();
$labels = $dataset->labels();
$counts = array_count_values($labels);
$outcome = argmax($counts);
$probabilities = [];
foreach ($counts as $class => $count) {
$probabilities[$class] = $count / $n;
}
$impurity = 1. - (max($counts) / $n) ** 2;
return new Outcome($outcome, $probabilities, $impurity, $n);
} | php | protected function terminate(Labeled $dataset) : BinaryNode
{
$n = $dataset->numRows();
$labels = $dataset->labels();
$counts = array_count_values($labels);
$outcome = argmax($counts);
$probabilities = [];
foreach ($counts as $class => $count) {
$probabilities[$class] = $count / $n;
}
$impurity = 1. - (max($counts) / $n) ** 2;
return new Outcome($outcome, $probabilities, $impurity, $n);
} | [
"protected",
"function",
"terminate",
"(",
"Labeled",
"$",
"dataset",
")",
":",
"BinaryNode",
"{",
"$",
"n",
"=",
"$",
"dataset",
"->",
"numRows",
"(",
")",
";",
"$",
"labels",
"=",
"$",
"dataset",
"->",
"labels",
"(",
")",
";",
"$",
"counts",
"=",
"array_count_values",
"(",
"$",
"labels",
")",
";",
"$",
"outcome",
"=",
"argmax",
"(",
"$",
"counts",
")",
";",
"$",
"probabilities",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"counts",
"as",
"$",
"class",
"=>",
"$",
"count",
")",
"{",
"$",
"probabilities",
"[",
"$",
"class",
"]",
"=",
"$",
"count",
"/",
"$",
"n",
";",
"}",
"$",
"impurity",
"=",
"1.",
"-",
"(",
"max",
"(",
"$",
"counts",
")",
"/",
"$",
"n",
")",
"**",
"2",
";",
"return",
"new",
"Outcome",
"(",
"$",
"outcome",
",",
"$",
"probabilities",
",",
"$",
"impurity",
",",
"$",
"n",
")",
";",
"}"
] | Terminate the branch by selecting the class outcome with the highest
probability.
@param \Rubix\ML\Datasets\Labeled $dataset
@return \Rubix\ML\Graph\Nodes\BinaryNode | [
"Terminate",
"the",
"branch",
"by",
"selecting",
"the",
"class",
"outcome",
"with",
"the",
"highest",
"probability",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/ClassificationTree.php#L264-L283 | train |
RubixML/RubixML | src/Classifiers/ClassificationTree.php | ClassificationTree.splitImpurity | protected function splitImpurity(array $groups) : float
{
$n = array_sum(array_map('count', $groups));
$impurity = 0.;
foreach ($groups as $dataset) {
$k = $dataset->numRows();
if ($k < 2) {
continue 1;
}
$counts = array_count_values($dataset->labels());
$p = 0.;
foreach ($counts as $count) {
$p += 1. - ($count / $n) ** 2;
}
$impurity += ($k / $n) * $p;
}
return $impurity;
} | php | protected function splitImpurity(array $groups) : float
{
$n = array_sum(array_map('count', $groups));
$impurity = 0.;
foreach ($groups as $dataset) {
$k = $dataset->numRows();
if ($k < 2) {
continue 1;
}
$counts = array_count_values($dataset->labels());
$p = 0.;
foreach ($counts as $count) {
$p += 1. - ($count / $n) ** 2;
}
$impurity += ($k / $n) * $p;
}
return $impurity;
} | [
"protected",
"function",
"splitImpurity",
"(",
"array",
"$",
"groups",
")",
":",
"float",
"{",
"$",
"n",
"=",
"array_sum",
"(",
"array_map",
"(",
"'count'",
",",
"$",
"groups",
")",
")",
";",
"$",
"impurity",
"=",
"0.",
";",
"foreach",
"(",
"$",
"groups",
"as",
"$",
"dataset",
")",
"{",
"$",
"k",
"=",
"$",
"dataset",
"->",
"numRows",
"(",
")",
";",
"if",
"(",
"$",
"k",
"<",
"2",
")",
"{",
"continue",
"1",
";",
"}",
"$",
"counts",
"=",
"array_count_values",
"(",
"$",
"dataset",
"->",
"labels",
"(",
")",
")",
";",
"$",
"p",
"=",
"0.",
";",
"foreach",
"(",
"$",
"counts",
"as",
"$",
"count",
")",
"{",
"$",
"p",
"+=",
"1.",
"-",
"(",
"$",
"count",
"/",
"$",
"n",
")",
"**",
"2",
";",
"}",
"$",
"impurity",
"+=",
"(",
"$",
"k",
"/",
"$",
"n",
")",
"*",
"$",
"p",
";",
"}",
"return",
"$",
"impurity",
";",
"}"
] | Calculate the Gini impurity for a given split.
@param array $groups
@return float | [
"Calculate",
"the",
"Gini",
"impurity",
"for",
"a",
"given",
"split",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/ClassificationTree.php#L291-L316 | train |
RubixML/RubixML | src/Datasets/DataFrame.php | DataFrame.columnType | public function columnType(int $index) : int
{
if (empty($this->samples)) {
throw new RuntimeException('Cannot determine data type'
. ' of an empty data frame.');
}
$sample = reset($this->samples);
if (!isset($sample[$index])) {
throw new InvalidArgumentException("Column $index does"
. ' not exist.');
}
return DataType::determine($sample[$index]);
} | php | public function columnType(int $index) : int
{
if (empty($this->samples)) {
throw new RuntimeException('Cannot determine data type'
. ' of an empty data frame.');
}
$sample = reset($this->samples);
if (!isset($sample[$index])) {
throw new InvalidArgumentException("Column $index does"
. ' not exist.');
}
return DataType::determine($sample[$index]);
} | [
"public",
"function",
"columnType",
"(",
"int",
"$",
"index",
")",
":",
"int",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"samples",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Cannot determine data type'",
".",
"' of an empty data frame.'",
")",
";",
"}",
"$",
"sample",
"=",
"reset",
"(",
"$",
"this",
"->",
"samples",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"sample",
"[",
"$",
"index",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Column $index does\"",
".",
"' not exist.'",
")",
";",
"}",
"return",
"DataType",
"::",
"determine",
"(",
"$",
"sample",
"[",
"$",
"index",
"]",
")",
";",
"}"
] | Get the datatype for a feature column given a column index.
@param int $index
@throws \InvalidArgumentException
@throws \RuntimeException
@return int | [
"Get",
"the",
"datatype",
"for",
"a",
"feature",
"column",
"given",
"a",
"column",
"index",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/DataFrame.php#L145-L160 | train |
RubixML/RubixML | src/Datasets/DataFrame.php | DataFrame.columns | public function columns() : array
{
if ($this->numRows() > 1) {
return array_map(null, ...$this->samples);
}
$n = $this->numColumns();
$columns = [];
for ($i = 0; $i < $n; $i++) {
$columns[] = array_column($this->samples, $i);
}
return $columns;
} | php | public function columns() : array
{
if ($this->numRows() > 1) {
return array_map(null, ...$this->samples);
}
$n = $this->numColumns();
$columns = [];
for ($i = 0; $i < $n; $i++) {
$columns[] = array_column($this->samples, $i);
}
return $columns;
} | [
"public",
"function",
"columns",
"(",
")",
":",
"array",
"{",
"if",
"(",
"$",
"this",
"->",
"numRows",
"(",
")",
">",
"1",
")",
"{",
"return",
"array_map",
"(",
"null",
",",
"...",
"$",
"this",
"->",
"samples",
")",
";",
"}",
"$",
"n",
"=",
"$",
"this",
"->",
"numColumns",
"(",
")",
";",
"$",
"columns",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"n",
";",
"$",
"i",
"++",
")",
"{",
"$",
"columns",
"[",
"]",
"=",
"array_column",
"(",
"$",
"this",
"->",
"samples",
",",
"$",
"i",
")",
";",
"}",
"return",
"$",
"columns",
";",
"}"
] | Rotate the dataframe and return it in an array. i.e. rows become
columns and columns become rows.
@return array | [
"Rotate",
"the",
"dataframe",
"and",
"return",
"it",
"in",
"an",
"array",
".",
"i",
".",
"e",
".",
"rows",
"become",
"columns",
"and",
"columns",
"become",
"rows",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/DataFrame.php#L189-L204 | train |
RubixML/RubixML | src/Datasets/DataFrame.php | DataFrame.columnsByType | public function columnsByType(int $type) : array
{
$n = $this->numColumns();
$columns = [];
for ($i = 0; $i < $n; $i++) {
if ($this->columnType($i) === $type) {
$columns[$i] = $this->column($i);
}
}
return $columns;
} | php | public function columnsByType(int $type) : array
{
$n = $this->numColumns();
$columns = [];
for ($i = 0; $i < $n; $i++) {
if ($this->columnType($i) === $type) {
$columns[$i] = $this->column($i);
}
}
return $columns;
} | [
"public",
"function",
"columnsByType",
"(",
"int",
"$",
"type",
")",
":",
"array",
"{",
"$",
"n",
"=",
"$",
"this",
"->",
"numColumns",
"(",
")",
";",
"$",
"columns",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"n",
";",
"$",
"i",
"++",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"columnType",
"(",
"$",
"i",
")",
"===",
"$",
"type",
")",
"{",
"$",
"columns",
"[",
"$",
"i",
"]",
"=",
"$",
"this",
"->",
"column",
"(",
"$",
"i",
")",
";",
"}",
"}",
"return",
"$",
"columns",
";",
"}"
] | Return the columns that match a given data type.
@param int $type
@return array | [
"Return",
"the",
"columns",
"that",
"match",
"a",
"given",
"data",
"type",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/DataFrame.php#L212-L225 | train |
RubixML/RubixML | src/Classifiers/LogisticRegression.php | LogisticRegression.partial | public function partial(Dataset $dataset) : void
{
if (!$this->network) {
$this->train($dataset);
return;
}
if (!$dataset instanceof Labeled) {
throw new InvalidArgumentException('This estimator requires a'
. ' labeled training set.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
if ($this->logger) {
$this->logger->info('Learner init ' . Params::stringify([
'batch_size' => $this->batchSize,
'optimizer' => $this->optimizer,
'alpha' => $this->alpha,
'epochs' => $this->epochs,
'min_change' => $this->minChange,
'cost_fn' => $this->costFn,
]));
}
$n = $dataset->numRows();
$randomize = $n > $this->batchSize ? true : false;
$previous = INF;
for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
if ($randomize) {
$dataset->randomize();
}
$batches = $dataset->batch($this->batchSize);
$loss = 0.;
foreach ($batches as $batch) {
$loss += $this->network->roundtrip($batch);
}
$loss /= $n;
$this->steps[] = $loss;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete, loss=$loss");
}
if (is_nan($loss)) {
break 1;
}
if (abs($previous - $loss) < $this->minChange) {
break 1;
}
$previous = $loss;
}
if ($this->logger) {
$this->logger->info('Training complete');
}
} | php | public function partial(Dataset $dataset) : void
{
if (!$this->network) {
$this->train($dataset);
return;
}
if (!$dataset instanceof Labeled) {
throw new InvalidArgumentException('This estimator requires a'
. ' labeled training set.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
if ($this->logger) {
$this->logger->info('Learner init ' . Params::stringify([
'batch_size' => $this->batchSize,
'optimizer' => $this->optimizer,
'alpha' => $this->alpha,
'epochs' => $this->epochs,
'min_change' => $this->minChange,
'cost_fn' => $this->costFn,
]));
}
$n = $dataset->numRows();
$randomize = $n > $this->batchSize ? true : false;
$previous = INF;
for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
if ($randomize) {
$dataset->randomize();
}
$batches = $dataset->batch($this->batchSize);
$loss = 0.;
foreach ($batches as $batch) {
$loss += $this->network->roundtrip($batch);
}
$loss /= $n;
$this->steps[] = $loss;
if ($this->logger) {
$this->logger->info("Epoch $epoch complete, loss=$loss");
}
if (is_nan($loss)) {
break 1;
}
if (abs($previous - $loss) < $this->minChange) {
break 1;
}
$previous = $loss;
}
if ($this->logger) {
$this->logger->info('Training complete');
}
} | [
"public",
"function",
"partial",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"network",
")",
"{",
"$",
"this",
"->",
"train",
"(",
"$",
"dataset",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"$",
"dataset",
"instanceof",
"Labeled",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'This estimator requires a'",
".",
"' labeled training set.'",
")",
";",
"}",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Learner init '",
".",
"Params",
"::",
"stringify",
"(",
"[",
"'batch_size'",
"=>",
"$",
"this",
"->",
"batchSize",
",",
"'optimizer'",
"=>",
"$",
"this",
"->",
"optimizer",
",",
"'alpha'",
"=>",
"$",
"this",
"->",
"alpha",
",",
"'epochs'",
"=>",
"$",
"this",
"->",
"epochs",
",",
"'min_change'",
"=>",
"$",
"this",
"->",
"minChange",
",",
"'cost_fn'",
"=>",
"$",
"this",
"->",
"costFn",
",",
"]",
")",
")",
";",
"}",
"$",
"n",
"=",
"$",
"dataset",
"->",
"numRows",
"(",
")",
";",
"$",
"randomize",
"=",
"$",
"n",
">",
"$",
"this",
"->",
"batchSize",
"?",
"true",
":",
"false",
";",
"$",
"previous",
"=",
"INF",
";",
"for",
"(",
"$",
"epoch",
"=",
"1",
";",
"$",
"epoch",
"<=",
"$",
"this",
"->",
"epochs",
";",
"$",
"epoch",
"++",
")",
"{",
"if",
"(",
"$",
"randomize",
")",
"{",
"$",
"dataset",
"->",
"randomize",
"(",
")",
";",
"}",
"$",
"batches",
"=",
"$",
"dataset",
"->",
"batch",
"(",
"$",
"this",
"->",
"batchSize",
")",
";",
"$",
"loss",
"=",
"0.",
";",
"foreach",
"(",
"$",
"batches",
"as",
"$",
"batch",
")",
"{",
"$",
"loss",
"+=",
"$",
"this",
"->",
"network",
"->",
"roundtrip",
"(",
"$",
"batch",
")",
";",
"}",
"$",
"loss",
"/=",
"$",
"n",
";",
"$",
"this",
"->",
"steps",
"[",
"]",
"=",
"$",
"loss",
";",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"\"Epoch $epoch complete, loss=$loss\"",
")",
";",
"}",
"if",
"(",
"is_nan",
"(",
"$",
"loss",
")",
")",
"{",
"break",
"1",
";",
"}",
"if",
"(",
"abs",
"(",
"$",
"previous",
"-",
"$",
"loss",
")",
"<",
"$",
"this",
"->",
"minChange",
")",
"{",
"break",
"1",
";",
"}",
"$",
"previous",
"=",
"$",
"loss",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"logger",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'Training complete'",
")",
";",
"}",
"}"
] | Perform mini-batch gradient descent with given optimizer over the training
set and update the input weights accordingly.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Perform",
"mini",
"-",
"batch",
"gradient",
"descent",
"with",
"given",
"optimizer",
"over",
"the",
"training",
"set",
"and",
"update",
"the",
"input",
"weights",
"accordingly",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/LogisticRegression.php#L237-L304 | train |
RubixML/RubixML | src/Regressors/GradientBoost.php | GradientBoost.compatibility | public function compatibility() : array
{
$compatibility = array_intersect($this->base->compatibility(), $this->booster->compatibility());
return array_values($compatibility);
} | php | public function compatibility() : array
{
$compatibility = array_intersect($this->base->compatibility(), $this->booster->compatibility());
return array_values($compatibility);
} | [
"public",
"function",
"compatibility",
"(",
")",
":",
"array",
"{",
"$",
"compatibility",
"=",
"array_intersect",
"(",
"$",
"this",
"->",
"base",
"->",
"compatibility",
"(",
")",
",",
"$",
"this",
"->",
"booster",
"->",
"compatibility",
"(",
")",
")",
";",
"return",
"array_values",
"(",
"$",
"compatibility",
")",
";",
"}"
] | Return the data types that this estimator is compatible with.
@return int[] | [
"Return",
"the",
"data",
"types",
"that",
"this",
"estimator",
"is",
"compatible",
"with",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/GradientBoost.php#L192-L197 | train |
RubixML/RubixML | src/Regressors/GradientBoost.php | GradientBoost.predict | public function predict(Dataset $dataset) : array
{
if (empty($this->ensemble)) {
throw new RuntimeException('Estimator has not been trained.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$predictions = $this->base->predict($dataset);
foreach ($this->ensemble as $estimator) {
foreach ($estimator->predict($dataset) as $j => $prediction) {
$predictions[$j] += $this->rate * $prediction;
}
}
return $predictions;
} | php | public function predict(Dataset $dataset) : array
{
if (empty($this->ensemble)) {
throw new RuntimeException('Estimator has not been trained.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$predictions = $this->base->predict($dataset);
foreach ($this->ensemble as $estimator) {
foreach ($estimator->predict($dataset) as $j => $prediction) {
$predictions[$j] += $this->rate * $prediction;
}
}
return $predictions;
} | [
"public",
"function",
"predict",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"array",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"ensemble",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Estimator has not been trained.'",
")",
";",
"}",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"$",
"predictions",
"=",
"$",
"this",
"->",
"base",
"->",
"predict",
"(",
"$",
"dataset",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"ensemble",
"as",
"$",
"estimator",
")",
"{",
"foreach",
"(",
"$",
"estimator",
"->",
"predict",
"(",
"$",
"dataset",
")",
"as",
"$",
"j",
"=>",
"$",
"prediction",
")",
"{",
"$",
"predictions",
"[",
"$",
"j",
"]",
"+=",
"$",
"this",
"->",
"rate",
"*",
"$",
"prediction",
";",
"}",
"}",
"return",
"$",
"predictions",
";",
"}"
] | Make a prediction from a dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \RuntimeException
@throws \InvalidArgumentException
@return array | [
"Make",
"a",
"prediction",
"from",
"a",
"dataset",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/GradientBoost.php#L335-L352 | train |
RubixML/RubixML | src/Embedders/TSNE.php | TSNE.pairwiseDistances | protected function pairwiseDistances(Matrix $samples) : Matrix
{
$distances = [];
foreach ($samples as $a) {
$temp = [];
foreach ($samples as $b) {
$temp[] = $this->kernel->compute($a, $b);
}
$distances[] = $temp;
}
return Matrix::quick($distances);
} | php | protected function pairwiseDistances(Matrix $samples) : Matrix
{
$distances = [];
foreach ($samples as $a) {
$temp = [];
foreach ($samples as $b) {
$temp[] = $this->kernel->compute($a, $b);
}
$distances[] = $temp;
}
return Matrix::quick($distances);
} | [
"protected",
"function",
"pairwiseDistances",
"(",
"Matrix",
"$",
"samples",
")",
":",
"Matrix",
"{",
"$",
"distances",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"samples",
"as",
"$",
"a",
")",
"{",
"$",
"temp",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"samples",
"as",
"$",
"b",
")",
"{",
"$",
"temp",
"[",
"]",
"=",
"$",
"this",
"->",
"kernel",
"->",
"compute",
"(",
"$",
"a",
",",
"$",
"b",
")",
";",
"}",
"$",
"distances",
"[",
"]",
"=",
"$",
"temp",
";",
"}",
"return",
"Matrix",
"::",
"quick",
"(",
"$",
"distances",
")",
";",
"}"
] | Calculate the pairwise distances for each sample.
@param \Rubix\Tensor\Matrix $samples
@return \Rubix\Tensor\Matrix | [
"Calculate",
"the",
"pairwise",
"distances",
"for",
"each",
"sample",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Embedders/TSNE.php#L373-L388 | train |
RubixML/RubixML | src/Embedders/TSNE.php | TSNE.highAffinities | protected function highAffinities(Matrix $distances) : Matrix
{
$zeros = array_fill(0, count($distances), 0);
$p = [];
foreach ($distances as $i => $row) {
$affinities = $zeros;
$minBeta = -INF;
$maxBeta = INF;
$beta = 1.;
for ($l = 0; $l < self::BINARY_PRECISION; $l++) {
$affinities = [];
$pSigma = 0.;
foreach ($row as $j => $distance) {
if ($i !== $j) {
$affinity = exp(-$distance * $beta);
} else {
$affinity = 0.;
}
$affinities[] = $affinity;
$pSigma += $affinity;
}
if ($pSigma === 0.) {
$pSigma = EPSILON;
}
$distSigma = 0.;
foreach ($affinities as $j => &$prob) {
$prob /= $pSigma;
$distSigma += $row[$j] * $prob;
}
$entropy = log($pSigma) + $beta * $distSigma;
$diff = $entropy - $this->entropy;
if (abs($diff) < self::SEARCH_TOLERANCE) {
break 1;
}
if ($diff > 0.) {
$minBeta = $beta;
if ($maxBeta === INF) {
$beta *= 2.;
} else {
$beta = ($beta + $maxBeta) / 2.;
}
} else {
$maxBeta = $beta;
if ($minBeta === -INF) {
$beta /= 2.;
} else {
$beta = ($beta + $minBeta) / 2.;
}
}
}
$p[] = $affinities;
}
$p = Matrix::quick($p);
$pHat = $p->add($p->transpose());
$sigma = $pHat->sum()
->clipLower(EPSILON);
return $pHat->divide($sigma);
} | php | protected function highAffinities(Matrix $distances) : Matrix
{
$zeros = array_fill(0, count($distances), 0);
$p = [];
foreach ($distances as $i => $row) {
$affinities = $zeros;
$minBeta = -INF;
$maxBeta = INF;
$beta = 1.;
for ($l = 0; $l < self::BINARY_PRECISION; $l++) {
$affinities = [];
$pSigma = 0.;
foreach ($row as $j => $distance) {
if ($i !== $j) {
$affinity = exp(-$distance * $beta);
} else {
$affinity = 0.;
}
$affinities[] = $affinity;
$pSigma += $affinity;
}
if ($pSigma === 0.) {
$pSigma = EPSILON;
}
$distSigma = 0.;
foreach ($affinities as $j => &$prob) {
$prob /= $pSigma;
$distSigma += $row[$j] * $prob;
}
$entropy = log($pSigma) + $beta * $distSigma;
$diff = $entropy - $this->entropy;
if (abs($diff) < self::SEARCH_TOLERANCE) {
break 1;
}
if ($diff > 0.) {
$minBeta = $beta;
if ($maxBeta === INF) {
$beta *= 2.;
} else {
$beta = ($beta + $maxBeta) / 2.;
}
} else {
$maxBeta = $beta;
if ($minBeta === -INF) {
$beta /= 2.;
} else {
$beta = ($beta + $minBeta) / 2.;
}
}
}
$p[] = $affinities;
}
$p = Matrix::quick($p);
$pHat = $p->add($p->transpose());
$sigma = $pHat->sum()
->clipLower(EPSILON);
return $pHat->divide($sigma);
} | [
"protected",
"function",
"highAffinities",
"(",
"Matrix",
"$",
"distances",
")",
":",
"Matrix",
"{",
"$",
"zeros",
"=",
"array_fill",
"(",
"0",
",",
"count",
"(",
"$",
"distances",
")",
",",
"0",
")",
";",
"$",
"p",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"distances",
"as",
"$",
"i",
"=>",
"$",
"row",
")",
"{",
"$",
"affinities",
"=",
"$",
"zeros",
";",
"$",
"minBeta",
"=",
"-",
"INF",
";",
"$",
"maxBeta",
"=",
"INF",
";",
"$",
"beta",
"=",
"1.",
";",
"for",
"(",
"$",
"l",
"=",
"0",
";",
"$",
"l",
"<",
"self",
"::",
"BINARY_PRECISION",
";",
"$",
"l",
"++",
")",
"{",
"$",
"affinities",
"=",
"[",
"]",
";",
"$",
"pSigma",
"=",
"0.",
";",
"foreach",
"(",
"$",
"row",
"as",
"$",
"j",
"=>",
"$",
"distance",
")",
"{",
"if",
"(",
"$",
"i",
"!==",
"$",
"j",
")",
"{",
"$",
"affinity",
"=",
"exp",
"(",
"-",
"$",
"distance",
"*",
"$",
"beta",
")",
";",
"}",
"else",
"{",
"$",
"affinity",
"=",
"0.",
";",
"}",
"$",
"affinities",
"[",
"]",
"=",
"$",
"affinity",
";",
"$",
"pSigma",
"+=",
"$",
"affinity",
";",
"}",
"if",
"(",
"$",
"pSigma",
"===",
"0.",
")",
"{",
"$",
"pSigma",
"=",
"EPSILON",
";",
"}",
"$",
"distSigma",
"=",
"0.",
";",
"foreach",
"(",
"$",
"affinities",
"as",
"$",
"j",
"=>",
"&",
"$",
"prob",
")",
"{",
"$",
"prob",
"/=",
"$",
"pSigma",
";",
"$",
"distSigma",
"+=",
"$",
"row",
"[",
"$",
"j",
"]",
"*",
"$",
"prob",
";",
"}",
"$",
"entropy",
"=",
"log",
"(",
"$",
"pSigma",
")",
"+",
"$",
"beta",
"*",
"$",
"distSigma",
";",
"$",
"diff",
"=",
"$",
"entropy",
"-",
"$",
"this",
"->",
"entropy",
";",
"if",
"(",
"abs",
"(",
"$",
"diff",
")",
"<",
"self",
"::",
"SEARCH_TOLERANCE",
")",
"{",
"break",
"1",
";",
"}",
"if",
"(",
"$",
"diff",
">",
"0.",
")",
"{",
"$",
"minBeta",
"=",
"$",
"beta",
";",
"if",
"(",
"$",
"maxBeta",
"===",
"INF",
")",
"{",
"$",
"beta",
"*=",
"2.",
";",
"}",
"else",
"{",
"$",
"beta",
"=",
"(",
"$",
"beta",
"+",
"$",
"maxBeta",
")",
"/",
"2.",
";",
"}",
"}",
"else",
"{",
"$",
"maxBeta",
"=",
"$",
"beta",
";",
"if",
"(",
"$",
"minBeta",
"===",
"-",
"INF",
")",
"{",
"$",
"beta",
"/=",
"2.",
";",
"}",
"else",
"{",
"$",
"beta",
"=",
"(",
"$",
"beta",
"+",
"$",
"minBeta",
")",
"/",
"2.",
";",
"}",
"}",
"}",
"$",
"p",
"[",
"]",
"=",
"$",
"affinities",
";",
"}",
"$",
"p",
"=",
"Matrix",
"::",
"quick",
"(",
"$",
"p",
")",
";",
"$",
"pHat",
"=",
"$",
"p",
"->",
"add",
"(",
"$",
"p",
"->",
"transpose",
"(",
")",
")",
";",
"$",
"sigma",
"=",
"$",
"pHat",
"->",
"sum",
"(",
")",
"->",
"clipLower",
"(",
"EPSILON",
")",
";",
"return",
"$",
"pHat",
"->",
"divide",
"(",
"$",
"sigma",
")",
";",
"}"
] | Calculate the joint likelihood of each sample in the high dimensional
space as being nearest neighbor to each other sample.
@param \Rubix\Tensor\Matrix $distances
@return \Rubix\Tensor\Matrix | [
"Calculate",
"the",
"joint",
"likelihood",
"of",
"each",
"sample",
"in",
"the",
"high",
"dimensional",
"space",
"as",
"being",
"nearest",
"neighbor",
"to",
"each",
"other",
"sample",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Embedders/TSNE.php#L397-L473 | train |
RubixML/RubixML | src/Embedders/TSNE.php | TSNE.gradient | protected function gradient(Matrix $p, Matrix $y, Matrix $distances) : Matrix
{
$q = $distances->square()
->divide($this->degrees)
->add(1.)
->pow((1. + $this->degrees) / -2.);
$qSigma = $q->sum()->multiply(2.);
$q = $q->divide($qSigma)
->clipLower(EPSILON);
$pqd = $p->subtract($q)
->multiply($distances);
$c = 2. * (1. + $this->degrees) / $this->degrees;
$gradient = [];
foreach ($pqd->asVectors() as $i => $row) {
$yHat = $y->rowAsVector($i)
->subtract($y);
$gradient[] = $row->matmul($yHat)
->multiply($c)
->row(0);
}
return Matrix::quick($gradient);
} | php | protected function gradient(Matrix $p, Matrix $y, Matrix $distances) : Matrix
{
$q = $distances->square()
->divide($this->degrees)
->add(1.)
->pow((1. + $this->degrees) / -2.);
$qSigma = $q->sum()->multiply(2.);
$q = $q->divide($qSigma)
->clipLower(EPSILON);
$pqd = $p->subtract($q)
->multiply($distances);
$c = 2. * (1. + $this->degrees) / $this->degrees;
$gradient = [];
foreach ($pqd->asVectors() as $i => $row) {
$yHat = $y->rowAsVector($i)
->subtract($y);
$gradient[] = $row->matmul($yHat)
->multiply($c)
->row(0);
}
return Matrix::quick($gradient);
} | [
"protected",
"function",
"gradient",
"(",
"Matrix",
"$",
"p",
",",
"Matrix",
"$",
"y",
",",
"Matrix",
"$",
"distances",
")",
":",
"Matrix",
"{",
"$",
"q",
"=",
"$",
"distances",
"->",
"square",
"(",
")",
"->",
"divide",
"(",
"$",
"this",
"->",
"degrees",
")",
"->",
"add",
"(",
"1.",
")",
"->",
"pow",
"(",
"(",
"1.",
"+",
"$",
"this",
"->",
"degrees",
")",
"/",
"-",
"2.",
")",
";",
"$",
"qSigma",
"=",
"$",
"q",
"->",
"sum",
"(",
")",
"->",
"multiply",
"(",
"2.",
")",
";",
"$",
"q",
"=",
"$",
"q",
"->",
"divide",
"(",
"$",
"qSigma",
")",
"->",
"clipLower",
"(",
"EPSILON",
")",
";",
"$",
"pqd",
"=",
"$",
"p",
"->",
"subtract",
"(",
"$",
"q",
")",
"->",
"multiply",
"(",
"$",
"distances",
")",
";",
"$",
"c",
"=",
"2.",
"*",
"(",
"1.",
"+",
"$",
"this",
"->",
"degrees",
")",
"/",
"$",
"this",
"->",
"degrees",
";",
"$",
"gradient",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"pqd",
"->",
"asVectors",
"(",
")",
"as",
"$",
"i",
"=>",
"$",
"row",
")",
"{",
"$",
"yHat",
"=",
"$",
"y",
"->",
"rowAsVector",
"(",
"$",
"i",
")",
"->",
"subtract",
"(",
"$",
"y",
")",
";",
"$",
"gradient",
"[",
"]",
"=",
"$",
"row",
"->",
"matmul",
"(",
"$",
"yHat",
")",
"->",
"multiply",
"(",
"$",
"c",
")",
"->",
"row",
"(",
"0",
")",
";",
"}",
"return",
"Matrix",
"::",
"quick",
"(",
"$",
"gradient",
")",
";",
"}"
] | Compute the gradient of the KL Divergence cost function with respect to
the embedding.
@param \Rubix\Tensor\Matrix $p
@param \Rubix\Tensor\Matrix $y
@param \Rubix\Tensor\Matrix $distances
@return \Rubix\Tensor\Matrix | [
"Compute",
"the",
"gradient",
"of",
"the",
"KL",
"Divergence",
"cost",
"function",
"with",
"respect",
"to",
"the",
"embedding",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Embedders/TSNE.php#L484-L513 | train |
RubixML/RubixML | src/BootstrapAggregator.php | BootstrapAggregator.train | public function train(Dataset $dataset) : void
{
if ($this->type() === self::CLASSIFIER or $this->type() === self::REGRESSOR) {
if (!$dataset instanceof Labeled) {
throw new InvalidArgumentException('This estimator requires a'
. ' labeled training set.');
}
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$p = (int) round($this->ratio * $dataset->numRows());
$this->ensemble = [];
Loop::run(function () use ($dataset, $p) {
$pool = new DefaultPool($this->workers);
$coroutines = [];
for ($i = 0; $i < $this->estimators; $i++) {
$estimator = clone $this->base;
$subset = $dataset->randomSubsetWithReplacement($p);
$task = new CallableTask(
[$this, '_train'],
[$estimator, $subset]
);
$coroutines[] = call(function () use ($pool, $task) {
return yield $pool->enqueue($task);
});
}
$this->ensemble = yield all($coroutines);
return yield $pool->shutdown();
});
} | php | public function train(Dataset $dataset) : void
{
if ($this->type() === self::CLASSIFIER or $this->type() === self::REGRESSOR) {
if (!$dataset instanceof Labeled) {
throw new InvalidArgumentException('This estimator requires a'
. ' labeled training set.');
}
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$p = (int) round($this->ratio * $dataset->numRows());
$this->ensemble = [];
Loop::run(function () use ($dataset, $p) {
$pool = new DefaultPool($this->workers);
$coroutines = [];
for ($i = 0; $i < $this->estimators; $i++) {
$estimator = clone $this->base;
$subset = $dataset->randomSubsetWithReplacement($p);
$task = new CallableTask(
[$this, '_train'],
[$estimator, $subset]
);
$coroutines[] = call(function () use ($pool, $task) {
return yield $pool->enqueue($task);
});
}
$this->ensemble = yield all($coroutines);
return yield $pool->shutdown();
});
} | [
"public",
"function",
"train",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"void",
"{",
"if",
"(",
"$",
"this",
"->",
"type",
"(",
")",
"===",
"self",
"::",
"CLASSIFIER",
"or",
"$",
"this",
"->",
"type",
"(",
")",
"===",
"self",
"::",
"REGRESSOR",
")",
"{",
"if",
"(",
"!",
"$",
"dataset",
"instanceof",
"Labeled",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'This estimator requires a'",
".",
"' labeled training set.'",
")",
";",
"}",
"}",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"$",
"p",
"=",
"(",
"int",
")",
"round",
"(",
"$",
"this",
"->",
"ratio",
"*",
"$",
"dataset",
"->",
"numRows",
"(",
")",
")",
";",
"$",
"this",
"->",
"ensemble",
"=",
"[",
"]",
";",
"Loop",
"::",
"run",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"dataset",
",",
"$",
"p",
")",
"{",
"$",
"pool",
"=",
"new",
"DefaultPool",
"(",
"$",
"this",
"->",
"workers",
")",
";",
"$",
"coroutines",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"this",
"->",
"estimators",
";",
"$",
"i",
"++",
")",
"{",
"$",
"estimator",
"=",
"clone",
"$",
"this",
"->",
"base",
";",
"$",
"subset",
"=",
"$",
"dataset",
"->",
"randomSubsetWithReplacement",
"(",
"$",
"p",
")",
";",
"$",
"task",
"=",
"new",
"CallableTask",
"(",
"[",
"$",
"this",
",",
"'_train'",
"]",
",",
"[",
"$",
"estimator",
",",
"$",
"subset",
"]",
")",
";",
"$",
"coroutines",
"[",
"]",
"=",
"call",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"pool",
",",
"$",
"task",
")",
"{",
"return",
"yield",
"$",
"pool",
"->",
"enqueue",
"(",
"$",
"task",
")",
";",
"}",
")",
";",
"}",
"$",
"this",
"->",
"ensemble",
"=",
"yield",
"all",
"(",
"$",
"coroutines",
")",
";",
"return",
"yield",
"$",
"pool",
"->",
"shutdown",
"(",
")",
";",
"}",
")",
";",
"}"
] | Instantiate and train each base estimator in the ensemble on a bootstrap
training set.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException | [
"Instantiate",
"and",
"train",
"each",
"base",
"estimator",
"in",
"the",
"ensemble",
"on",
"a",
"bootstrap",
"training",
"set",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/BootstrapAggregator.php#L141-L180 | train |
RubixML/RubixML | src/Graph/Nodes/Isolator.php | Isolator.split | public static function split(Dataset $dataset) : self
{
$column = rand(0, $dataset->numColumns() - 1);
$sample = $dataset[rand(0, count($dataset) - 1)];
$value = $sample[$column];
$groups = $dataset->partition($column, $value);
return new self($column, $value, $groups);
} | php | public static function split(Dataset $dataset) : self
{
$column = rand(0, $dataset->numColumns() - 1);
$sample = $dataset[rand(0, count($dataset) - 1)];
$value = $sample[$column];
$groups = $dataset->partition($column, $value);
return new self($column, $value, $groups);
} | [
"public",
"static",
"function",
"split",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"self",
"{",
"$",
"column",
"=",
"rand",
"(",
"0",
",",
"$",
"dataset",
"->",
"numColumns",
"(",
")",
"-",
"1",
")",
";",
"$",
"sample",
"=",
"$",
"dataset",
"[",
"rand",
"(",
"0",
",",
"count",
"(",
"$",
"dataset",
")",
"-",
"1",
")",
"]",
";",
"$",
"value",
"=",
"$",
"sample",
"[",
"$",
"column",
"]",
";",
"$",
"groups",
"=",
"$",
"dataset",
"->",
"partition",
"(",
"$",
"column",
",",
"$",
"value",
")",
";",
"return",
"new",
"self",
"(",
"$",
"column",
",",
"$",
"value",
",",
"$",
"groups",
")",
";",
"}"
] | Factory method to build a isolator node from a dataset
using a random split of the dataset.
@param \Rubix\ML\Datasets\Dataset $dataset
@return self | [
"Factory",
"method",
"to",
"build",
"a",
"isolator",
"node",
"from",
"a",
"dataset",
"using",
"a",
"random",
"split",
"of",
"the",
"dataset",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/Isolator.php#L48-L59 | train |
RubixML/RubixML | src/Clusterers/MeanShift.php | MeanShift.estimateRadius | public static function estimateRadius(Dataset $dataset, float $percentile = 30., ?Distance $kernel = null) : float
{
if ($percentile < 0. or $percentile > 100.) {
throw new InvalidArgumentException('Percentile must be between'
. " 0 and 100, $percentile given.");
}
$kernel = $kernel ?? new Euclidean();
$distances = [];
foreach ($dataset as $sampleA) {
foreach ($dataset as $sampleB) {
$distances[] = $kernel->compute($sampleA, $sampleB);
}
}
return Stats::percentile($distances, $percentile);
} | php | public static function estimateRadius(Dataset $dataset, float $percentile = 30., ?Distance $kernel = null) : float
{
if ($percentile < 0. or $percentile > 100.) {
throw new InvalidArgumentException('Percentile must be between'
. " 0 and 100, $percentile given.");
}
$kernel = $kernel ?? new Euclidean();
$distances = [];
foreach ($dataset as $sampleA) {
foreach ($dataset as $sampleB) {
$distances[] = $kernel->compute($sampleA, $sampleB);
}
}
return Stats::percentile($distances, $percentile);
} | [
"public",
"static",
"function",
"estimateRadius",
"(",
"Dataset",
"$",
"dataset",
",",
"float",
"$",
"percentile",
"=",
"30.",
",",
"?",
"Distance",
"$",
"kernel",
"=",
"null",
")",
":",
"float",
"{",
"if",
"(",
"$",
"percentile",
"<",
"0.",
"or",
"$",
"percentile",
">",
"100.",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Percentile must be between'",
".",
"\" 0 and 100, $percentile given.\"",
")",
";",
"}",
"$",
"kernel",
"=",
"$",
"kernel",
"??",
"new",
"Euclidean",
"(",
")",
";",
"$",
"distances",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"dataset",
"as",
"$",
"sampleA",
")",
"{",
"foreach",
"(",
"$",
"dataset",
"as",
"$",
"sampleB",
")",
"{",
"$",
"distances",
"[",
"]",
"=",
"$",
"kernel",
"->",
"compute",
"(",
"$",
"sampleA",
",",
"$",
"sampleB",
")",
";",
"}",
"}",
"return",
"Stats",
"::",
"percentile",
"(",
"$",
"distances",
",",
"$",
"percentile",
")",
";",
"}"
] | Estimate the radius of a cluster that encompasses a certain percentage of
the total training samples.
> **Note**: Since radius estimation scales quadratically in the number of
samples, for large datasets you can speed up the process by running it on
a sample subset of the training data.
@param \Rubix\ML\Datasets\Dataset $dataset
@param float $percentile
@param \Rubix\ML\Kernels\Distance\Distance|null $kernel
@throws \InvalidArgumentException
@return float | [
"Estimate",
"the",
"radius",
"of",
"a",
"cluster",
"that",
"encompasses",
"a",
"certain",
"percentage",
"of",
"the",
"total",
"training",
"samples",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/MeanShift.php#L137-L155 | train |
RubixML/RubixML | src/Clusterers/MeanShift.php | MeanShift.assign | protected function assign(array $sample) : int
{
$bestDistance = INF;
$bestCluster = -1;
foreach ($this->centroids as $cluster => $centroid) {
$distance = $this->kernel->compute($sample, $centroid);
if ($distance < $bestDistance) {
$bestDistance = $distance;
$bestCluster = $cluster;
}
}
return (int) $bestCluster;
} | php | protected function assign(array $sample) : int
{
$bestDistance = INF;
$bestCluster = -1;
foreach ($this->centroids as $cluster => $centroid) {
$distance = $this->kernel->compute($sample, $centroid);
if ($distance < $bestDistance) {
$bestDistance = $distance;
$bestCluster = $cluster;
}
}
return (int) $bestCluster;
} | [
"protected",
"function",
"assign",
"(",
"array",
"$",
"sample",
")",
":",
"int",
"{",
"$",
"bestDistance",
"=",
"INF",
";",
"$",
"bestCluster",
"=",
"-",
"1",
";",
"foreach",
"(",
"$",
"this",
"->",
"centroids",
"as",
"$",
"cluster",
"=>",
"$",
"centroid",
")",
"{",
"$",
"distance",
"=",
"$",
"this",
"->",
"kernel",
"->",
"compute",
"(",
"$",
"sample",
",",
"$",
"centroid",
")",
";",
"if",
"(",
"$",
"distance",
"<",
"$",
"bestDistance",
")",
"{",
"$",
"bestDistance",
"=",
"$",
"distance",
";",
"$",
"bestCluster",
"=",
"$",
"cluster",
";",
"}",
"}",
"return",
"(",
"int",
")",
"$",
"bestCluster",
";",
"}"
] | Label a given sample based on its distance from a particular centroid.
@param array $sample
@return int | [
"Label",
"a",
"given",
"sample",
"based",
"on",
"its",
"distance",
"from",
"a",
"particular",
"centroid",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/MeanShift.php#L403-L418 | train |
RubixML/RubixML | src/Clusterers/MeanShift.php | MeanShift.membership | protected function membership(array $sample) : array
{
$membership = $distances = [];
foreach ($this->centroids as $centroid) {
$distances[] = $this->kernel->compute($sample, $centroid);
}
$total = array_sum($distances) ?: EPSILON;
foreach ($distances as $distance) {
$membership[] = $distance / $total;
}
return $membership;
} | php | protected function membership(array $sample) : array
{
$membership = $distances = [];
foreach ($this->centroids as $centroid) {
$distances[] = $this->kernel->compute($sample, $centroid);
}
$total = array_sum($distances) ?: EPSILON;
foreach ($distances as $distance) {
$membership[] = $distance / $total;
}
return $membership;
} | [
"protected",
"function",
"membership",
"(",
"array",
"$",
"sample",
")",
":",
"array",
"{",
"$",
"membership",
"=",
"$",
"distances",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"centroids",
"as",
"$",
"centroid",
")",
"{",
"$",
"distances",
"[",
"]",
"=",
"$",
"this",
"->",
"kernel",
"->",
"compute",
"(",
"$",
"sample",
",",
"$",
"centroid",
")",
";",
"}",
"$",
"total",
"=",
"array_sum",
"(",
"$",
"distances",
")",
"?",
":",
"EPSILON",
";",
"foreach",
"(",
"$",
"distances",
"as",
"$",
"distance",
")",
"{",
"$",
"membership",
"[",
"]",
"=",
"$",
"distance",
"/",
"$",
"total",
";",
"}",
"return",
"$",
"membership",
";",
"}"
] | Return the membership of a sample to each of the centroids.
@param array $sample
@return array | [
"Return",
"the",
"membership",
"of",
"a",
"sample",
"to",
"each",
"of",
"the",
"centroids",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/MeanShift.php#L426-L441 | train |
RubixML/RubixML | src/AnomalyDetectors/LODA.php | LODA.logLikelihood | protected function logLikelihood(Matrix $z) : array
{
$likelihoods = array_fill(0, $z->n(), 0.);
foreach ($z as $i => $values) {
[$edges, $counts, $densities] = $this->histograms[$i];
foreach ($values as $j => $value) {
foreach ($edges as $k => $edge) {
if ($value < $edge) {
$likelihoods[$j] += $densities[$k];
break 1;
}
}
}
}
foreach ($likelihoods as &$likelihood) {
$likelihood /= $this->estimators;
}
return $likelihoods;
} | php | protected function logLikelihood(Matrix $z) : array
{
$likelihoods = array_fill(0, $z->n(), 0.);
foreach ($z as $i => $values) {
[$edges, $counts, $densities] = $this->histograms[$i];
foreach ($values as $j => $value) {
foreach ($edges as $k => $edge) {
if ($value < $edge) {
$likelihoods[$j] += $densities[$k];
break 1;
}
}
}
}
foreach ($likelihoods as &$likelihood) {
$likelihood /= $this->estimators;
}
return $likelihoods;
} | [
"protected",
"function",
"logLikelihood",
"(",
"Matrix",
"$",
"z",
")",
":",
"array",
"{",
"$",
"likelihoods",
"=",
"array_fill",
"(",
"0",
",",
"$",
"z",
"->",
"n",
"(",
")",
",",
"0.",
")",
";",
"foreach",
"(",
"$",
"z",
"as",
"$",
"i",
"=>",
"$",
"values",
")",
"{",
"[",
"$",
"edges",
",",
"$",
"counts",
",",
"$",
"densities",
"]",
"=",
"$",
"this",
"->",
"histograms",
"[",
"$",
"i",
"]",
";",
"foreach",
"(",
"$",
"values",
"as",
"$",
"j",
"=>",
"$",
"value",
")",
"{",
"foreach",
"(",
"$",
"edges",
"as",
"$",
"k",
"=>",
"$",
"edge",
")",
"{",
"if",
"(",
"$",
"value",
"<",
"$",
"edge",
")",
"{",
"$",
"likelihoods",
"[",
"$",
"j",
"]",
"+=",
"$",
"densities",
"[",
"$",
"k",
"]",
";",
"break",
"1",
";",
"}",
"}",
"}",
"}",
"foreach",
"(",
"$",
"likelihoods",
"as",
"&",
"$",
"likelihood",
")",
"{",
"$",
"likelihood",
"/=",
"$",
"this",
"->",
"estimators",
";",
"}",
"return",
"$",
"likelihoods",
";",
"}"
] | Return the negative log likelihoods of each projection.
@param \Rubix\Tensor\Matrix $z
@return array | [
"Return",
"the",
"negative",
"log",
"likelihoods",
"of",
"each",
"projection",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/AnomalyDetectors/LODA.php#L309-L332 | train |
RubixML/RubixML | src/Transformers/GaussianRandomProjector.php | GaussianRandomProjector.minDimensions | public static function minDimensions(int $n, float $maxDistortion = 0.1) : int
{
return (int) round(4. * log($n)
/ ($maxDistortion ** 2 / 2. - $maxDistortion ** 3 / 3.));
} | php | public static function minDimensions(int $n, float $maxDistortion = 0.1) : int
{
return (int) round(4. * log($n)
/ ($maxDistortion ** 2 / 2. - $maxDistortion ** 3 / 3.));
} | [
"public",
"static",
"function",
"minDimensions",
"(",
"int",
"$",
"n",
",",
"float",
"$",
"maxDistortion",
"=",
"0.1",
")",
":",
"int",
"{",
"return",
"(",
"int",
")",
"round",
"(",
"4.",
"*",
"log",
"(",
"$",
"n",
")",
"/",
"(",
"$",
"maxDistortion",
"**",
"2",
"/",
"2.",
"-",
"$",
"maxDistortion",
"**",
"3",
"/",
"3.",
")",
")",
";",
"}"
] | Calculate the minimum number of dimensions for n total samples with a
given maximum distortion using the Johnson-Lindenstrauss lemma.
@param int $n
@param float $maxDistortion
@return int | [
"Calculate",
"the",
"minimum",
"number",
"of",
"dimensions",
"for",
"n",
"total",
"samples",
"with",
"a",
"given",
"maximum",
"distortion",
"using",
"the",
"Johnson",
"-",
"Lindenstrauss",
"lemma",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Transformers/GaussianRandomProjector.php#L49-L53 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L102-L105 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L146-L149 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Unlabeled.php#L269-L280 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/ExtraTreeRegressor.php#L34-L66 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/GridSearch.php#L113-L131 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/GridSearch.php#L282-L365 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/GridSearch.php#L386-L389 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L88-L104 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L151-L160 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L169-L177 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L184-L191 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L199-L211 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L276-L283 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L346-L355 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L364-L376 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L384-L396 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L405-L417 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L425-L434 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L443-L454 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L463-L482 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L553-L576 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L584-L593 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L603-L615 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Datasets/Labeled.php#L742-L777 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/FuzzyCMeans.php#L314-L335 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/Hypersphere.php#L55-L85 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/DummyClassifier.php#L88-L98 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Classifiers/DummyClassifier.php#L106-L122 | train |
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?"
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L118-L123 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L141-L150 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L157-L166 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L174-L179 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L207-L226 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L233-L252 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Pipeline.php#L259-L264 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L55-L64 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L92-L98 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L107-L111 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L128-L133 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L140-L145 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L150-L157 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Graph/Nodes/BinaryNode.php#L162-L169 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Clusterers/KMeans.php#L366-L375 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/PersistentModel.php#L46-L56 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/PersistentModel.php#L157-L166 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Persisters/RedisDB.php#L116-L126 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Strategies/WildGuess.php#L79-L89 | train |
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",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/CrossValidation/Metrics/MCC.php#L42-L47 | train |
RubixML/RubixML | src/Regressors/Ridge.php | Ridge.predict | public function predict(Dataset $dataset) : array
{
if (!$this->weights or $this->bias === null) {
throw new RuntimeException('Estimator has not been trained.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
return Matrix::build($dataset->samples())
->dot($this->weights)
->add($this->bias)
->asArray();
} | php | public function predict(Dataset $dataset) : array
{
if (!$this->weights or $this->bias === null) {
throw new RuntimeException('Estimator has not been trained.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
return Matrix::build($dataset->samples())
->dot($this->weights)
->add($this->bias)
->asArray();
} | [
"public",
"function",
"predict",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"weights",
"or",
"$",
"this",
"->",
"bias",
"===",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Estimator has not been trained.'",
")",
";",
"}",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"return",
"Matrix",
"::",
"build",
"(",
"$",
"dataset",
"->",
"samples",
"(",
")",
")",
"->",
"dot",
"(",
"$",
"this",
"->",
"weights",
")",
"->",
"add",
"(",
"$",
"this",
"->",
"bias",
")",
"->",
"asArray",
"(",
")",
";",
"}"
] | Make a prediction based on the line calculated from the training data.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException
@throws \RuntimeException
@return array | [
"Make",
"a",
"prediction",
"based",
"on",
"the",
"line",
"calculated",
"from",
"the",
"training",
"data",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/Ridge.php#L165-L177 | train |
RubixML/RubixML | src/Regressors/MLPRegressor.php | MLPRegressor.predict | public function predict(Dataset $dataset) : array
{
if (!$this->network) {
throw new RuntimeException('The learner has not'
. ' been trained.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$xT = Matrix::quick($dataset->samples())->transpose();
return $this->network->infer($xT)->row(0);
} | php | public function predict(Dataset $dataset) : array
{
if (!$this->network) {
throw new RuntimeException('The learner has not'
. ' been trained.');
}
DatasetIsCompatibleWithEstimator::check($dataset, $this);
$xT = Matrix::quick($dataset->samples())->transpose();
return $this->network->infer($xT)->row(0);
} | [
"public",
"function",
"predict",
"(",
"Dataset",
"$",
"dataset",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"network",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'The learner has not'",
".",
"' been trained.'",
")",
";",
"}",
"DatasetIsCompatibleWithEstimator",
"::",
"check",
"(",
"$",
"dataset",
",",
"$",
"this",
")",
";",
"$",
"xT",
"=",
"Matrix",
"::",
"quick",
"(",
"$",
"dataset",
"->",
"samples",
"(",
")",
")",
"->",
"transpose",
"(",
")",
";",
"return",
"$",
"this",
"->",
"network",
"->",
"infer",
"(",
"$",
"xT",
")",
"->",
"row",
"(",
"0",
")",
";",
"}"
] | Feed a sample through the network and make a prediction based on the
activation of the output neuron.
@param \Rubix\ML\Datasets\Dataset $dataset
@throws \InvalidArgumentException
@throws \RuntimeException
@return array | [
"Feed",
"a",
"sample",
"through",
"the",
"network",
"and",
"make",
"a",
"prediction",
"based",
"on",
"the",
"activation",
"of",
"the",
"output",
"neuron",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Regressors/MLPRegressor.php#L440-L452 | train |
RubixML/RubixML | src/NeuralNet/Layers/Dropout.php | Dropout.back | public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred
{
if (!$this->mask) {
throw new RuntimeException('Must perform forward pass before'
. ' backpropagating.');
}
$mask = $this->mask;
unset($this->mask);
return new Deferred(function () use ($prevGradient, $mask) {
return $prevGradient->result()->multiply($mask);
});
} | php | public function back(Deferred $prevGradient, Optimizer $optimizer) : Deferred
{
if (!$this->mask) {
throw new RuntimeException('Must perform forward pass before'
. ' backpropagating.');
}
$mask = $this->mask;
unset($this->mask);
return new Deferred(function () use ($prevGradient, $mask) {
return $prevGradient->result()->multiply($mask);
});
} | [
"public",
"function",
"back",
"(",
"Deferred",
"$",
"prevGradient",
",",
"Optimizer",
"$",
"optimizer",
")",
":",
"Deferred",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"mask",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Must perform forward pass before'",
".",
"' backpropagating.'",
")",
";",
"}",
"$",
"mask",
"=",
"$",
"this",
"->",
"mask",
";",
"unset",
"(",
"$",
"this",
"->",
"mask",
")",
";",
"return",
"new",
"Deferred",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"prevGradient",
",",
"$",
"mask",
")",
"{",
"return",
"$",
"prevGradient",
"->",
"result",
"(",
")",
"->",
"multiply",
"(",
"$",
"mask",
")",
";",
"}",
")",
";",
"}"
] | Calculate the gradients of the layer and update the parameters.
@param \Rubix\ML\NeuralNet\Deferred $prevGradient
@param \Rubix\ML\NeuralNet\Optimizers\Optimizer $optimizer
@throws \RuntimeException
@return \Rubix\ML\NeuralNet\Deferred | [
"Calculate",
"the",
"gradients",
"of",
"the",
"layer",
"and",
"update",
"the",
"parameters",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/NeuralNet/Layers/Dropout.php#L136-L150 | train |
RubixML/RubixML | src/Kernels/Distance/Minkowski.php | Minkowski.compute | public function compute(array $a, array $b) : float
{
$distance = 0.;
foreach ($a as $i => $value) {
$distance += abs($value - $b[$i]) ** $this->lambda;
}
return $distance ** $this->inverse;
} | php | public function compute(array $a, array $b) : float
{
$distance = 0.;
foreach ($a as $i => $value) {
$distance += abs($value - $b[$i]) ** $this->lambda;
}
return $distance ** $this->inverse;
} | [
"public",
"function",
"compute",
"(",
"array",
"$",
"a",
",",
"array",
"$",
"b",
")",
":",
"float",
"{",
"$",
"distance",
"=",
"0.",
";",
"foreach",
"(",
"$",
"a",
"as",
"$",
"i",
"=>",
"$",
"value",
")",
"{",
"$",
"distance",
"+=",
"abs",
"(",
"$",
"value",
"-",
"$",
"b",
"[",
"$",
"i",
"]",
")",
"**",
"$",
"this",
"->",
"lambda",
";",
"}",
"return",
"$",
"distance",
"**",
"$",
"this",
"->",
"inverse",
";",
"}"
] | Compute the distance given two vectors.
@param array $a
@param array $b
@return float | [
"Compute",
"the",
"distance",
"given",
"two",
"vectors",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Kernels/Distance/Minkowski.php#L59-L68 | train |
RubixML/RubixML | src/Other/Helpers/Stats.php | Stats.mean | public static function mean(array $values, ?int $n = null) : float
{
$n = $n ?? count($values);
if ($n < 1) {
throw new InvalidArgumentException('Mean is undefined for empty'
. ' set.');
}
return array_sum($values) / $n;
} | php | public static function mean(array $values, ?int $n = null) : float
{
$n = $n ?? count($values);
if ($n < 1) {
throw new InvalidArgumentException('Mean is undefined for empty'
. ' set.');
}
return array_sum($values) / $n;
} | [
"public",
"static",
"function",
"mean",
"(",
"array",
"$",
"values",
",",
"?",
"int",
"$",
"n",
"=",
"null",
")",
":",
"float",
"{",
"$",
"n",
"=",
"$",
"n",
"??",
"count",
"(",
"$",
"values",
")",
";",
"if",
"(",
"$",
"n",
"<",
"1",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Mean is undefined for empty'",
".",
"' set.'",
")",
";",
"}",
"return",
"array_sum",
"(",
"$",
"values",
")",
"/",
"$",
"n",
";",
"}"
] | Compute the population mean of a set of values.
@param array $values
@param int|null $n
@return float | [
"Compute",
"the",
"population",
"mean",
"of",
"a",
"set",
"of",
"values",
"."
] | 837385e2eb9f05c76c9522fc1673bdb87d11742d | https://github.com/RubixML/RubixML/blob/837385e2eb9f05c76c9522fc1673bdb87d11742d/src/Other/Helpers/Stats.php#L29-L39 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.