repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
php-http/multipart-stream-builder | src/MultipartStreamBuilder.php | MultipartStreamBuilder.build | public function build()
{
$streams = '';
foreach ($this->data as $data) {
// Add start and headers
$streams .= "--{$this->getBoundary()}\r\n".
$this->getHeaders($data['headers'])."\r\n";
// Convert the stream to string
/* @var $contentStream StreamInterface */
$contentStream = $data['contents'];
if ($contentStream->isSeekable()) {
$streams .= $contentStream->__toString();
} else {
$streams .= $contentStream->getContents();
}
$streams .= "\r\n";
}
// Append end
$streams .= "--{$this->getBoundary()}--\r\n";
return $this->streamFactory->createStream($streams);
} | php | public function build()
{
$streams = '';
foreach ($this->data as $data) {
// Add start and headers
$streams .= "--{$this->getBoundary()}\r\n".
$this->getHeaders($data['headers'])."\r\n";
// Convert the stream to string
/* @var $contentStream StreamInterface */
$contentStream = $data['contents'];
if ($contentStream->isSeekable()) {
$streams .= $contentStream->__toString();
} else {
$streams .= $contentStream->getContents();
}
$streams .= "\r\n";
}
// Append end
$streams .= "--{$this->getBoundary()}--\r\n";
return $this->streamFactory->createStream($streams);
} | [
"public",
"function",
"build",
"(",
")",
"{",
"$",
"streams",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"data",
"as",
"$",
"data",
")",
"{",
"// Add start and headers",
"$",
"streams",
".=",
"\"--{$this->getBoundary()}\\r\\n\"",
".",
"$",
"this",
... | Build the stream.
@return StreamInterface | [
"Build",
"the",
"stream",
"."
] | train | https://github.com/php-http/multipart-stream-builder/blob/60d37c0d405c36fd5e4693bc0cede613492e68d8/src/MultipartStreamBuilder.php#L88-L112 |
php-http/multipart-stream-builder | src/MultipartStreamBuilder.php | MultipartStreamBuilder.prepareHeaders | private function prepareHeaders($name, StreamInterface $stream, $filename, array &$headers)
{
$hasFilename = '0' === $filename || $filename;
// Set a default content-disposition header if one was not provided
if (!$this->hasHeader($headers, 'content-disposition')) {
$headers['Content-Disposition'] = sprintf('form-data; name="%s"', $name);
if ($hasFilename) {
$headers['Content-Disposition'] .= sprintf('; filename="%s"', $this->basename($filename));
}
}
// Set a default content-length header if one was not provided
if (!$this->hasHeader($headers, 'content-length')) {
if ($length = $stream->getSize()) {
$headers['Content-Length'] = (string) $length;
}
}
// Set a default Content-Type if one was not provided
if (!$this->hasHeader($headers, 'content-type') && $hasFilename) {
if ($type = $this->getMimetypeHelper()->getMimetypeFromFilename($filename)) {
$headers['Content-Type'] = $type;
}
}
} | php | private function prepareHeaders($name, StreamInterface $stream, $filename, array &$headers)
{
$hasFilename = '0' === $filename || $filename;
// Set a default content-disposition header if one was not provided
if (!$this->hasHeader($headers, 'content-disposition')) {
$headers['Content-Disposition'] = sprintf('form-data; name="%s"', $name);
if ($hasFilename) {
$headers['Content-Disposition'] .= sprintf('; filename="%s"', $this->basename($filename));
}
}
// Set a default content-length header if one was not provided
if (!$this->hasHeader($headers, 'content-length')) {
if ($length = $stream->getSize()) {
$headers['Content-Length'] = (string) $length;
}
}
// Set a default Content-Type if one was not provided
if (!$this->hasHeader($headers, 'content-type') && $hasFilename) {
if ($type = $this->getMimetypeHelper()->getMimetypeFromFilename($filename)) {
$headers['Content-Type'] = $type;
}
}
} | [
"private",
"function",
"prepareHeaders",
"(",
"$",
"name",
",",
"StreamInterface",
"$",
"stream",
",",
"$",
"filename",
",",
"array",
"&",
"$",
"headers",
")",
"{",
"$",
"hasFilename",
"=",
"'0'",
"===",
"$",
"filename",
"||",
"$",
"filename",
";",
"// S... | Add extra headers if they are missing.
@param string $name
@param StreamInterface $stream
@param string $filename
@param array &$headers | [
"Add",
"extra",
"headers",
"if",
"they",
"are",
"missing",
"."
] | train | https://github.com/php-http/multipart-stream-builder/blob/60d37c0d405c36fd5e4693bc0cede613492e68d8/src/MultipartStreamBuilder.php#L122-L147 |
php-http/multipart-stream-builder | src/MultipartStreamBuilder.php | MultipartStreamBuilder.getHeaders | private function getHeaders(array $headers)
{
$str = '';
foreach ($headers as $key => $value) {
$str .= sprintf("%s: %s\r\n", $key, $value);
}
return $str;
} | php | private function getHeaders(array $headers)
{
$str = '';
foreach ($headers as $key => $value) {
$str .= sprintf("%s: %s\r\n", $key, $value);
}
return $str;
} | [
"private",
"function",
"getHeaders",
"(",
"array",
"$",
"headers",
")",
"{",
"$",
"str",
"=",
"''",
";",
"foreach",
"(",
"$",
"headers",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"str",
".=",
"sprintf",
"(",
"\"%s: %s\\r\\n\"",
",",
"$",
... | Get the headers formatted for the HTTP message.
@param array $headers
@return string | [
"Get",
"the",
"headers",
"formatted",
"for",
"the",
"HTTP",
"message",
"."
] | train | https://github.com/php-http/multipart-stream-builder/blob/60d37c0d405c36fd5e4693bc0cede613492e68d8/src/MultipartStreamBuilder.php#L156-L164 |
php-http/multipart-stream-builder | src/MultipartStreamBuilder.php | MultipartStreamBuilder.getBoundary | public function getBoundary()
{
if (null === $this->boundary) {
$this->boundary = uniqid('', true);
}
return $this->boundary;
} | php | public function getBoundary()
{
if (null === $this->boundary) {
$this->boundary = uniqid('', true);
}
return $this->boundary;
} | [
"public",
"function",
"getBoundary",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"boundary",
")",
"{",
"$",
"this",
"->",
"boundary",
"=",
"uniqid",
"(",
"''",
",",
"true",
")",
";",
"}",
"return",
"$",
"this",
"->",
"boundary",
";"... | Get the boundary that separates the streams.
@return string | [
"Get",
"the",
"boundary",
"that",
"separates",
"the",
"streams",
"."
] | train | https://github.com/php-http/multipart-stream-builder/blob/60d37c0d405c36fd5e4693bc0cede613492e68d8/src/MultipartStreamBuilder.php#L191-L198 |
php-http/multipart-stream-builder | src/MultipartStreamBuilder.php | MultipartStreamBuilder.basename | private function basename($path)
{
$separators = '/';
if (DIRECTORY_SEPARATOR != '/') {
// For Windows OS add special separator.
$separators .= DIRECTORY_SEPARATOR;
}
// Remove right-most slashes when $path points to directory.
$path = rtrim($path, $separators);
// Returns the trailing part of the $path starting after one of the directory separators.
$filename = preg_match('@[^'.preg_quote($separators, '@').']+$@', $path, $matches) ? $matches[0] : '';
return $filename;
} | php | private function basename($path)
{
$separators = '/';
if (DIRECTORY_SEPARATOR != '/') {
// For Windows OS add special separator.
$separators .= DIRECTORY_SEPARATOR;
}
// Remove right-most slashes when $path points to directory.
$path = rtrim($path, $separators);
// Returns the trailing part of the $path starting after one of the directory separators.
$filename = preg_match('@[^'.preg_quote($separators, '@').']+$@', $path, $matches) ? $matches[0] : '';
return $filename;
} | [
"private",
"function",
"basename",
"(",
"$",
"path",
")",
"{",
"$",
"separators",
"=",
"'/'",
";",
"if",
"(",
"DIRECTORY_SEPARATOR",
"!=",
"'/'",
")",
"{",
"// For Windows OS add special separator.",
"$",
"separators",
".=",
"DIRECTORY_SEPARATOR",
";",
"}",
"// ... | Gets the filename from a given path.
PHP's basename() does not properly support streams or filenames beginning with a non-US-ASCII character.
@author Drupal 8.2
@param string $path
@return string | [
"Gets",
"the",
"filename",
"from",
"a",
"given",
"path",
"."
] | train | https://github.com/php-http/multipart-stream-builder/blob/60d37c0d405c36fd5e4693bc0cede613492e68d8/src/MultipartStreamBuilder.php#L262-L277 |
php-http/multipart-stream-builder | src/CustomMimetypeHelper.php | CustomMimetypeHelper.getMimetypeFromExtension | public function getMimetypeFromExtension($extension)
{
$extension = strtolower($extension);
return isset($this->mimetypes[$extension])
? $this->mimetypes[$extension]
: parent::getMimetypeFromExtension($extension);
} | php | public function getMimetypeFromExtension($extension)
{
$extension = strtolower($extension);
return isset($this->mimetypes[$extension])
? $this->mimetypes[$extension]
: parent::getMimetypeFromExtension($extension);
} | [
"public",
"function",
"getMimetypeFromExtension",
"(",
"$",
"extension",
")",
"{",
"$",
"extension",
"=",
"strtolower",
"(",
"$",
"extension",
")",
";",
"return",
"isset",
"(",
"$",
"this",
"->",
"mimetypes",
"[",
"$",
"extension",
"]",
")",
"?",
"$",
"t... | {@inheritdoc}
Check if we have any defined mimetypes and of not fallback to ApacheMimetypeHelper | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/php-http/multipart-stream-builder/blob/60d37c0d405c36fd5e4693bc0cede613492e68d8/src/CustomMimetypeHelper.php#L43-L50 |
php-http/multipart-stream-builder | src/ApacheMimetypeHelper.php | ApacheMimetypeHelper.getMimetypeFromExtension | public function getMimetypeFromExtension($extension)
{
static $mimetypes = [
'7z' => 'application/x-7z-compressed',
'aac' => 'audio/x-aac',
'ai' => 'application/postscript',
'aif' => 'audio/x-aiff',
'asc' => 'text/plain',
'asf' => 'video/x-ms-asf',
'atom' => 'application/atom+xml',
'avi' => 'video/x-msvideo',
'bmp' => 'image/bmp',
'bz2' => 'application/x-bzip2',
'cer' => 'application/pkix-cert',
'crl' => 'application/pkix-crl',
'crt' => 'application/x-x509-ca-cert',
'css' => 'text/css',
'csv' => 'text/csv',
'cu' => 'application/cu-seeme',
'deb' => 'application/x-debian-package',
'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dvi' => 'application/x-dvi',
'eot' => 'application/vnd.ms-fontobject',
'eps' => 'application/postscript',
'epub' => 'application/epub+zip',
'etx' => 'text/x-setext',
'flac' => 'audio/flac',
'flv' => 'video/x-flv',
'gif' => 'image/gif',
'gz' => 'application/gzip',
'htm' => 'text/html',
'html' => 'text/html',
'ico' => 'image/x-icon',
'ics' => 'text/calendar',
'ini' => 'text/plain',
'iso' => 'application/x-iso9660-image',
'jar' => 'application/java-archive',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'js' => 'text/javascript',
'json' => 'application/json',
'latex' => 'application/x-latex',
'log' => 'text/plain',
'm4a' => 'audio/mp4',
'm4v' => 'video/mp4',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mov' => 'video/quicktime',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
'mp4a' => 'audio/mp4',
'mp4v' => 'video/mp4',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpg4' => 'video/mp4',
'oga' => 'audio/ogg',
'ogg' => 'audio/ogg',
'ogv' => 'video/ogg',
'ogx' => 'application/ogg',
'pbm' => 'image/x-portable-bitmap',
'pdf' => 'application/pdf',
'pgm' => 'image/x-portable-graymap',
'png' => 'image/png',
'pnm' => 'image/x-portable-anymap',
'ppm' => 'image/x-portable-pixmap',
'ppt' => 'application/vnd.ms-powerpoint',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'ps' => 'application/postscript',
'qt' => 'video/quicktime',
'rar' => 'application/x-rar-compressed',
'ras' => 'image/x-cmu-raster',
'rss' => 'application/rss+xml',
'rtf' => 'application/rtf',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'svg' => 'image/svg+xml',
'swf' => 'application/x-shockwave-flash',
'tar' => 'application/x-tar',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'torrent' => 'application/x-bittorrent',
'ttf' => 'application/x-font-ttf',
'txt' => 'text/plain',
'wav' => 'audio/x-wav',
'webm' => 'video/webm',
'wma' => 'audio/x-ms-wma',
'wmv' => 'video/x-ms-wmv',
'woff' => 'application/x-font-woff',
'wsdl' => 'application/wsdl+xml',
'xbm' => 'image/x-xbitmap',
'xls' => 'application/vnd.ms-excel',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xml' => 'application/xml',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'yaml' => 'text/yaml',
'yml' => 'text/yaml',
'zip' => 'application/zip',
// Non-Apache standard
'pkpass' => 'application/vnd.apple.pkpass',
'msg' => 'application/vnd.ms-outlook',
];
$extension = strtolower($extension);
return isset($mimetypes[$extension])
? $mimetypes[$extension]
: null;
} | php | public function getMimetypeFromExtension($extension)
{
static $mimetypes = [
'7z' => 'application/x-7z-compressed',
'aac' => 'audio/x-aac',
'ai' => 'application/postscript',
'aif' => 'audio/x-aiff',
'asc' => 'text/plain',
'asf' => 'video/x-ms-asf',
'atom' => 'application/atom+xml',
'avi' => 'video/x-msvideo',
'bmp' => 'image/bmp',
'bz2' => 'application/x-bzip2',
'cer' => 'application/pkix-cert',
'crl' => 'application/pkix-crl',
'crt' => 'application/x-x509-ca-cert',
'css' => 'text/css',
'csv' => 'text/csv',
'cu' => 'application/cu-seeme',
'deb' => 'application/x-debian-package',
'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dvi' => 'application/x-dvi',
'eot' => 'application/vnd.ms-fontobject',
'eps' => 'application/postscript',
'epub' => 'application/epub+zip',
'etx' => 'text/x-setext',
'flac' => 'audio/flac',
'flv' => 'video/x-flv',
'gif' => 'image/gif',
'gz' => 'application/gzip',
'htm' => 'text/html',
'html' => 'text/html',
'ico' => 'image/x-icon',
'ics' => 'text/calendar',
'ini' => 'text/plain',
'iso' => 'application/x-iso9660-image',
'jar' => 'application/java-archive',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'js' => 'text/javascript',
'json' => 'application/json',
'latex' => 'application/x-latex',
'log' => 'text/plain',
'm4a' => 'audio/mp4',
'm4v' => 'video/mp4',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mov' => 'video/quicktime',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
'mp4a' => 'audio/mp4',
'mp4v' => 'video/mp4',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpg4' => 'video/mp4',
'oga' => 'audio/ogg',
'ogg' => 'audio/ogg',
'ogv' => 'video/ogg',
'ogx' => 'application/ogg',
'pbm' => 'image/x-portable-bitmap',
'pdf' => 'application/pdf',
'pgm' => 'image/x-portable-graymap',
'png' => 'image/png',
'pnm' => 'image/x-portable-anymap',
'ppm' => 'image/x-portable-pixmap',
'ppt' => 'application/vnd.ms-powerpoint',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'ps' => 'application/postscript',
'qt' => 'video/quicktime',
'rar' => 'application/x-rar-compressed',
'ras' => 'image/x-cmu-raster',
'rss' => 'application/rss+xml',
'rtf' => 'application/rtf',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'svg' => 'image/svg+xml',
'swf' => 'application/x-shockwave-flash',
'tar' => 'application/x-tar',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'torrent' => 'application/x-bittorrent',
'ttf' => 'application/x-font-ttf',
'txt' => 'text/plain',
'wav' => 'audio/x-wav',
'webm' => 'video/webm',
'wma' => 'audio/x-ms-wma',
'wmv' => 'video/x-ms-wmv',
'woff' => 'application/x-font-woff',
'wsdl' => 'application/wsdl+xml',
'xbm' => 'image/x-xbitmap',
'xls' => 'application/vnd.ms-excel',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xml' => 'application/xml',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'yaml' => 'text/yaml',
'yml' => 'text/yaml',
'zip' => 'application/zip',
// Non-Apache standard
'pkpass' => 'application/vnd.apple.pkpass',
'msg' => 'application/vnd.ms-outlook',
];
$extension = strtolower($extension);
return isset($mimetypes[$extension])
? $mimetypes[$extension]
: null;
} | [
"public",
"function",
"getMimetypeFromExtension",
"(",
"$",
"extension",
")",
"{",
"static",
"$",
"mimetypes",
"=",
"[",
"'7z'",
"=>",
"'application/x-7z-compressed'",
",",
"'aac'",
"=>",
"'audio/x-aac'",
",",
"'ai'",
"=>",
"'application/postscript'",
",",
"'aif'",
... | {@inheritdoc}
@see http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/php-http/multipart-stream-builder/blob/60d37c0d405c36fd5e4693bc0cede613492e68d8/src/ApacheMimetypeHelper.php#L29-L141 |
BePsvPT/secure-headers | src/SecureHeadersMiddleware.php | SecureHeadersMiddleware.handle | public function handle(Request $request, Closure $next)
{
$response = $next($request);
$headers = (new SecureHeaders(config('secure-headers', [])))->headers();
foreach ($headers as $key => $value) {
$response->headers->set($key, $value, true);
}
return $response;
} | php | public function handle(Request $request, Closure $next)
{
$response = $next($request);
$headers = (new SecureHeaders(config('secure-headers', [])))->headers();
foreach ($headers as $key => $value) {
$response->headers->set($key, $value, true);
}
return $response;
} | [
"public",
"function",
"handle",
"(",
"Request",
"$",
"request",
",",
"Closure",
"$",
"next",
")",
"{",
"$",
"response",
"=",
"$",
"next",
"(",
"$",
"request",
")",
";",
"$",
"headers",
"=",
"(",
"new",
"SecureHeaders",
"(",
"config",
"(",
"'secure-head... | Handle an incoming request.
@param Request $request
@param Closure $next
@return Response | [
"Handle",
"an",
"incoming",
"request",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/SecureHeadersMiddleware.php#L19-L30 |
BePsvPT/secure-headers | src/SecureHeaders.php | SecureHeaders.send | public function send()
{
if (headers_sent($file, $line)) {
throw new RuntimeException("Headers already sent in {$file} on line {$line}."); // @codeCoverageIgnore
}
foreach ($this->headers() as $key => $value) {
header("{$key}: {$value}", true);
}
} | php | public function send()
{
if (headers_sent($file, $line)) {
throw new RuntimeException("Headers already sent in {$file} on line {$line}."); // @codeCoverageIgnore
}
foreach ($this->headers() as $key => $value) {
header("{$key}: {$value}", true);
}
} | [
"public",
"function",
"send",
"(",
")",
"{",
"if",
"(",
"headers_sent",
"(",
"$",
"file",
",",
"$",
"line",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Headers already sent in {$file} on line {$line}.\"",
")",
";",
"// @codeCoverageIgnore",
"}",
"... | Send HTTP headers.
@return void | [
"Send",
"HTTP",
"headers",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/SecureHeaders.php#L58-L67 |
BePsvPT/secure-headers | src/SecureHeaders.php | SecureHeaders.compile | protected function compile()
{
$this->headers = array_merge(
$this->csp(),
$this->featurePolicy(),
$this->hpkp(),
$this->hsts(),
$this->expectCT(),
$this->clearSiteData(),
$this->miscellaneous()
);
$this->compiled = true;
} | php | protected function compile()
{
$this->headers = array_merge(
$this->csp(),
$this->featurePolicy(),
$this->hpkp(),
$this->hsts(),
$this->expectCT(),
$this->clearSiteData(),
$this->miscellaneous()
);
$this->compiled = true;
} | [
"protected",
"function",
"compile",
"(",
")",
"{",
"$",
"this",
"->",
"headers",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"csp",
"(",
")",
",",
"$",
"this",
"->",
"featurePolicy",
"(",
")",
",",
"$",
"this",
"->",
"hpkp",
"(",
")",
",",
"$",
"... | Compile HTTP headers.
@return void | [
"Compile",
"HTTP",
"headers",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/SecureHeaders.php#L88-L101 |
BePsvPT/secure-headers | src/SecureHeaders.php | SecureHeaders.csp | protected function csp(): array
{
if (! is_null($this->config['custom-csp'])) {
if (empty($this->config['custom-csp'])) {
return [];
}
return [
'Content-Security-Policy' => $this->config['custom-csp'],
];
}
return Builder::getCSPHeader($this->config['csp']);
} | php | protected function csp(): array
{
if (! is_null($this->config['custom-csp'])) {
if (empty($this->config['custom-csp'])) {
return [];
}
return [
'Content-Security-Policy' => $this->config['custom-csp'],
];
}
return Builder::getCSPHeader($this->config['csp']);
} | [
"protected",
"function",
"csp",
"(",
")",
":",
"array",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"config",
"[",
"'custom-csp'",
"]",
")",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"config",
"[",
"'custom-csp'",
"]",
")",
... | Get CSP header.
@return array | [
"Get",
"CSP",
"header",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/SecureHeaders.php#L108-L121 |
BePsvPT/secure-headers | src/SecureHeaders.php | SecureHeaders.expectCT | protected function expectCT(): array
{
if (! ($this->config['expect-ct']['enable'] ?? false)) {
return [];
}
$ct = "max-age={$this->config['expect-ct']['max-age']}";
if ($this->config['expect-ct']['enforce']) {
$ct .= ', enforce';
}
if (! empty($this->config['expect-ct']['report-uri'])) {
$ct .= sprintf(', report-uri="%s"', $this->config['expect-ct']['report-uri']);
}
return [
'Expect-CT' => $ct,
];
} | php | protected function expectCT(): array
{
if (! ($this->config['expect-ct']['enable'] ?? false)) {
return [];
}
$ct = "max-age={$this->config['expect-ct']['max-age']}";
if ($this->config['expect-ct']['enforce']) {
$ct .= ', enforce';
}
if (! empty($this->config['expect-ct']['report-uri'])) {
$ct .= sprintf(', report-uri="%s"', $this->config['expect-ct']['report-uri']);
}
return [
'Expect-CT' => $ct,
];
} | [
"protected",
"function",
"expectCT",
"(",
")",
":",
"array",
"{",
"if",
"(",
"!",
"(",
"$",
"this",
"->",
"config",
"[",
"'expect-ct'",
"]",
"[",
"'enable'",
"]",
"??",
"false",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"ct",
"=",
"\"max-... | Generate Expect-CT header.
@return array | [
"Generate",
"Expect",
"-",
"CT",
"header",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/SecureHeaders.php#L180-L199 |
BePsvPT/secure-headers | src/SecureHeaders.php | SecureHeaders.clearSiteData | protected function clearSiteData(): array
{
if (! ($this->config['clear-site-data']['enable'] ?? false)) {
return [];
}
if ($this->config['clear-site-data']['all']) {
$csd = '"*"';
} else {
// simulate array_only, filter disabled and get keys
$flags = array_keys(array_filter(array_intersect_key(
$this->config['clear-site-data'],
array_flip(['cache', 'cookies', 'storage', 'executionContexts'])
)));
if (empty($flags)) {
return [];
}
$csd = sprintf('"%s"', implode('", "', $flags));
}
return [
'Clear-Site-Data' => $csd,
];
} | php | protected function clearSiteData(): array
{
if (! ($this->config['clear-site-data']['enable'] ?? false)) {
return [];
}
if ($this->config['clear-site-data']['all']) {
$csd = '"*"';
} else {
// simulate array_only, filter disabled and get keys
$flags = array_keys(array_filter(array_intersect_key(
$this->config['clear-site-data'],
array_flip(['cache', 'cookies', 'storage', 'executionContexts'])
)));
if (empty($flags)) {
return [];
}
$csd = sprintf('"%s"', implode('", "', $flags));
}
return [
'Clear-Site-Data' => $csd,
];
} | [
"protected",
"function",
"clearSiteData",
"(",
")",
":",
"array",
"{",
"if",
"(",
"!",
"(",
"$",
"this",
"->",
"config",
"[",
"'clear-site-data'",
"]",
"[",
"'enable'",
"]",
"??",
"false",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"$"... | Generate Clear-Site-Data header.
@return array | [
"Generate",
"Clear",
"-",
"Site",
"-",
"Data",
"header",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/SecureHeaders.php#L206-L231 |
BePsvPT/secure-headers | src/SecureHeaders.php | SecureHeaders.miscellaneous | protected function miscellaneous(): array
{
return array_filter([
'X-Content-Type-Options' => $this->config['x-content-type-options'],
'X-Download-Options' => $this->config['x-download-options'],
'X-Frame-Options' => $this->config['x-frame-options'],
'X-Permitted-Cross-Domain-Policies' => $this->config['x-permitted-cross-domain-policies'],
'X-XSS-Protection' => $this->config['x-xss-protection'],
'Referrer-Policy' => $this->config['referrer-policy'],
'Server' => $this->config['server'] ?? '',
]);
} | php | protected function miscellaneous(): array
{
return array_filter([
'X-Content-Type-Options' => $this->config['x-content-type-options'],
'X-Download-Options' => $this->config['x-download-options'],
'X-Frame-Options' => $this->config['x-frame-options'],
'X-Permitted-Cross-Domain-Policies' => $this->config['x-permitted-cross-domain-policies'],
'X-XSS-Protection' => $this->config['x-xss-protection'],
'Referrer-Policy' => $this->config['referrer-policy'],
'Server' => $this->config['server'] ?? '',
]);
} | [
"protected",
"function",
"miscellaneous",
"(",
")",
":",
"array",
"{",
"return",
"array_filter",
"(",
"[",
"'X-Content-Type-Options'",
"=>",
"$",
"this",
"->",
"config",
"[",
"'x-content-type-options'",
"]",
",",
"'X-Download-Options'",
"=>",
"$",
"this",
"->",
... | Get miscellaneous headers.
@return array | [
"Get",
"miscellaneous",
"headers",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/SecureHeaders.php#L238-L249 |
BePsvPT/secure-headers | src/SecureHeaders.php | SecureHeaders.addGeneratedNonce | protected function addGeneratedNonce(array $config): array
{
if (($config['csp']['script-src']['add-generated-nonce'] ?? false) === true) {
$config['csp']['script-src']['nonces'][] = self::nonce();
}
if (($config['csp']['style-src']['add-generated-nonce'] ?? false) === true) {
$config['csp']['style-src']['nonces'][] = self::nonce();
}
return $config;
} | php | protected function addGeneratedNonce(array $config): array
{
if (($config['csp']['script-src']['add-generated-nonce'] ?? false) === true) {
$config['csp']['script-src']['nonces'][] = self::nonce();
}
if (($config['csp']['style-src']['add-generated-nonce'] ?? false) === true) {
$config['csp']['style-src']['nonces'][] = self::nonce();
}
return $config;
} | [
"protected",
"function",
"addGeneratedNonce",
"(",
"array",
"$",
"config",
")",
":",
"array",
"{",
"if",
"(",
"(",
"$",
"config",
"[",
"'csp'",
"]",
"[",
"'script-src'",
"]",
"[",
"'add-generated-nonce'",
"]",
"??",
"false",
")",
"===",
"true",
")",
"{",... | Add generated nonce value to script-src and style-src.
@param array $config
@return array | [
"Add",
"generated",
"nonce",
"value",
"to",
"script",
"-",
"src",
"and",
"style",
"-",
"src",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/SecureHeaders.php#L270-L281 |
BePsvPT/secure-headers | src/Builder.php | Builder.getHPKPHeader | public static function getHPKPHeader(array $config): array
{
$headers = [];
foreach ($config['hashes'] as $hash) {
$headers[] = sprintf('pin-sha256="%s"', $hash);
}
$headers[] = sprintf('max-age=%d', $config['max-age']);
if ($config['include-sub-domains']) {
$headers[] = 'includeSubDomains';
}
if (! empty($config['report-uri'])) {
$headers[] = sprintf('report-uri="%s"', $config['report-uri']);
}
$key = $config['report-only']
? 'Public-Key-Pins-Report-Only'
: 'Public-Key-Pins';
return [$key => implode('; ', $headers)];
} | php | public static function getHPKPHeader(array $config): array
{
$headers = [];
foreach ($config['hashes'] as $hash) {
$headers[] = sprintf('pin-sha256="%s"', $hash);
}
$headers[] = sprintf('max-age=%d', $config['max-age']);
if ($config['include-sub-domains']) {
$headers[] = 'includeSubDomains';
}
if (! empty($config['report-uri'])) {
$headers[] = sprintf('report-uri="%s"', $config['report-uri']);
}
$key = $config['report-only']
? 'Public-Key-Pins-Report-Only'
: 'Public-Key-Pins';
return [$key => implode('; ', $headers)];
} | [
"public",
"static",
"function",
"getHPKPHeader",
"(",
"array",
"$",
"config",
")",
":",
"array",
"{",
"$",
"headers",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"config",
"[",
"'hashes'",
"]",
"as",
"$",
"hash",
")",
"{",
"$",
"headers",
"[",
"]",
"=... | Generate HPKP header.
@param array $config
@return array | [
"Generate",
"HPKP",
"header",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/Builder.php#L14-L37 |
BePsvPT/secure-headers | src/Builder.php | Builder.getFeaturePolicyHeader | public static function getFeaturePolicyHeader(array $config): array
{
$directives = [
'accelerometer',
'ambient-light-sensor',
'autoplay',
'camera',
'encrypted-media',
'fullscreen',
'geolocation',
'gyroscope',
'magnetometer',
'microphone',
'midi',
'payment',
'picture-in-picture',
'speaker',
'sync-xhr',
'usb',
'var',
];
foreach ($directives as $directive) {
if (! isset($config[$directive]) || empty($config[$directive])) {
continue;
}
$value = '';
if ($config[$directive]['none']) {
$value = "'none'";
} elseif ($config[$directive]['*']) {
$value = '*';
} else {
if ($config[$directive]['self']) {
$value = "'self'";
}
foreach ($config[$directive]['allow'] as $url) {
if (false !== ($url = filter_var($url, FILTER_SANITIZE_URL))) {
$value = sprintf('%s %s', $value, $url);
}
}
}
if (strlen($value = trim($value)) > 0) {
$headers[] = sprintf('%s %s', $directive, $value);
}
}
if (! isset($headers)) {
return [];
}
return ['Feature-Policy' => implode('; ', $headers)];
} | php | public static function getFeaturePolicyHeader(array $config): array
{
$directives = [
'accelerometer',
'ambient-light-sensor',
'autoplay',
'camera',
'encrypted-media',
'fullscreen',
'geolocation',
'gyroscope',
'magnetometer',
'microphone',
'midi',
'payment',
'picture-in-picture',
'speaker',
'sync-xhr',
'usb',
'var',
];
foreach ($directives as $directive) {
if (! isset($config[$directive]) || empty($config[$directive])) {
continue;
}
$value = '';
if ($config[$directive]['none']) {
$value = "'none'";
} elseif ($config[$directive]['*']) {
$value = '*';
} else {
if ($config[$directive]['self']) {
$value = "'self'";
}
foreach ($config[$directive]['allow'] as $url) {
if (false !== ($url = filter_var($url, FILTER_SANITIZE_URL))) {
$value = sprintf('%s %s', $value, $url);
}
}
}
if (strlen($value = trim($value)) > 0) {
$headers[] = sprintf('%s %s', $directive, $value);
}
}
if (! isset($headers)) {
return [];
}
return ['Feature-Policy' => implode('; ', $headers)];
} | [
"public",
"static",
"function",
"getFeaturePolicyHeader",
"(",
"array",
"$",
"config",
")",
":",
"array",
"{",
"$",
"directives",
"=",
"[",
"'accelerometer'",
",",
"'ambient-light-sensor'",
",",
"'autoplay'",
",",
"'camera'",
",",
"'encrypted-media'",
",",
"'fulls... | Generate Feature Policy header.
@param array $config
@return array | [
"Generate",
"Feature",
"Policy",
"header",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/Builder.php#L46-L101 |
BePsvPT/secure-headers | src/Builder.php | Builder.getCSPHeader | public static function getCSPHeader(array $config): array
{
$directives = [
'default-src',
'base-uri',
'connect-src',
'font-src',
'form-action',
'frame-ancestors',
'frame-src',
'img-src',
'manifest-src',
'media-src',
'object-src',
'plugin-types',
'require-sri-for',
'sandbox',
'script-src',
'style-src',
'worker-src',
];
$headers = [];
foreach ($directives as $directive) {
if (isset($config[$directive])) {
$headers[] = self::compileDirective($directive, $config[$directive]);
}
}
if (! empty($config['block-all-mixed-content'])) {
$headers[] = 'block-all-mixed-content';
}
if (! empty($config['upgrade-insecure-requests'])) {
$headers[] = 'upgrade-insecure-requests';
}
if (! empty($config['report-uri'])) {
$headers[] = sprintf('report-uri %s', $config['report-uri']);
}
$key = ! empty($config['report-only'])
? 'Content-Security-Policy-Report-Only'
: 'Content-Security-Policy';
return [$key => implode('; ', array_filter($headers, 'strlen'))];
} | php | public static function getCSPHeader(array $config): array
{
$directives = [
'default-src',
'base-uri',
'connect-src',
'font-src',
'form-action',
'frame-ancestors',
'frame-src',
'img-src',
'manifest-src',
'media-src',
'object-src',
'plugin-types',
'require-sri-for',
'sandbox',
'script-src',
'style-src',
'worker-src',
];
$headers = [];
foreach ($directives as $directive) {
if (isset($config[$directive])) {
$headers[] = self::compileDirective($directive, $config[$directive]);
}
}
if (! empty($config['block-all-mixed-content'])) {
$headers[] = 'block-all-mixed-content';
}
if (! empty($config['upgrade-insecure-requests'])) {
$headers[] = 'upgrade-insecure-requests';
}
if (! empty($config['report-uri'])) {
$headers[] = sprintf('report-uri %s', $config['report-uri']);
}
$key = ! empty($config['report-only'])
? 'Content-Security-Policy-Report-Only'
: 'Content-Security-Policy';
return [$key => implode('; ', array_filter($headers, 'strlen'))];
} | [
"public",
"static",
"function",
"getCSPHeader",
"(",
"array",
"$",
"config",
")",
":",
"array",
"{",
"$",
"directives",
"=",
"[",
"'default-src'",
",",
"'base-uri'",
",",
"'connect-src'",
",",
"'font-src'",
",",
"'form-action'",
",",
"'frame-ancestors'",
",",
... | Generate CSP header.
@param array $config
@return array | [
"Generate",
"CSP",
"header",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/Builder.php#L110-L157 |
BePsvPT/secure-headers | src/Builder.php | Builder.compileDirective | protected static function compileDirective(string $directive, $policies): string
{
// handle special directive first
switch ($directive) {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/plugin-types
case 'plugin-types':
return empty($policies) ? '' : sprintf('%s %s', $directive, implode(' ', $policies));
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-sri-for
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/sandbox
case 'require-sri-for':
case 'sandbox':
return empty($policies) ? '' : sprintf('%s %s', $directive, $policies);
}
// when policies is empty, we assume that user disallow this directive
if (empty($policies)) {
return sprintf("%s 'none'", $directive);
}
$ret = [$directive];
// keyword source, https://www.w3.org/TR/CSP/#grammardef-keyword-source, https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src
foreach (['self', 'unsafe-inline', 'unsafe-eval', 'strict-dynamic', 'unsafe-hashed-attributes', 'report-sample'] as $keyword) {
if (! empty($policies[$keyword])) {
$ret[] = sprintf("'%s'", $keyword);
}
}
if (! empty($policies['allow'])) {
foreach ($policies['allow'] as $url) {
// removes illegal URL characters
if (false !== ($url = filter_var($url, FILTER_SANITIZE_URL))) {
$ret[] = $url;
}
}
}
if (! empty($policies['hashes'])) {
foreach ($policies['hashes'] as $algo => $hashes) {
// skip not support algorithm, https://www.w3.org/TR/CSP/#grammardef-hash-source
if (! in_array($algo, ['sha256', 'sha384', 'sha512'])) {
continue;
}
foreach ($hashes as $value) {
// skip invalid value
if (! self::isBase64Valid($value)) {
continue;
}
$ret[] = sprintf("'%s-%s'", $algo, $value);
}
}
}
if (! empty($policies['nonces'])) {
foreach ($policies['nonces'] as $nonce) {
// skip invalid value, https://www.w3.org/TR/CSP/#grammardef-nonce-source
if (! self::isBase64Valid($nonce)) {
continue;
}
$ret[] = sprintf("'nonce-%s'", $nonce);
}
}
if (! empty($policies['schemes'])) {
foreach ($policies['schemes'] as $scheme) {
$ret[] = sprintf('%s', $scheme);
}
}
return implode(' ', $ret);
} | php | protected static function compileDirective(string $directive, $policies): string
{
// handle special directive first
switch ($directive) {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/plugin-types
case 'plugin-types':
return empty($policies) ? '' : sprintf('%s %s', $directive, implode(' ', $policies));
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-sri-for
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/sandbox
case 'require-sri-for':
case 'sandbox':
return empty($policies) ? '' : sprintf('%s %s', $directive, $policies);
}
// when policies is empty, we assume that user disallow this directive
if (empty($policies)) {
return sprintf("%s 'none'", $directive);
}
$ret = [$directive];
// keyword source, https://www.w3.org/TR/CSP/#grammardef-keyword-source, https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src
foreach (['self', 'unsafe-inline', 'unsafe-eval', 'strict-dynamic', 'unsafe-hashed-attributes', 'report-sample'] as $keyword) {
if (! empty($policies[$keyword])) {
$ret[] = sprintf("'%s'", $keyword);
}
}
if (! empty($policies['allow'])) {
foreach ($policies['allow'] as $url) {
// removes illegal URL characters
if (false !== ($url = filter_var($url, FILTER_SANITIZE_URL))) {
$ret[] = $url;
}
}
}
if (! empty($policies['hashes'])) {
foreach ($policies['hashes'] as $algo => $hashes) {
// skip not support algorithm, https://www.w3.org/TR/CSP/#grammardef-hash-source
if (! in_array($algo, ['sha256', 'sha384', 'sha512'])) {
continue;
}
foreach ($hashes as $value) {
// skip invalid value
if (! self::isBase64Valid($value)) {
continue;
}
$ret[] = sprintf("'%s-%s'", $algo, $value);
}
}
}
if (! empty($policies['nonces'])) {
foreach ($policies['nonces'] as $nonce) {
// skip invalid value, https://www.w3.org/TR/CSP/#grammardef-nonce-source
if (! self::isBase64Valid($nonce)) {
continue;
}
$ret[] = sprintf("'nonce-%s'", $nonce);
}
}
if (! empty($policies['schemes'])) {
foreach ($policies['schemes'] as $scheme) {
$ret[] = sprintf('%s', $scheme);
}
}
return implode(' ', $ret);
} | [
"protected",
"static",
"function",
"compileDirective",
"(",
"string",
"$",
"directive",
",",
"$",
"policies",
")",
":",
"string",
"{",
"// handle special directive first",
"switch",
"(",
"$",
"directive",
")",
"{",
"// https://developer.mozilla.org/en-US/docs/Web/HTTP/Hea... | Compile a subgroup into a policy string.
@param string $directive
@param mixed $policies
@return string | [
"Compile",
"a",
"subgroup",
"into",
"a",
"policy",
"string",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/Builder.php#L167-L241 |
BePsvPT/secure-headers | src/Builder.php | Builder.isBase64Valid | protected static function isBase64Valid(string $encode): bool
{
$decode = base64_decode($encode, true);
if (false === $decode) {
return false;
}
return base64_encode($decode) === $encode;
} | php | protected static function isBase64Valid(string $encode): bool
{
$decode = base64_decode($encode, true);
if (false === $decode) {
return false;
}
return base64_encode($decode) === $encode;
} | [
"protected",
"static",
"function",
"isBase64Valid",
"(",
"string",
"$",
"encode",
")",
":",
"bool",
"{",
"$",
"decode",
"=",
"base64_decode",
"(",
"$",
"encode",
",",
"true",
")",
";",
"if",
"(",
"false",
"===",
"$",
"decode",
")",
"{",
"return",
"fals... | Check base64 encoded string is valid or not.
@param string $encode
@return bool | [
"Check",
"base64",
"encoded",
"string",
"is",
"valid",
"or",
"not",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/Builder.php#L250-L259 |
BePsvPT/secure-headers | src/SecureHeadersServiceProvider.php | SecureHeadersServiceProvider.boot | public function boot()
{
if ($this->app instanceof \Laravel\Lumen\Application) {
$this->bootLumen();
} else {
$this->bootLaravel();
}
} | php | public function boot()
{
if ($this->app instanceof \Laravel\Lumen\Application) {
$this->bootLumen();
} else {
$this->bootLaravel();
}
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"app",
"instanceof",
"\\",
"Laravel",
"\\",
"Lumen",
"\\",
"Application",
")",
"{",
"$",
"this",
"->",
"bootLumen",
"(",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"boot... | Bootstrap the application events.
@return void | [
"Bootstrap",
"the",
"application",
"events",
"."
] | train | https://github.com/BePsvPT/secure-headers/blob/f45d2c216b85a89c41312449542c47e94a35bff8/src/SecureHeadersServiceProvider.php#L14-L21 |
angeloskath/php-nlp-tools | src/NlpTools/Optimizers/GradientDescentOptimizer.php | GradientDescentOptimizer.optimize | public function optimize(array &$feature_array)
{
$itercount = 0;
$optimized = false;
$maxiter = $this->maxiter;
$prec = $this->precision;
$step = $this->step;
$l = array();
$this->initParameters($feature_array,$l);
while (!$optimized && $itercount++!=$maxiter) {
//$start = microtime(true);
$optimized = true;
$this->prepareFprime($feature_array,$l);
$this->Fprime($feature_array,$l);
foreach ($this->fprime_vector as $i=>$fprime_i_val) {
$l[$i] -= $step*$fprime_i_val;
if (abs($fprime_i_val) > $prec) {
$optimized = false;
}
}
//fprintf(STDERR,"%f\n",microtime(true)-$start);
if ($this->verbose>0)
$this->reportProgress($itercount);
}
return $l;
} | php | public function optimize(array &$feature_array)
{
$itercount = 0;
$optimized = false;
$maxiter = $this->maxiter;
$prec = $this->precision;
$step = $this->step;
$l = array();
$this->initParameters($feature_array,$l);
while (!$optimized && $itercount++!=$maxiter) {
//$start = microtime(true);
$optimized = true;
$this->prepareFprime($feature_array,$l);
$this->Fprime($feature_array,$l);
foreach ($this->fprime_vector as $i=>$fprime_i_val) {
$l[$i] -= $step*$fprime_i_val;
if (abs($fprime_i_val) > $prec) {
$optimized = false;
}
}
//fprintf(STDERR,"%f\n",microtime(true)-$start);
if ($this->verbose>0)
$this->reportProgress($itercount);
}
return $l;
} | [
"public",
"function",
"optimize",
"(",
"array",
"&",
"$",
"feature_array",
")",
"{",
"$",
"itercount",
"=",
"0",
";",
"$",
"optimized",
"=",
"false",
";",
"$",
"maxiter",
"=",
"$",
"this",
"->",
"maxiter",
";",
"$",
"prec",
"=",
"$",
"this",
"->",
... | Actually do the gradient descent algorithm.
l[i] = l[i] - learning_rate*( theta f/delta l[i] ) for each i
Could possibly benefit from a vetor add/scale function.
@param $feature_array All the data known about the training set
@return array The parameters $l[$i] that minimize F | [
"Actually",
"do",
"the",
"gradient",
"descent",
"algorithm",
".",
"l",
"[",
"i",
"]",
"=",
"l",
"[",
"i",
"]",
"-",
"learning_rate",
"*",
"(",
"theta",
"f",
"/",
"delta",
"l",
"[",
"i",
"]",
")",
"for",
"each",
"i",
"Could",
"possibly",
"benefit",
... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Optimizers/GradientDescentOptimizer.php#L65-L91 |
angeloskath/php-nlp-tools | src/NlpTools/Similarity/JaccardIndex.php | JaccardIndex.similarity | public function similarity(&$A, &$B)
{
$a = array_fill_keys($A,1);
$b = array_fill_keys($B,1);
$intersect = count(array_intersect_key($a,$b));
$union = count(array_fill_keys(array_merge($A,$B),1));
return $intersect/$union;
} | php | public function similarity(&$A, &$B)
{
$a = array_fill_keys($A,1);
$b = array_fill_keys($B,1);
$intersect = count(array_intersect_key($a,$b));
$union = count(array_fill_keys(array_merge($A,$B),1));
return $intersect/$union;
} | [
"public",
"function",
"similarity",
"(",
"&",
"$",
"A",
",",
"&",
"$",
"B",
")",
"{",
"$",
"a",
"=",
"array_fill_keys",
"(",
"$",
"A",
",",
"1",
")",
";",
"$",
"b",
"=",
"array_fill_keys",
"(",
"$",
"B",
",",
"1",
")",
";",
"$",
"intersect",
... | The similarity returned by this algorithm is a number between 0,1 | [
"The",
"similarity",
"returned",
"by",
"this",
"algorithm",
"is",
"a",
"number",
"between",
"0",
"1"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Similarity/JaccardIndex.php#L13-L22 |
angeloskath/php-nlp-tools | src/NlpTools/Similarity/CosineSimilarity.php | CosineSimilarity.similarity | public function similarity(&$A, &$B)
{
if (!is_array($A) || !is_array($B)) {
throw new \InvalidArgumentException('Vector $' . (!is_array($A) ? 'A' : 'B') . ' is not an array');
}
// This means they are simple text vectors
// so we need to count to make them vectors
if (is_int(key($A)))
$v1 = array_count_values($A);
else
$v1 = &$A;
if (is_int(key($B)))
$v2 = array_count_values($B);
else
$v2 = &$B;
$prod = 0.0;
$v1_norm = 0.0;
foreach ($v1 as $i=>$xi) {
if (isset($v2[$i])) {
$prod += $xi*$v2[$i];
}
$v1_norm += $xi*$xi;
}
$v1_norm = sqrt($v1_norm);
if ($v1_norm==0)
throw new \InvalidArgumentException("Vector \$A is the zero vector");
$v2_norm = 0.0;
foreach ($v2 as $i=>$xi) {
$v2_norm += $xi*$xi;
}
$v2_norm = sqrt($v2_norm);
if ($v2_norm==0)
throw new \InvalidArgumentException("Vector \$B is the zero vector");
return $prod/($v1_norm*$v2_norm);
} | php | public function similarity(&$A, &$B)
{
if (!is_array($A) || !is_array($B)) {
throw new \InvalidArgumentException('Vector $' . (!is_array($A) ? 'A' : 'B') . ' is not an array');
}
// This means they are simple text vectors
// so we need to count to make them vectors
if (is_int(key($A)))
$v1 = array_count_values($A);
else
$v1 = &$A;
if (is_int(key($B)))
$v2 = array_count_values($B);
else
$v2 = &$B;
$prod = 0.0;
$v1_norm = 0.0;
foreach ($v1 as $i=>$xi) {
if (isset($v2[$i])) {
$prod += $xi*$v2[$i];
}
$v1_norm += $xi*$xi;
}
$v1_norm = sqrt($v1_norm);
if ($v1_norm==0)
throw new \InvalidArgumentException("Vector \$A is the zero vector");
$v2_norm = 0.0;
foreach ($v2 as $i=>$xi) {
$v2_norm += $xi*$xi;
}
$v2_norm = sqrt($v2_norm);
if ($v2_norm==0)
throw new \InvalidArgumentException("Vector \$B is the zero vector");
return $prod/($v1_norm*$v2_norm);
} | [
"public",
"function",
"similarity",
"(",
"&",
"$",
"A",
",",
"&",
"$",
"B",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"A",
")",
"||",
"!",
"is_array",
"(",
"$",
"B",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Ve... | Returns a number between 0,1 that corresponds to the cos(theta)
where theta is the angle between the two sets if they are treated
as n-dimensional vectors.
See the class comment about why the number is in [0,1] and not
in [-1,1] as it normally should.
@param array $A Either feature vector or simply vector
@param array $B Either feature vector or simply vector
@return float The cosinus of the angle between the two vectors | [
"Returns",
"a",
"number",
"between",
"0",
"1",
"that",
"corresponds",
"to",
"the",
"cos",
"(",
"theta",
")",
"where",
"theta",
"is",
"the",
"angle",
"between",
"the",
"two",
"sets",
"if",
"they",
"are",
"treated",
"as",
"n",
"-",
"dimensional",
"vectors"... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Similarity/CosineSimilarity.php#L43-L82 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Lda.php | Lda.generateDocs | public function generateDocs(TrainingSet $tset)
{
$docs = array();
foreach ($tset as $d)
$docs[] = $this->ff->getFeatureArray('',$d);
return $docs;
} | php | public function generateDocs(TrainingSet $tset)
{
$docs = array();
foreach ($tset as $d)
$docs[] = $this->ff->getFeatureArray('',$d);
return $docs;
} | [
"public",
"function",
"generateDocs",
"(",
"TrainingSet",
"$",
"tset",
")",
"{",
"$",
"docs",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"tset",
"as",
"$",
"d",
")",
"$",
"docs",
"[",
"]",
"=",
"$",
"this",
"->",
"ff",
"->",
"getFeatureArray... | Generate an array suitable for use with Lda::initialize and
Lda::gibbsSample from a training set. | [
"Generate",
"an",
"array",
"suitable",
"for",
"use",
"with",
"Lda",
"::",
"initialize",
"and",
"Lda",
"::",
"gibbsSample",
"from",
"a",
"training",
"set",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Lda.php#L60-L67 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Lda.php | Lda.initialize | public function initialize(array &$docs)
{
$doc_keys = range(0,count($docs)-1);
$topic_keys = range(0,$this->ntopics-1);
// initialize the arrays
$this->words_in_doc = array_fill_keys(
$doc_keys,
0
);
$this->words_in_topic = array_fill_keys(
$topic_keys,
0
);
$this->count_docs_topics = array_fill_keys(
$doc_keys,
array_fill_keys(
$topic_keys,
0
)
);
$this->count_topics_words = array_fill_keys(
$topic_keys,
array()
);
$this->word_doc_assigned_topic = array_fill_keys(
$doc_keys,
array()
);
$this->voc = array();
foreach ($docs as $i=>$doc) {
$this->words_in_doc[$i] = count($doc);
foreach ($doc as $idx=>$w) {
// choose a topic randomly to assign this word to
$topic = (int) ($this->mt->generate()*$this->ntopics);
//$this->words_in_doc[$i]++;
$this->words_in_topic[$topic]++;
$this->count_docs_topics[$i][$topic]++;
if (!isset($this->count_topics_words[$topic][$w]))
$this->count_topics_words[$topic][$w]=0;
$this->count_topics_words[$topic][$w]++;
$this->word_doc_assigned_topic[$i][$idx] = $topic;
$this->voc[$w] = 1;
}
}
$this->voccnt = count($this->voc);
$this->voc = array_keys($this->voc);
} | php | public function initialize(array &$docs)
{
$doc_keys = range(0,count($docs)-1);
$topic_keys = range(0,$this->ntopics-1);
// initialize the arrays
$this->words_in_doc = array_fill_keys(
$doc_keys,
0
);
$this->words_in_topic = array_fill_keys(
$topic_keys,
0
);
$this->count_docs_topics = array_fill_keys(
$doc_keys,
array_fill_keys(
$topic_keys,
0
)
);
$this->count_topics_words = array_fill_keys(
$topic_keys,
array()
);
$this->word_doc_assigned_topic = array_fill_keys(
$doc_keys,
array()
);
$this->voc = array();
foreach ($docs as $i=>$doc) {
$this->words_in_doc[$i] = count($doc);
foreach ($doc as $idx=>$w) {
// choose a topic randomly to assign this word to
$topic = (int) ($this->mt->generate()*$this->ntopics);
//$this->words_in_doc[$i]++;
$this->words_in_topic[$topic]++;
$this->count_docs_topics[$i][$topic]++;
if (!isset($this->count_topics_words[$topic][$w]))
$this->count_topics_words[$topic][$w]=0;
$this->count_topics_words[$topic][$w]++;
$this->word_doc_assigned_topic[$i][$idx] = $topic;
$this->voc[$w] = 1;
}
}
$this->voccnt = count($this->voc);
$this->voc = array_keys($this->voc);
} | [
"public",
"function",
"initialize",
"(",
"array",
"&",
"$",
"docs",
")",
"{",
"$",
"doc_keys",
"=",
"range",
"(",
"0",
",",
"count",
"(",
"$",
"docs",
")",
"-",
"1",
")",
";",
"$",
"topic_keys",
"=",
"range",
"(",
"0",
",",
"$",
"this",
"->",
"... | Count initially the co-occurences of documents,topics and
topics,words and cache them to run Gibbs sampling faster
@param array $docs The docs that we will use to generate the sample | [
"Count",
"initially",
"the",
"co",
"-",
"occurences",
"of",
"documents",
"topics",
"and",
"topics",
"words",
"and",
"cache",
"them",
"to",
"run",
"Gibbs",
"sampling",
"faster"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Lda.php#L75-L127 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Lda.php | Lda.train | public function train(TrainingSet $tset,$it)
{
$docs = $this->generateDocs($tset);
$this->initialize($docs);
while ($it-- > 0) {
$this->gibbsSample($docs);
}
} | php | public function train(TrainingSet $tset,$it)
{
$docs = $this->generateDocs($tset);
$this->initialize($docs);
while ($it-- > 0) {
$this->gibbsSample($docs);
}
} | [
"public",
"function",
"train",
"(",
"TrainingSet",
"$",
"tset",
",",
"$",
"it",
")",
"{",
"$",
"docs",
"=",
"$",
"this",
"->",
"generateDocs",
"(",
"$",
"tset",
")",
";",
"$",
"this",
"->",
"initialize",
"(",
"$",
"docs",
")",
";",
"while",
"(",
... | Run the gibbs sampler $it times.
@param TrainingSet The docs to run lda on
@param $it The number of iterations to run | [
"Run",
"the",
"gibbs",
"sampler",
"$it",
"times",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Lda.php#L135-L144 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Lda.php | Lda.gibbsSample | public function gibbsSample(array &$docs)
{
foreach ($docs as $i=>$doc) {
foreach ($doc as $idx=>$w) {
// remove word $w from the dataset
$topic = $this->word_doc_assigned_topic[$i][$idx];
$this->count_docs_topics[$i][$topic]--;
$this->count_topics_words[$topic][$w]--;
$this->words_in_topic[$topic]--;
$this->words_in_doc[$i]--;
// ---------------------------
// recompute the probabilities of all topics and
// resample a topic for this word $w
$p_topics = $this->conditionalDistribution($i,$w);
$topic = $this->drawIndex($p_topics);
// ---------------------------
// add word $w back into the dataset
if (!isset($this->count_topics_words[$topic][$w]))
$this->count_topics_words[$topic][$w]=0;
$this->count_topics_words[$topic][$w]++;
$this->count_docs_topics[$i][$topic]++;
$this->words_in_topic[$topic]++;
$this->words_in_doc[$i]++;
$this->word_doc_assigned_topic[$i][$idx] = $topic;
// ---------------------------
}
}
} | php | public function gibbsSample(array &$docs)
{
foreach ($docs as $i=>$doc) {
foreach ($doc as $idx=>$w) {
// remove word $w from the dataset
$topic = $this->word_doc_assigned_topic[$i][$idx];
$this->count_docs_topics[$i][$topic]--;
$this->count_topics_words[$topic][$w]--;
$this->words_in_topic[$topic]--;
$this->words_in_doc[$i]--;
// ---------------------------
// recompute the probabilities of all topics and
// resample a topic for this word $w
$p_topics = $this->conditionalDistribution($i,$w);
$topic = $this->drawIndex($p_topics);
// ---------------------------
// add word $w back into the dataset
if (!isset($this->count_topics_words[$topic][$w]))
$this->count_topics_words[$topic][$w]=0;
$this->count_topics_words[$topic][$w]++;
$this->count_docs_topics[$i][$topic]++;
$this->words_in_topic[$topic]++;
$this->words_in_doc[$i]++;
$this->word_doc_assigned_topic[$i][$idx] = $topic;
// ---------------------------
}
}
} | [
"public",
"function",
"gibbsSample",
"(",
"array",
"&",
"$",
"docs",
")",
"{",
"foreach",
"(",
"$",
"docs",
"as",
"$",
"i",
"=>",
"$",
"doc",
")",
"{",
"foreach",
"(",
"$",
"doc",
"as",
"$",
"idx",
"=>",
"$",
"w",
")",
"{",
"// remove word $w from ... | Generate one gibbs sample.
The docs must have been passed to initialize previous to calling
this function.
@param array $docs The docs that we will use to generate the sample | [
"Generate",
"one",
"gibbs",
"sample",
".",
"The",
"docs",
"must",
"have",
"been",
"passed",
"to",
"initialize",
"previous",
"to",
"calling",
"this",
"function",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Lda.php#L153-L183 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Lda.php | Lda.getWordsPerTopicsProbabilities | public function getWordsPerTopicsProbabilities($limit_words=-1)
{
$p_t_w = array_fill_keys(
range(0,$this->ntopics-1),
array()
);
foreach ($p_t_w as $topic=>&$p) {
$denom = $this->words_in_topic[$topic]+$this->voccnt*$this->b;
foreach ($this->voc as $w) {
if (isset($this->count_topics_words[$topic][$w]))
$p[$w] = $this->count_topics_words[$topic][$w]+$this->b;
else
$p[$w] = $this->b;
$p[$w] /= $denom;
}
if ($limit_words>0) {
arsort($p);
$p = array_slice($p,0,$limit_words,true); // true to preserve the keys
}
}
return $p_t_w;
} | php | public function getWordsPerTopicsProbabilities($limit_words=-1)
{
$p_t_w = array_fill_keys(
range(0,$this->ntopics-1),
array()
);
foreach ($p_t_w as $topic=>&$p) {
$denom = $this->words_in_topic[$topic]+$this->voccnt*$this->b;
foreach ($this->voc as $w) {
if (isset($this->count_topics_words[$topic][$w]))
$p[$w] = $this->count_topics_words[$topic][$w]+$this->b;
else
$p[$w] = $this->b;
$p[$w] /= $denom;
}
if ($limit_words>0) {
arsort($p);
$p = array_slice($p,0,$limit_words,true); // true to preserve the keys
}
}
return $p_t_w;
} | [
"public",
"function",
"getWordsPerTopicsProbabilities",
"(",
"$",
"limit_words",
"=",
"-",
"1",
")",
"{",
"$",
"p_t_w",
"=",
"array_fill_keys",
"(",
"range",
"(",
"0",
",",
"$",
"this",
"->",
"ntopics",
"-",
"1",
")",
",",
"array",
"(",
")",
")",
";",
... | Get the probability of a word given a topic (phi according to
Griffiths and Steyvers)
@param $limit_words Limit the results to the top n words
@return array A two dimensional array that contains the probabilities for each topic | [
"Get",
"the",
"probability",
"of",
"a",
"word",
"given",
"a",
"topic",
"(",
"phi",
"according",
"to",
"Griffiths",
"and",
"Steyvers",
")"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Lda.php#L192-L214 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Lda.php | Lda.getDocumentsPerTopicsProbabilities | public function getDocumentsPerTopicsProbabilities($limit_docs=-1)
{
$p_t_d = array_fill_keys(
range(0,$this->ntopics-1),
array()
);
$doccnt = count($this->words_in_doc);
$denom = $doccnt + $this->ntopics*$this->a;
$count_topics_docs = array();
foreach ($this->count_docs_topics as $doc=>$topics) {
foreach ($topics as $t=>$c)
$count_topics_docs[$doc][$t]++;
}
foreach ($p_t_d as $topic=>&$p) {
foreach ($count_topics_docs as $doc=>$tc) {
$p[$doc] = ($tc[$topic] + $this->a)/$denom;
}
if ($limit_words>0) {
arsort($p);
$p = array_slice($p,0,$limit_words,true); // true to preserve the keys
}
}
return $p;
} | php | public function getDocumentsPerTopicsProbabilities($limit_docs=-1)
{
$p_t_d = array_fill_keys(
range(0,$this->ntopics-1),
array()
);
$doccnt = count($this->words_in_doc);
$denom = $doccnt + $this->ntopics*$this->a;
$count_topics_docs = array();
foreach ($this->count_docs_topics as $doc=>$topics) {
foreach ($topics as $t=>$c)
$count_topics_docs[$doc][$t]++;
}
foreach ($p_t_d as $topic=>&$p) {
foreach ($count_topics_docs as $doc=>$tc) {
$p[$doc] = ($tc[$topic] + $this->a)/$denom;
}
if ($limit_words>0) {
arsort($p);
$p = array_slice($p,0,$limit_words,true); // true to preserve the keys
}
}
return $p;
} | [
"public",
"function",
"getDocumentsPerTopicsProbabilities",
"(",
"$",
"limit_docs",
"=",
"-",
"1",
")",
"{",
"$",
"p_t_d",
"=",
"array_fill_keys",
"(",
"range",
"(",
"0",
",",
"$",
"this",
"->",
"ntopics",
"-",
"1",
")",
",",
"array",
"(",
")",
")",
";... | Get the probability of a document given a topic (theta according
to Griffiths and Steyvers)
@param $limit_docs Limit the results to the top n docs
@return array A two dimensional array that contains the probabilities for each document | [
"Get",
"the",
"probability",
"of",
"a",
"document",
"given",
"a",
"topic",
"(",
"theta",
"according",
"to",
"Griffiths",
"and",
"Steyvers",
")"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Lda.php#L231-L257 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Lda.php | Lda.getLogLikelihood | public function getLogLikelihood()
{
$voccnt = $this->voccnt;
$lik = 0;
$b = $this->b;
$a = $this->a;
foreach ($this->count_topics_words as $topic=>$words) {
$lik += $this->log_multi_beta(
$words,
$b
);
$lik -= $this->log_multi_beta(
$b,
0,
$voccnt
);
}
foreach ($this->count_docs_topics as $doc=>$topics) {
$lik += $this->log_multi_beta(
$topics,
$a
);
$lik -= $this->log_multi_beta(
$a,
0,
$this->ntopics
);
}
return $lik;
} | php | public function getLogLikelihood()
{
$voccnt = $this->voccnt;
$lik = 0;
$b = $this->b;
$a = $this->a;
foreach ($this->count_topics_words as $topic=>$words) {
$lik += $this->log_multi_beta(
$words,
$b
);
$lik -= $this->log_multi_beta(
$b,
0,
$voccnt
);
}
foreach ($this->count_docs_topics as $doc=>$topics) {
$lik += $this->log_multi_beta(
$topics,
$a
);
$lik -= $this->log_multi_beta(
$a,
0,
$this->ntopics
);
}
return $lik;
} | [
"public",
"function",
"getLogLikelihood",
"(",
")",
"{",
"$",
"voccnt",
"=",
"$",
"this",
"->",
"voccnt",
";",
"$",
"lik",
"=",
"0",
";",
"$",
"b",
"=",
"$",
"this",
"->",
"b",
";",
"$",
"a",
"=",
"$",
"this",
"->",
"a",
";",
"foreach",
"(",
... | Log likelihood of the model having generated the data as
implemented by M. Blondel | [
"Log",
"likelihood",
"of",
"the",
"model",
"having",
"generated",
"the",
"data",
"as",
"implemented",
"by",
"M",
".",
"Blondel"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Lda.php#L271-L301 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Lda.php | Lda.conditionalDistribution | protected function conditionalDistribution($i,$w)
{
$p = array_fill_keys(range(0,$this->ntopics-1),0);
for ($topic=0;$topic<$this->ntopics;$topic++) {
if (isset($this->count_topics_words[$topic][$w]))
$numerator = $this->count_topics_words[$topic][$w]+$this->b;
else
$numerator = $this->b;
$numerator *= $this->count_docs_topics[$i][$topic]+$this->a;
$denominator = $this->words_in_topic[$topic]+$this->voccnt*$this->b;
$denominator *= $this->words_in_doc[$i]+$this->ntopics*$this->a;
$p[$topic] = $numerator/$denominator;
}
// divide by sum to obtain probabilities
$sum = array_sum($p);
return array_map(
function ($p) use ($sum) {
return $p/$sum;
},
$p
);
} | php | protected function conditionalDistribution($i,$w)
{
$p = array_fill_keys(range(0,$this->ntopics-1),0);
for ($topic=0;$topic<$this->ntopics;$topic++) {
if (isset($this->count_topics_words[$topic][$w]))
$numerator = $this->count_topics_words[$topic][$w]+$this->b;
else
$numerator = $this->b;
$numerator *= $this->count_docs_topics[$i][$topic]+$this->a;
$denominator = $this->words_in_topic[$topic]+$this->voccnt*$this->b;
$denominator *= $this->words_in_doc[$i]+$this->ntopics*$this->a;
$p[$topic] = $numerator/$denominator;
}
// divide by sum to obtain probabilities
$sum = array_sum($p);
return array_map(
function ($p) use ($sum) {
return $p/$sum;
},
$p
);
} | [
"protected",
"function",
"conditionalDistribution",
"(",
"$",
"i",
",",
"$",
"w",
")",
"{",
"$",
"p",
"=",
"array_fill_keys",
"(",
"range",
"(",
"0",
",",
"$",
"this",
"->",
"ntopics",
"-",
"1",
")",
",",
"0",
")",
";",
"for",
"(",
"$",
"topic",
... | This is the implementation of the equation number 5 in the paper
by Griffiths and Steyvers.
@return array The vector of probabilites for all topics as computed by the equation 5 | [
"This",
"is",
"the",
"implementation",
"of",
"the",
"equation",
"number",
"5",
"in",
"the",
"paper",
"by",
"Griffiths",
"and",
"Steyvers",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Lda.php#L309-L335 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Lda.php | Lda.drawIndex | protected function drawIndex(array $d)
{
$x = $this->mt->generate();
$p = 0.0;
foreach ($d as $i=>$v) {
$p+=$v;
if ($p > $x)
return $i;
}
} | php | protected function drawIndex(array $d)
{
$x = $this->mt->generate();
$p = 0.0;
foreach ($d as $i=>$v) {
$p+=$v;
if ($p > $x)
return $i;
}
} | [
"protected",
"function",
"drawIndex",
"(",
"array",
"$",
"d",
")",
"{",
"$",
"x",
"=",
"$",
"this",
"->",
"mt",
"->",
"generate",
"(",
")",
";",
"$",
"p",
"=",
"0.0",
";",
"foreach",
"(",
"$",
"d",
"as",
"$",
"i",
"=>",
"$",
"v",
")",
"{",
... | Draw once from a multinomial distribution and return the index
of that is drawn.
@return int The index that was drawn. | [
"Draw",
"once",
"from",
"a",
"multinomial",
"distribution",
"and",
"return",
"the",
"index",
"of",
"that",
"is",
"drawn",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Lda.php#L343-L352 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Lda.php | Lda.gamma | private function gamma($x)
{
$gamma = 0.577215664901532860606512090; # Euler's gamma constant
if ($x < 0.001) {
return 1.0/($x*(1.0 + $gamma*$x));
}
if ($x < 12.0) {
# The algorithm directly approximates gamma over (1,2) and uses
# reduction identities to reduce other arguments to this interval.
$y = $x;
$n = 0;
$arg_was_less_than_one = ($y < 1.0);
# Add or subtract integers as necessary to bring y into (1,2)
# Will correct for this below
if ($arg_was_less_than_one) {
$y += 1.0;
} else {
$n = floor($y) - 1; # will use n later
$y -= $n;
}
# numerator coefficients for approximation over the interval (1,2)
$p =
array(
-1.71618513886549492533811E+0,
2.47656508055759199108314E+1,
-3.79804256470945635097577E+2,
6.29331155312818442661052E+2,
8.66966202790413211295064E+2,
-3.14512729688483675254357E+4,
-3.61444134186911729807069E+4,
6.64561438202405440627855E+4
);
# denominator coefficients for approximation over the interval (1,2)
$q =
array(
-3.08402300119738975254353E+1,
3.15350626979604161529144E+2,
-1.01515636749021914166146E+3,
-3.10777167157231109440444E+3,
2.25381184209801510330112E+4,
4.75584627752788110767815E+3,
-1.34659959864969306392456E+5,
-1.15132259675553483497211E+5
);
$num = 0.0;
$den = 1.0;
$z = $y - 1;
for ($i = 0; $i < 8; $i++) {
$num = ($num + $p[$i])*$z;
$den = $den*$z + $q[$i];
}
$result = $num/$den + 1.0;
# Apply correction if argument was not initially in (1,2)
if ($arg_was_less_than_one) {
# Use identity gamma(z) = gamma(z+1)/z
# The variable "result" now holds gamma of the original y + 1
# Thus we use y-1 to get back the orginal y.
$result /= ($y-1.0);
} else {
# Use the identity gamma(z+n) = z*(z+1)* ... *(z+n-1)*gamma(z)
for ($i = 0; $i < $n; $i++) {
$result *= $y++;
}
}
return $result;
}
###########################################################################
# Third interval: [12, infinity)
if ($x > 171.624) {
# Correct answer too large to display.
return Double.POSITIVE_INFINITY;
}
return exp($this->log_gamma($x));
} | php | private function gamma($x)
{
$gamma = 0.577215664901532860606512090; # Euler's gamma constant
if ($x < 0.001) {
return 1.0/($x*(1.0 + $gamma*$x));
}
if ($x < 12.0) {
# The algorithm directly approximates gamma over (1,2) and uses
# reduction identities to reduce other arguments to this interval.
$y = $x;
$n = 0;
$arg_was_less_than_one = ($y < 1.0);
# Add or subtract integers as necessary to bring y into (1,2)
# Will correct for this below
if ($arg_was_less_than_one) {
$y += 1.0;
} else {
$n = floor($y) - 1; # will use n later
$y -= $n;
}
# numerator coefficients for approximation over the interval (1,2)
$p =
array(
-1.71618513886549492533811E+0,
2.47656508055759199108314E+1,
-3.79804256470945635097577E+2,
6.29331155312818442661052E+2,
8.66966202790413211295064E+2,
-3.14512729688483675254357E+4,
-3.61444134186911729807069E+4,
6.64561438202405440627855E+4
);
# denominator coefficients for approximation over the interval (1,2)
$q =
array(
-3.08402300119738975254353E+1,
3.15350626979604161529144E+2,
-1.01515636749021914166146E+3,
-3.10777167157231109440444E+3,
2.25381184209801510330112E+4,
4.75584627752788110767815E+3,
-1.34659959864969306392456E+5,
-1.15132259675553483497211E+5
);
$num = 0.0;
$den = 1.0;
$z = $y - 1;
for ($i = 0; $i < 8; $i++) {
$num = ($num + $p[$i])*$z;
$den = $den*$z + $q[$i];
}
$result = $num/$den + 1.0;
# Apply correction if argument was not initially in (1,2)
if ($arg_was_less_than_one) {
# Use identity gamma(z) = gamma(z+1)/z
# The variable "result" now holds gamma of the original y + 1
# Thus we use y-1 to get back the orginal y.
$result /= ($y-1.0);
} else {
# Use the identity gamma(z+n) = z*(z+1)* ... *(z+n-1)*gamma(z)
for ($i = 0; $i < $n; $i++) {
$result *= $y++;
}
}
return $result;
}
###########################################################################
# Third interval: [12, infinity)
if ($x > 171.624) {
# Correct answer too large to display.
return Double.POSITIVE_INFINITY;
}
return exp($this->log_gamma($x));
} | [
"private",
"function",
"gamma",
"(",
"$",
"x",
")",
"{",
"$",
"gamma",
"=",
"0.577215664901532860606512090",
";",
"# Euler's gamma constant",
"if",
"(",
"$",
"x",
"<",
"0.001",
")",
"{",
"return",
"1.0",
"/",
"(",
"$",
"x",
"*",
"(",
"1.0",
"+",
"$",
... | Gamma function from picomath.org
see http://picomath.org/php/gamma.php.html for commented
implementation
TODO: These should probably move outside of NlpTools together
with the Random namespace and form a nice php math library | [
"Gamma",
"function",
"from",
"picomath",
".",
"org",
"see",
"http",
":",
"//",
"picomath",
".",
"org",
"/",
"php",
"/",
"gamma",
".",
"php",
".",
"html",
"for",
"commented",
"implementation"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Lda.php#L362-L444 |
angeloskath/php-nlp-tools | src/NlpTools/Random/Generators/FromFile.php | FromFile.generate | public function generate()
{
if (feof($this->h))
rewind($this->h);
return (float) fgets($this->h);
} | php | public function generate()
{
if (feof($this->h))
rewind($this->h);
return (float) fgets($this->h);
} | [
"public",
"function",
"generate",
"(",
")",
"{",
"if",
"(",
"feof",
"(",
"$",
"this",
"->",
"h",
")",
")",
"rewind",
"(",
"$",
"this",
"->",
"h",
")",
";",
"return",
"(",
"float",
")",
"fgets",
"(",
"$",
"this",
"->",
"h",
")",
";",
"}"
] | Read a float from a file and return it. It doesn't do anything
to make sure that the float returned will be in the appropriate
range.
If the file has reached its end it rewinds the file pointer.
@return float A random float in the range (0,1) | [
"Read",
"a",
"float",
"from",
"a",
"file",
"and",
"return",
"it",
".",
"It",
"doesn",
"t",
"do",
"anything",
"to",
"make",
"sure",
"that",
"the",
"float",
"returned",
"will",
"be",
"in",
"the",
"appropriate",
"range",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Random/Generators/FromFile.php#L32-L38 |
angeloskath/php-nlp-tools | src/NlpTools/Utils/ClassifierBasedTransformation.php | ClassifierBasedTransformation.transform | public function transform($w)
{
$class = $this->cls->classify(
$this->classes,
new RawDocument($w)
);
foreach ($this->transforms[$class] as $t) {
$w = $t->transform($w);
}
return $w;
} | php | public function transform($w)
{
$class = $this->cls->classify(
$this->classes,
new RawDocument($w)
);
foreach ($this->transforms[$class] as $t) {
$w = $t->transform($w);
}
return $w;
} | [
"public",
"function",
"transform",
"(",
"$",
"w",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"cls",
"->",
"classify",
"(",
"$",
"this",
"->",
"classes",
",",
"new",
"RawDocument",
"(",
"$",
"w",
")",
")",
";",
"foreach",
"(",
"$",
"this",
"-... | Classify the passed in variable w and then apply each transformation
to the output of the previous one. | [
"Classify",
"the",
"passed",
"in",
"variable",
"w",
"and",
"then",
"apply",
"each",
"transformation",
"to",
"the",
"output",
"of",
"the",
"previous",
"one",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Utils/ClassifierBasedTransformation.php#L38-L50 |
angeloskath/php-nlp-tools | src/NlpTools/Utils/ClassifierBasedTransformation.php | ClassifierBasedTransformation.register | public function register($class, $transforms)
{
if (!is_array($transforms)) {
$transforms = array($transforms);
}
foreach ($transforms as $t) {
if (!($t instanceof TransformationInterface)) {
throw new \InvalidArgumentException("Only instances of TransformationInterface can be registered");
}
}
if (!isset($this->transforms[$class])) {
$this->classes[] = $class;
$this->transforms[$class] = array();
}
foreach ($transforms as $t) {
$this->transforms[$class][] = $t;
}
} | php | public function register($class, $transforms)
{
if (!is_array($transforms)) {
$transforms = array($transforms);
}
foreach ($transforms as $t) {
if (!($t instanceof TransformationInterface)) {
throw new \InvalidArgumentException("Only instances of TransformationInterface can be registered");
}
}
if (!isset($this->transforms[$class])) {
$this->classes[] = $class;
$this->transforms[$class] = array();
}
foreach ($transforms as $t) {
$this->transforms[$class][] = $t;
}
} | [
"public",
"function",
"register",
"(",
"$",
"class",
",",
"$",
"transforms",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"transforms",
")",
")",
"{",
"$",
"transforms",
"=",
"array",
"(",
"$",
"transforms",
")",
";",
"}",
"foreach",
"(",
"$",
"... | Register a set of transformations for a given class.
@param string $class
@param array|TransformationInterface Either an array of transformations or a single transformation | [
"Register",
"a",
"set",
"of",
"transformations",
"for",
"a",
"given",
"class",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Utils/ClassifierBasedTransformation.php#L58-L77 |
angeloskath/php-nlp-tools | src/NlpTools/Similarity/OverlapCoefficient.php | OverlapCoefficient.similarity | public function similarity(&$A, &$B)
{
// Make the arrays into sets
$a = array_fill_keys($A,1);
$b = array_fill_keys($B,1);
// Count the cardinalities of the sets
$a_count = count($a);
$b_count = count($b);
if ($a_count == 0 || $b_count == 0) {
return 0;
}
// Compute the intersection and count its cardinality
$intersect = count(array_intersect_key($a,$b));
return $intersect/min($a_count,$b_count);
} | php | public function similarity(&$A, &$B)
{
// Make the arrays into sets
$a = array_fill_keys($A,1);
$b = array_fill_keys($B,1);
// Count the cardinalities of the sets
$a_count = count($a);
$b_count = count($b);
if ($a_count == 0 || $b_count == 0) {
return 0;
}
// Compute the intersection and count its cardinality
$intersect = count(array_intersect_key($a,$b));
return $intersect/min($a_count,$b_count);
} | [
"public",
"function",
"similarity",
"(",
"&",
"$",
"A",
",",
"&",
"$",
"B",
")",
"{",
"// Make the arrays into sets",
"$",
"a",
"=",
"array_fill_keys",
"(",
"$",
"A",
",",
"1",
")",
";",
"$",
"b",
"=",
"array_fill_keys",
"(",
"$",
"B",
",",
"1",
")... | The similarity returned by this algorithm is a number between 0,1 | [
"The",
"similarity",
"returned",
"by",
"this",
"algorithm",
"is",
"a",
"number",
"between",
"0",
"1"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Similarity/OverlapCoefficient.php#L13-L31 |
angeloskath/php-nlp-tools | src/NlpTools/Tokenizers/ClassifierBasedTokenizer.php | ClassifierBasedTokenizer.tokenize | public function tokenize($str)
{
// split the string in tokens and create documents to be
// classified
$tokens = $this->tok->tokenize($str);
$docs = array();
foreach ($tokens as $offset=>$tok) {
$docs[] = new WordDocument($tokens,$offset,5);
}
// classify each token as an EOW or O
$tags = array();
foreach ($docs as $doc) {
$tags[] = $this->classifier->classify(self::$classSet, $doc);
}
// merge O and EOW into real tokens
$realtokens = array();
$currentToken = array();
foreach ($tokens as $offset=>$tok) {
$currentToken[] = $tok;
if ($tags[$offset] == self::EOW) {
$realtokens[] = implode($this->sep,$currentToken);
$currentToken = array();
}
}
// return real tokens
return $realtokens;
} | php | public function tokenize($str)
{
// split the string in tokens and create documents to be
// classified
$tokens = $this->tok->tokenize($str);
$docs = array();
foreach ($tokens as $offset=>$tok) {
$docs[] = new WordDocument($tokens,$offset,5);
}
// classify each token as an EOW or O
$tags = array();
foreach ($docs as $doc) {
$tags[] = $this->classifier->classify(self::$classSet, $doc);
}
// merge O and EOW into real tokens
$realtokens = array();
$currentToken = array();
foreach ($tokens as $offset=>$tok) {
$currentToken[] = $tok;
if ($tags[$offset] == self::EOW) {
$realtokens[] = implode($this->sep,$currentToken);
$currentToken = array();
}
}
// return real tokens
return $realtokens;
} | [
"public",
"function",
"tokenize",
"(",
"$",
"str",
")",
"{",
"// split the string in tokens and create documents to be",
"// classified",
"$",
"tokens",
"=",
"$",
"this",
"->",
"tok",
"->",
"tokenize",
"(",
"$",
"str",
")",
";",
"$",
"docs",
"=",
"array",
"(",... | Tokenize the string.
1. Break up the string in tokens using the initial tokenizer
2. Classify each token if it is an EOW
3. For each token that is not an EOW add it to the next EOW token using a separator
@param string $str The character sequence to be broken in tokens
@return array The token array | [
"Tokenize",
"the",
"string",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Tokenizers/ClassifierBasedTokenizer.php#L77-L106 |
angeloskath/php-nlp-tools | src/NlpTools/Clustering/CentroidFactories/Hamming.php | Hamming.getCentroid | public function getCentroid(array &$docs, array $choose=array())
{
$bitl = strlen($docs[0]);
$buckets = array_fill_keys(
range(0,$bitl-1),
0
);
if (empty($choose))
$choose = range(0,count($docs)-1);
foreach ($choose as $idx) {
$s = $docs[$idx];
foreach ($buckets as $i=>&$v) {
if ($s[$i]=='1')
$v += 1;
else
$v -= 1;
}
}
return implode(
'',
array_map(
function ($v) {
return ($v>0) ? '1' : '0';
},
$buckets
)
);
} | php | public function getCentroid(array &$docs, array $choose=array())
{
$bitl = strlen($docs[0]);
$buckets = array_fill_keys(
range(0,$bitl-1),
0
);
if (empty($choose))
$choose = range(0,count($docs)-1);
foreach ($choose as $idx) {
$s = $docs[$idx];
foreach ($buckets as $i=>&$v) {
if ($s[$i]=='1')
$v += 1;
else
$v -= 1;
}
}
return implode(
'',
array_map(
function ($v) {
return ($v>0) ? '1' : '0';
},
$buckets
)
);
} | [
"public",
"function",
"getCentroid",
"(",
"array",
"&",
"$",
"docs",
",",
"array",
"$",
"choose",
"=",
"array",
"(",
")",
")",
"{",
"$",
"bitl",
"=",
"strlen",
"(",
"$",
"docs",
"[",
"0",
"]",
")",
";",
"$",
"buckets",
"=",
"array_fill_keys",
"(",
... | Return a number in binary encoding in a string such that the sum of its
hamming distances of each document is minimized.
Assumptions: The docs array should contain strings that are properly padded
binary (they should all be the same length). | [
"Return",
"a",
"number",
"in",
"binary",
"encoding",
"in",
"a",
"string",
"such",
"that",
"the",
"sum",
"of",
"its",
"hamming",
"distances",
"of",
"each",
"document",
"is",
"minimized",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Clustering/CentroidFactories/Hamming.php#L20-L48 |
angeloskath/php-nlp-tools | src/NlpTools/Similarity/HammingDistance.php | HammingDistance.dist | public function dist(&$A, &$B)
{
$l1 = strlen($A);
$l2 = strlen($B);
$l = min($l1,$l2);
$d = 0;
for ($i=0;$i<$l;$i++) {
$d += (int) ($A[$i]!=$B[$i]);
}
return $d + (int) abs($l1-$l2);
} | php | public function dist(&$A, &$B)
{
$l1 = strlen($A);
$l2 = strlen($B);
$l = min($l1,$l2);
$d = 0;
for ($i=0;$i<$l;$i++) {
$d += (int) ($A[$i]!=$B[$i]);
}
return $d + (int) abs($l1-$l2);
} | [
"public",
"function",
"dist",
"(",
"&",
"$",
"A",
",",
"&",
"$",
"B",
")",
"{",
"$",
"l1",
"=",
"strlen",
"(",
"$",
"A",
")",
";",
"$",
"l2",
"=",
"strlen",
"(",
"$",
"B",
")",
";",
"$",
"l",
"=",
"min",
"(",
"$",
"l1",
",",
"$",
"l2",
... | Count the number of positions that A and B differ.
@param string $A
@param string $B
@return int The hamming distance of the two strings A and B | [
"Count",
"the",
"number",
"of",
"positions",
"that",
"A",
"and",
"B",
"differ",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Similarity/HammingDistance.php#L19-L30 |
angeloskath/php-nlp-tools | src/NlpTools/Documents/TokensDocument.php | TokensDocument.applyTransformation | public function applyTransformation(TransformationInterface $transform)
{
// array_values for re-indexing
$this->tokens = array_values(
array_filter(
array_map(
array($transform, 'transform'),
$this->tokens
),
function ($token) {
return $token!==null;
}
)
);
} | php | public function applyTransformation(TransformationInterface $transform)
{
// array_values for re-indexing
$this->tokens = array_values(
array_filter(
array_map(
array($transform, 'transform'),
$this->tokens
),
function ($token) {
return $token!==null;
}
)
);
} | [
"public",
"function",
"applyTransformation",
"(",
"TransformationInterface",
"$",
"transform",
")",
"{",
"// array_values for re-indexing",
"$",
"this",
"->",
"tokens",
"=",
"array_values",
"(",
"array_filter",
"(",
"array_map",
"(",
"array",
"(",
"$",
"transform",
... | Apply the transform to each token. Filter out the null tokens.
@param TransformationInterface $transform The transformation to be applied | [
"Apply",
"the",
"transform",
"to",
"each",
"token",
".",
"Filter",
"out",
"the",
"null",
"tokens",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Documents/TokensDocument.php#L31-L45 |
angeloskath/php-nlp-tools | src/NlpTools/Similarity/TverskyIndex.php | TverskyIndex.similarity | public function similarity(&$A, &$B)
{
$alpha = $this->alpha;
$beta = $this->beta;
$a = array_fill_keys($A,1);
$b = array_fill_keys($B,1);
$min = min(count(array_diff_key($a,$b)),count(array_diff_key($b, $a)));
$max = max(count(array_diff_key($a,$b)),count(array_diff_key($b, $a)));
$intersect = count(array_intersect_key($a,$b));
return $intersect/($intersect + ($beta * ($alpha * $min + $max*(1-$alpha)) ));
} | php | public function similarity(&$A, &$B)
{
$alpha = $this->alpha;
$beta = $this->beta;
$a = array_fill_keys($A,1);
$b = array_fill_keys($B,1);
$min = min(count(array_diff_key($a,$b)),count(array_diff_key($b, $a)));
$max = max(count(array_diff_key($a,$b)),count(array_diff_key($b, $a)));
$intersect = count(array_intersect_key($a,$b));
return $intersect/($intersect + ($beta * ($alpha * $min + $max*(1-$alpha)) ));
} | [
"public",
"function",
"similarity",
"(",
"&",
"$",
"A",
",",
"&",
"$",
"B",
")",
"{",
"$",
"alpha",
"=",
"$",
"this",
"->",
"alpha",
";",
"$",
"beta",
"=",
"$",
"this",
"->",
"beta",
";",
"$",
"a",
"=",
"array_fill_keys",
"(",
"$",
"A",
",",
... | Compute the similarity using the alpha and beta values given in the
constructor.
@param array $A
@param array $B
@return float | [
"Compute",
"the",
"similarity",
"using",
"the",
"alpha",
"and",
"beta",
"values",
"given",
"in",
"the",
"constructor",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Similarity/TverskyIndex.php#L36-L50 |
angeloskath/php-nlp-tools | src/NlpTools/Clustering/Hierarchical.php | Hierarchical.cluster | public function cluster(TrainingSet $documents, FeatureFactoryInterface $ff)
{
// what a complete waste of memory here ...
// the same data exists in $documents, $docs and
// the only useful parts are in $this->strategy
$docs = $this->getDocumentArray($documents, $ff);
$this->strategy->initializeStrategy($this->dist,$docs);
unset($docs); // perhaps save some memory
// start with all the documents being in their
// own cluster we 'll merge later
$clusters = range(0,count($documents)-1);
$c = count($clusters);
while ($c>1) {
// ask the strategy which to merge. The strategy
// will assume that we will indeed merge the returned clusters
list($i,$j) = $this->strategy->getNextMerge();
$clusters[$i] = array($clusters[$i],$clusters[$j]);
unset($clusters[$j]);
$c--;
}
$clusters = array($clusters[$i]);
// return the dendrogram
return array($clusters);
} | php | public function cluster(TrainingSet $documents, FeatureFactoryInterface $ff)
{
// what a complete waste of memory here ...
// the same data exists in $documents, $docs and
// the only useful parts are in $this->strategy
$docs = $this->getDocumentArray($documents, $ff);
$this->strategy->initializeStrategy($this->dist,$docs);
unset($docs); // perhaps save some memory
// start with all the documents being in their
// own cluster we 'll merge later
$clusters = range(0,count($documents)-1);
$c = count($clusters);
while ($c>1) {
// ask the strategy which to merge. The strategy
// will assume that we will indeed merge the returned clusters
list($i,$j) = $this->strategy->getNextMerge();
$clusters[$i] = array($clusters[$i],$clusters[$j]);
unset($clusters[$j]);
$c--;
}
$clusters = array($clusters[$i]);
// return the dendrogram
return array($clusters);
} | [
"public",
"function",
"cluster",
"(",
"TrainingSet",
"$",
"documents",
",",
"FeatureFactoryInterface",
"$",
"ff",
")",
"{",
"// what a complete waste of memory here ...",
"// the same data exists in $documents, $docs and",
"// the only useful parts are in $this->strategy",
"$",
"do... | Iteratively merge documents together to create an hierarchy of clusters.
While hierarchical clustering only returns one element, it still wraps it
in an array to be consistent with the rest of the clustering methods.
@return array An array containing one element which is the resulting dendrogram | [
"Iteratively",
"merge",
"documents",
"together",
"to",
"create",
"an",
"hierarchy",
"of",
"clusters",
".",
"While",
"hierarchical",
"clustering",
"only",
"returns",
"one",
"element",
"it",
"still",
"wraps",
"it",
"in",
"an",
"array",
"to",
"be",
"consistent",
... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Clustering/Hierarchical.php#L32-L57 |
angeloskath/php-nlp-tools | src/NlpTools/Clustering/Hierarchical.php | Hierarchical.dendrogramToClusters | public static function dendrogramToClusters($tree,$NC)
{
$clusters = $tree;
while (count($clusters)<$NC) {
$tmpc = array();
foreach ($clusters as $subclust) {
if (!is_array($subclust))
$tmpc[] = $subclust;
else {
foreach ($subclust as $c)
$tmpc[] = $c;
}
}
$clusters = $tmpc;
}
foreach ($clusters as &$c) {
$c = iterator_to_array(
new \RecursiveIteratorIterator(
new \RecursiveArrayIterator(
array($c)
)
),
false // do not use keys
);
}
return $clusters;
} | php | public static function dendrogramToClusters($tree,$NC)
{
$clusters = $tree;
while (count($clusters)<$NC) {
$tmpc = array();
foreach ($clusters as $subclust) {
if (!is_array($subclust))
$tmpc[] = $subclust;
else {
foreach ($subclust as $c)
$tmpc[] = $c;
}
}
$clusters = $tmpc;
}
foreach ($clusters as &$c) {
$c = iterator_to_array(
new \RecursiveIteratorIterator(
new \RecursiveArrayIterator(
array($c)
)
),
false // do not use keys
);
}
return $clusters;
} | [
"public",
"static",
"function",
"dendrogramToClusters",
"(",
"$",
"tree",
",",
"$",
"NC",
")",
"{",
"$",
"clusters",
"=",
"$",
"tree",
";",
"while",
"(",
"count",
"(",
"$",
"clusters",
")",
"<",
"$",
"NC",
")",
"{",
"$",
"tmpc",
"=",
"array",
"(",
... | Flatten a dendrogram to an almost specific
number of clusters (the closest power of 2 larger than
$NC)
@param array $tree The dendrogram to be flattened
@param integer $NC The number of clusters to cut to
@return array The flat clusters | [
"Flatten",
"a",
"dendrogram",
"to",
"an",
"almost",
"specific",
"number",
"of",
"clusters",
"(",
"the",
"closest",
"power",
"of",
"2",
"larger",
"than",
"$NC",
")"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Clustering/Hierarchical.php#L68-L95 |
angeloskath/php-nlp-tools | src/NlpTools/Classifiers/FeatureBasedLinearClassifier.php | FeatureBasedLinearClassifier.classify | public function classify(array $classes, DocumentInterface $d)
{
$maxclass = current($classes);
$maxvote = $this->getVote($maxclass,$d);
while ($class = next($classes)) {
$v = $this->getVote($class,$d);
if ($v>$maxvote) {
$maxclass = $class;
$maxvote = $v;
}
}
return $maxclass;
} | php | public function classify(array $classes, DocumentInterface $d)
{
$maxclass = current($classes);
$maxvote = $this->getVote($maxclass,$d);
while ($class = next($classes)) {
$v = $this->getVote($class,$d);
if ($v>$maxvote) {
$maxclass = $class;
$maxvote = $v;
}
}
return $maxclass;
} | [
"public",
"function",
"classify",
"(",
"array",
"$",
"classes",
",",
"DocumentInterface",
"$",
"d",
")",
"{",
"$",
"maxclass",
"=",
"current",
"(",
"$",
"classes",
")",
";",
"$",
"maxvote",
"=",
"$",
"this",
"->",
"getVote",
"(",
"$",
"maxclass",
",",
... | Compute the vote for every class. Return the class that
receive the maximum vote.
@param array $classes A set of classes
@param DocumentInterface $d A Document
@return string A class | [
"Compute",
"the",
"vote",
"for",
"every",
"class",
".",
"Return",
"the",
"class",
"that",
"receive",
"the",
"maximum",
"vote",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Classifiers/FeatureBasedLinearClassifier.php#L34-L47 |
angeloskath/php-nlp-tools | src/NlpTools/Classifiers/FeatureBasedLinearClassifier.php | FeatureBasedLinearClassifier.getVote | public function getVote($class, DocumentInterface $d)
{
$v = 0;
$features = $this->feature_factory->getFeatureArray($class,$d);
foreach ($features as $f) {
$v += $this->model->getWeight($f);
}
return $v;
} | php | public function getVote($class, DocumentInterface $d)
{
$v = 0;
$features = $this->feature_factory->getFeatureArray($class,$d);
foreach ($features as $f) {
$v += $this->model->getWeight($f);
}
return $v;
} | [
"public",
"function",
"getVote",
"(",
"$",
"class",
",",
"DocumentInterface",
"$",
"d",
")",
"{",
"$",
"v",
"=",
"0",
";",
"$",
"features",
"=",
"$",
"this",
"->",
"feature_factory",
"->",
"getFeatureArray",
"(",
"$",
"class",
",",
"$",
"d",
")",
";"... | Compute the features that fire for the Document $d. The sum of
the weights of the features is the vote.
@param string $class The vote for class $class
@param DocumentInterface $d The vote for Document $d
@return float The vote of the model for class $class and Document $d | [
"Compute",
"the",
"features",
"that",
"fire",
"for",
"the",
"Document",
"$d",
".",
"The",
"sum",
"of",
"the",
"weights",
"of",
"the",
"features",
"is",
"the",
"vote",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Classifiers/FeatureBasedLinearClassifier.php#L57-L66 |
angeloskath/php-nlp-tools | src/NlpTools/Analysis/Idf.php | Idf.offsetGet | public function offsetGet($token)
{
if (isset($this->idf[$token])) {
return $this->idf[$token];
} else {
return $this->logD;
}
} | php | public function offsetGet($token)
{
if (isset($this->idf[$token])) {
return $this->idf[$token];
} else {
return $this->logD;
}
} | [
"public",
"function",
"offsetGet",
"(",
"$",
"token",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"idf",
"[",
"$",
"token",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"idf",
"[",
"$",
"token",
"]",
";",
"}",
"else",
"{",
"return... | Implements the array access interface. Return the computed idf or
the logarithm of the count of the documents for a token we have not
seen before.
@param string $token The token to return the idf for
@return float The idf | [
"Implements",
"the",
"array",
"access",
"interface",
".",
"Return",
"the",
"computed",
"idf",
"or",
"the",
"logarithm",
"of",
"the",
"count",
"of",
"the",
"documents",
"for",
"a",
"token",
"we",
"have",
"not",
"seen",
"before",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Analysis/Idf.php#L61-L68 |
angeloskath/php-nlp-tools | src/NlpTools/Clustering/KMeans.php | KMeans.cluster | public function cluster(TrainingSet $documents, FeatureFactoryInterface $ff)
{
// transform the documents according to the FeatureFactory
$docs = $this->getDocumentArray($documents,$ff);
// choose N centroids at random
$centroids = array();
foreach (array_rand($docs,$this->n) as $key) {
$centroids[] = $docs[$key];
}
// cache the distance and centroid factory functions for use
// with closures
$dist = array($this->dist,'dist');
$cf = array($this->centroidF,'getCentroid');
// looooooooop
while (true) {
// compute the distance each document has from our centroids
// the array is MxN where M = count($docs) and N = count($centroids)
$distances = array_map(
function ($doc) use (&$centroids,$dist) {
return array_map(
function ($c) use ($dist,$doc) {
// it is passed with an array because dist expects references
// and it failed when run with phpunit.
// see http://php.net/manual/en/function.call-user-func.php
// for the solution used below
return call_user_func_array(
$dist,
array(
&$c,
&$doc
)
);
},
$centroids
);
},
$docs
);
// initialize the empty clusters
$clusters = array_fill_keys(
array_keys($centroids),
array()
);
foreach ($distances as $idx=>$d) {
// assign document idx to the closest centroid
$clusters[array_search(min($d),$d)][] = $idx;
}
// compute the new centroids from the assigned documents
// using the centroid factory function
$new_centroids = array_map(
function ($cluster) use (&$docs,$cf) {
return call_user_func_array(
$cf,
array(
&$docs,
$cluster
)
);
},
$clusters
);
// compute the change each centroid had from the previous one
$changes = array_map(
$dist,
$new_centroids,
$centroids
);
// if the largest change is small enough we are done
if (max($changes)<$this->cutoff) {
// return the clusters, the centroids and the distances
return array($clusters,$centroids,$distances);
}
// update the centroids and loooooop again
$centroids = $new_centroids;
}
} | php | public function cluster(TrainingSet $documents, FeatureFactoryInterface $ff)
{
// transform the documents according to the FeatureFactory
$docs = $this->getDocumentArray($documents,$ff);
// choose N centroids at random
$centroids = array();
foreach (array_rand($docs,$this->n) as $key) {
$centroids[] = $docs[$key];
}
// cache the distance and centroid factory functions for use
// with closures
$dist = array($this->dist,'dist');
$cf = array($this->centroidF,'getCentroid');
// looooooooop
while (true) {
// compute the distance each document has from our centroids
// the array is MxN where M = count($docs) and N = count($centroids)
$distances = array_map(
function ($doc) use (&$centroids,$dist) {
return array_map(
function ($c) use ($dist,$doc) {
// it is passed with an array because dist expects references
// and it failed when run with phpunit.
// see http://php.net/manual/en/function.call-user-func.php
// for the solution used below
return call_user_func_array(
$dist,
array(
&$c,
&$doc
)
);
},
$centroids
);
},
$docs
);
// initialize the empty clusters
$clusters = array_fill_keys(
array_keys($centroids),
array()
);
foreach ($distances as $idx=>$d) {
// assign document idx to the closest centroid
$clusters[array_search(min($d),$d)][] = $idx;
}
// compute the new centroids from the assigned documents
// using the centroid factory function
$new_centroids = array_map(
function ($cluster) use (&$docs,$cf) {
return call_user_func_array(
$cf,
array(
&$docs,
$cluster
)
);
},
$clusters
);
// compute the change each centroid had from the previous one
$changes = array_map(
$dist,
$new_centroids,
$centroids
);
// if the largest change is small enough we are done
if (max($changes)<$this->cutoff) {
// return the clusters, the centroids and the distances
return array($clusters,$centroids,$distances);
}
// update the centroids and loooooop again
$centroids = $new_centroids;
}
} | [
"public",
"function",
"cluster",
"(",
"TrainingSet",
"$",
"documents",
",",
"FeatureFactoryInterface",
"$",
"ff",
")",
"{",
"// transform the documents according to the FeatureFactory",
"$",
"docs",
"=",
"$",
"this",
"->",
"getDocumentArray",
"(",
"$",
"documents",
",... | Apply the feature factory to the documents and then cluster the resulting array
using the provided distance metric and centroid factory. | [
"Apply",
"the",
"feature",
"factory",
"to",
"the",
"documents",
"and",
"then",
"cluster",
"the",
"resulting",
"array",
"using",
"the",
"provided",
"distance",
"metric",
"and",
"centroid",
"factory",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Clustering/KMeans.php#L46-L129 |
angeloskath/php-nlp-tools | src/NlpTools/Classifiers/MultinomialNBClassifier.php | MultinomialNBClassifier.classify | public function classify(array $classes, DocumentInterface $d)
{
$maxclass = current($classes);
$maxscore = $this->getScore($maxclass,$d);
while ($class=next($classes)) {
$score = $this->getScore($class,$d);
if ($score>$maxscore) {
$maxclass = $class;
$maxscore = $score;
}
}
return $maxclass;
} | php | public function classify(array $classes, DocumentInterface $d)
{
$maxclass = current($classes);
$maxscore = $this->getScore($maxclass,$d);
while ($class=next($classes)) {
$score = $this->getScore($class,$d);
if ($score>$maxscore) {
$maxclass = $class;
$maxscore = $score;
}
}
return $maxclass;
} | [
"public",
"function",
"classify",
"(",
"array",
"$",
"classes",
",",
"DocumentInterface",
"$",
"d",
")",
"{",
"$",
"maxclass",
"=",
"current",
"(",
"$",
"classes",
")",
";",
"$",
"maxscore",
"=",
"$",
"this",
"->",
"getScore",
"(",
"$",
"maxclass",
","... | Compute the probability of $d belonging to each class
successively and return that class that has the maximum
probability.
@param array $classes The classes from which to choose
@param DocumentInterface $d The document to classify
@return string $class The class that has the maximum probability | [
"Compute",
"the",
"probability",
"of",
"$d",
"belonging",
"to",
"each",
"class",
"successively",
"and",
"return",
"that",
"class",
"that",
"has",
"the",
"maximum",
"probability",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Classifiers/MultinomialNBClassifier.php#L34-L47 |
angeloskath/php-nlp-tools | src/NlpTools/Classifiers/MultinomialNBClassifier.php | MultinomialNBClassifier.getScore | public function getScore($class, DocumentInterface $d)
{
$score = log($this->model->getPrior($class));
$features = $this->feature_factory->getFeatureArray($class,$d);
if (is_int(key($features)))
$features = array_count_values($features);
foreach ($features as $f=>$fcnt) {
$score += $fcnt*log($this->model->getCondProb($f,$class));
}
return $score;
} | php | public function getScore($class, DocumentInterface $d)
{
$score = log($this->model->getPrior($class));
$features = $this->feature_factory->getFeatureArray($class,$d);
if (is_int(key($features)))
$features = array_count_values($features);
foreach ($features as $f=>$fcnt) {
$score += $fcnt*log($this->model->getCondProb($f,$class));
}
return $score;
} | [
"public",
"function",
"getScore",
"(",
"$",
"class",
",",
"DocumentInterface",
"$",
"d",
")",
"{",
"$",
"score",
"=",
"log",
"(",
"$",
"this",
"->",
"model",
"->",
"getPrior",
"(",
"$",
"class",
")",
")",
";",
"$",
"features",
"=",
"$",
"this",
"->... | Compute the log of the probability of the Document $d belonging
to class $class. We compute the log so that we can sum over the
logarithms instead of multiplying each probability.
@todo perhaps MultinomialNBModel should have precomputed the logs
ex.: getLogPrior() and getLogCondProb()
@param string $class The class for which we are getting a score
@param DocumentInterface The document whose score we are getting
@return float The log of the probability of $d belonging to $class | [
"Compute",
"the",
"log",
"of",
"the",
"probability",
"of",
"the",
"Document",
"$d",
"belonging",
"to",
"class",
"$class",
".",
"We",
"compute",
"the",
"log",
"so",
"that",
"we",
"can",
"sum",
"over",
"the",
"logarithms",
"instead",
"of",
"multiplying",
"ea... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Classifiers/MultinomialNBClassifier.php#L61-L72 |
angeloskath/php-nlp-tools | src/NlpTools/Clustering/CentroidFactories/Euclidean.php | Euclidean.getCentroid | public function getCentroid(array &$docs, array $choose=array())
{
$v = array();
if (empty($choose))
$choose = range(0,count($docs)-1);
$cnt = count($choose);
foreach ($choose as $idx) {
$doc = $this->getVector($docs[$idx]);
foreach ($doc as $k=>$w) {
if (!isset($v[$k]))
$v[$k] = $w;
else
$v[$k] += $w;
}
}
foreach ($v as &$w) {
$w /= $cnt;
}
return $v;
} | php | public function getCentroid(array &$docs, array $choose=array())
{
$v = array();
if (empty($choose))
$choose = range(0,count($docs)-1);
$cnt = count($choose);
foreach ($choose as $idx) {
$doc = $this->getVector($docs[$idx]);
foreach ($doc as $k=>$w) {
if (!isset($v[$k]))
$v[$k] = $w;
else
$v[$k] += $w;
}
}
foreach ($v as &$w) {
$w /= $cnt;
}
return $v;
} | [
"public",
"function",
"getCentroid",
"(",
"array",
"&",
"$",
"docs",
",",
"array",
"$",
"choose",
"=",
"array",
"(",
")",
")",
"{",
"$",
"v",
"=",
"array",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"choose",
")",
")",
"$",
"choose",
"=",
"ra... | Compute the mean value for each dimension.
@param array $docs The docs from which the centroid will be computed
@param array $choose The indexes from which the centroid will be computed (if empty all the docs will be used)
@return mixed The centroid. It could be any form of data a number, a vector (it will be the same as the data provided in docs) | [
"Compute",
"the",
"mean",
"value",
"for",
"each",
"dimension",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Clustering/CentroidFactories/Euclidean.php#L35-L55 |
angeloskath/php-nlp-tools | src/NlpTools/Optimizers/ExternalMaxentOptimizer.php | ExternalMaxentOptimizer.optimize | public function optimize(array &$feature_array)
{
// whete we will read from where we will write to
$desrciptorspec = array(
0=>array('pipe','r'),
1=>array('pipe','w'),
2=>STDERR // Should that be redirected to /dev/null or like?
);
// Run the optimizer
$process = proc_open($this->optimizer,$desrciptorspec,$pipes);
if (!is_resource($process)) {
return array();
}
// send the data
fwrite($pipes[0],json_encode($feature_array));
fclose($pipes[0]);
// get the weights
$json = stream_get_contents($pipes[1]);
// decode as an associative array
$l = json_decode( $json , true );
// close up the optimizer
fclose($pipes[1]);
proc_close($process);
return $l;
} | php | public function optimize(array &$feature_array)
{
// whete we will read from where we will write to
$desrciptorspec = array(
0=>array('pipe','r'),
1=>array('pipe','w'),
2=>STDERR // Should that be redirected to /dev/null or like?
);
// Run the optimizer
$process = proc_open($this->optimizer,$desrciptorspec,$pipes);
if (!is_resource($process)) {
return array();
}
// send the data
fwrite($pipes[0],json_encode($feature_array));
fclose($pipes[0]);
// get the weights
$json = stream_get_contents($pipes[1]);
// decode as an associative array
$l = json_decode( $json , true );
// close up the optimizer
fclose($pipes[1]);
proc_close($process);
return $l;
} | [
"public",
"function",
"optimize",
"(",
"array",
"&",
"$",
"feature_array",
")",
"{",
"// whete we will read from where we will write to",
"$",
"desrciptorspec",
"=",
"array",
"(",
"0",
"=>",
"array",
"(",
"'pipe'",
",",
"'r'",
")",
",",
"1",
"=>",
"array",
"("... | Open a pipe to the optimizer, send him the data encoded in json
and then read the stdout to get the results encoded in json
@param array $feature_array The features that fired for any document for any class @see NlpTools\Models\Maxent
@return array The optimized weights | [
"Open",
"a",
"pipe",
"to",
"the",
"optimizer",
"send",
"him",
"the",
"data",
"encoded",
"in",
"json",
"and",
"then",
"read",
"the",
"stdout",
"to",
"get",
"the",
"results",
"encoded",
"in",
"json"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Optimizers/ExternalMaxentOptimizer.php#L63-L93 |
angeloskath/php-nlp-tools | src/NlpTools/Clustering/MergeStrategies/HeapLinkage.php | HeapLinkage.initializeStrategy | public function initializeStrategy(DistanceInterface $d, array &$docs)
{
// the number of documents and the dimensions of the matrix
$this->L = count($docs);
// just to hold which document has been removed
$this->removed = array_fill_keys(range(0, $this->L-1), false);
// how many distances we must compute
$elements = (int) ($this->L*($this->L-1))/2;
// the containers that will hold the distances
$this->dm = new \SplFixedArray($elements);
$this->queue = new \SplPriorityQueue();
$this->queue->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
// for each unique pair of documents calculate the distance and
// save it in the heap and distance matrix
for ($x=0;$x<$this->L;$x++) {
for ($y=$x+1;$y<$this->L;$y++) {
$index = $this->packIndex($y,$x);
$tmp_d = $d->dist($docs[$x],$docs[$y]);
$this->dm[$index] = $tmp_d;
$this->queue->insert($index, -$tmp_d);
}
}
} | php | public function initializeStrategy(DistanceInterface $d, array &$docs)
{
// the number of documents and the dimensions of the matrix
$this->L = count($docs);
// just to hold which document has been removed
$this->removed = array_fill_keys(range(0, $this->L-1), false);
// how many distances we must compute
$elements = (int) ($this->L*($this->L-1))/2;
// the containers that will hold the distances
$this->dm = new \SplFixedArray($elements);
$this->queue = new \SplPriorityQueue();
$this->queue->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
// for each unique pair of documents calculate the distance and
// save it in the heap and distance matrix
for ($x=0;$x<$this->L;$x++) {
for ($y=$x+1;$y<$this->L;$y++) {
$index = $this->packIndex($y,$x);
$tmp_d = $d->dist($docs[$x],$docs[$y]);
$this->dm[$index] = $tmp_d;
$this->queue->insert($index, -$tmp_d);
}
}
} | [
"public",
"function",
"initializeStrategy",
"(",
"DistanceInterface",
"$",
"d",
",",
"array",
"&",
"$",
"docs",
")",
"{",
"// the number of documents and the dimensions of the matrix",
"$",
"this",
"->",
"L",
"=",
"count",
"(",
"$",
"docs",
")",
";",
"// just to h... | Initialize the distance matrix and any other data structure needed
to calculate the merges later.
@param DistanceInterface $d The distance metric used to calculate the distance matrix
@param array $docs The docs to be clustered | [
"Initialize",
"the",
"distance",
"matrix",
"and",
"any",
"other",
"data",
"structure",
"needed",
"to",
"calculate",
"the",
"merges",
"later",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Clustering/MergeStrategies/HeapLinkage.php#L44-L67 |
angeloskath/php-nlp-tools | src/NlpTools/Clustering/MergeStrategies/HeapLinkage.php | HeapLinkage.getNextMerge | public function getNextMerge()
{
// extract the pair with the smallest distance
$tmp = $this->queue->extract();
$index = $tmp["data"];
$d = -$tmp["priority"];
list($y,$x) = $this->unravelIndex($index);
// check if it is invalid
while ($this->removed[$y] || $this->removed[$x] || $this->dm[$index]!=$d) {
$tmp = $this->queue->extract();
$index = $tmp["data"];
$d = -$tmp["priority"];
list($y,$x) = $this->unravelIndex($index);
}
// Now that we have a valid pair to be merged
// calculate the distances of the merged cluster with any
// other cluster
$yi = $this->packIndex($y,0);
$xi = $this->packIndex($x,0);
// for every cluster with index i<x<y
for ($i=0;$i<$x;$i++,$yi++,$xi++) {
$d = $this->newDistance($xi,$yi,$x,$y);
if ($d!=$this->dm[$xi]) {
$this->dm[$xi] = $d;
$this->queue->insert($xi, -$d);
}
}
// for every cluster with index x<i<y
for ($i=$x+1;$i<$y;$i++,$yi++) {
$xi = $this->packIndex($i,$x);
$d = $this->newDistance($xi,$yi,$x,$y);
if ($d!=$this->dm[$xi]) {
$this->dm[$xi] = $d;
$this->queue->insert($xi, -$d);
}
}
// for every cluster x<y<i
for ($i=$y+1;$i<$this->L;$i++) {
$xi = $this->packIndex($i,$x);
$yi = $this->packIndex($i,$y);
$d = $this->newDistance($xi,$yi,$x,$y);
if ($d!=$this->dm[$xi]) {
$this->dm[$xi] = $d;
$this->queue->insert($xi, -$d);
}
}
// mark y as removed
$this->removed[$y] = true;
return array($x,$y);
} | php | public function getNextMerge()
{
// extract the pair with the smallest distance
$tmp = $this->queue->extract();
$index = $tmp["data"];
$d = -$tmp["priority"];
list($y,$x) = $this->unravelIndex($index);
// check if it is invalid
while ($this->removed[$y] || $this->removed[$x] || $this->dm[$index]!=$d) {
$tmp = $this->queue->extract();
$index = $tmp["data"];
$d = -$tmp["priority"];
list($y,$x) = $this->unravelIndex($index);
}
// Now that we have a valid pair to be merged
// calculate the distances of the merged cluster with any
// other cluster
$yi = $this->packIndex($y,0);
$xi = $this->packIndex($x,0);
// for every cluster with index i<x<y
for ($i=0;$i<$x;$i++,$yi++,$xi++) {
$d = $this->newDistance($xi,$yi,$x,$y);
if ($d!=$this->dm[$xi]) {
$this->dm[$xi] = $d;
$this->queue->insert($xi, -$d);
}
}
// for every cluster with index x<i<y
for ($i=$x+1;$i<$y;$i++,$yi++) {
$xi = $this->packIndex($i,$x);
$d = $this->newDistance($xi,$yi,$x,$y);
if ($d!=$this->dm[$xi]) {
$this->dm[$xi] = $d;
$this->queue->insert($xi, -$d);
}
}
// for every cluster x<y<i
for ($i=$y+1;$i<$this->L;$i++) {
$xi = $this->packIndex($i,$x);
$yi = $this->packIndex($i,$y);
$d = $this->newDistance($xi,$yi,$x,$y);
if ($d!=$this->dm[$xi]) {
$this->dm[$xi] = $d;
$this->queue->insert($xi, -$d);
}
}
// mark y as removed
$this->removed[$y] = true;
return array($x,$y);
} | [
"public",
"function",
"getNextMerge",
"(",
")",
"{",
"// extract the pair with the smallest distance",
"$",
"tmp",
"=",
"$",
"this",
"->",
"queue",
"->",
"extract",
"(",
")",
";",
"$",
"index",
"=",
"$",
"tmp",
"[",
"\"data\"",
"]",
";",
"$",
"d",
"=",
"... | Return the pair of clusters x,y to be merged.
1. Extract the pair with the smallest distance
2. Recalculate the distance of the merged cluster with every other cluster
3. Merge the clusters (by labeling one as removed)
4. Reheap
@return array The pair (x,y) to be merged | [
"Return",
"the",
"pair",
"of",
"clusters",
"x",
"y",
"to",
"be",
"merged",
".",
"1",
".",
"Extract",
"the",
"pair",
"with",
"the",
"smallest",
"distance",
"2",
".",
"Recalculate",
"the",
"distance",
"of",
"the",
"merged",
"cluster",
"with",
"every",
"oth... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Clustering/MergeStrategies/HeapLinkage.php#L78-L131 |
angeloskath/php-nlp-tools | src/NlpTools/Clustering/MergeStrategies/HeapLinkage.php | HeapLinkage.unravelIndex | protected function unravelIndex($index)
{
$a = 0;
$b = $this->L-1;
$y = 0;
while ($b-$a > 1) {
// the middle row in the interval [a,b]
$y = (int) (($a+$b)/2);
// the candidate index aka how many points until this row
$i = $y*($y-1)/2;
// if we need an offset les then the wanted y will be in the offset [a,y]
if ($i > $index) {
$b = $y;
} else {
// else it will be in the offset [y,b]
$a = $y;
}
}
// we have finished searching it is either a or b
$x = $index - $i;
// this means that it is b and we have a
if ($y <= $x) {
$y++;
$x = $index - $y*($y-1)/2;
} elseif ($x < 0) {
// this means that it is a and we have b
$y--;
$x = $index - $y*($y-1)/2;
}
return array(
(int) $y,
(int) $x
);
} | php | protected function unravelIndex($index)
{
$a = 0;
$b = $this->L-1;
$y = 0;
while ($b-$a > 1) {
// the middle row in the interval [a,b]
$y = (int) (($a+$b)/2);
// the candidate index aka how many points until this row
$i = $y*($y-1)/2;
// if we need an offset les then the wanted y will be in the offset [a,y]
if ($i > $index) {
$b = $y;
} else {
// else it will be in the offset [y,b]
$a = $y;
}
}
// we have finished searching it is either a or b
$x = $index - $i;
// this means that it is b and we have a
if ($y <= $x) {
$y++;
$x = $index - $y*($y-1)/2;
} elseif ($x < 0) {
// this means that it is a and we have b
$y--;
$x = $index - $y*($y-1)/2;
}
return array(
(int) $y,
(int) $x
);
} | [
"protected",
"function",
"unravelIndex",
"(",
"$",
"index",
")",
"{",
"$",
"a",
"=",
"0",
";",
"$",
"b",
"=",
"$",
"this",
"->",
"L",
"-",
"1",
";",
"$",
"y",
"=",
"0",
";",
"while",
"(",
"$",
"b",
"-",
"$",
"a",
">",
"1",
")",
"{",
"// t... | Use binary search to unravel the index to its coordinates x,y
return them in the order y,x . This operation is to be done only
once per merge so it doesn't add much overhead.
Note: y will always be larger than x
@param integer $index The index to be unraveled
@return array An array containing (y,x) | [
"Use",
"binary",
"search",
"to",
"unravel",
"the",
"index",
"to",
"its",
"coordinates",
"x",
"y",
"return",
"them",
"in",
"the",
"order",
"y",
"x",
".",
"This",
"operation",
"is",
"to",
"be",
"done",
"only",
"once",
"per",
"merge",
"so",
"it",
"doesn",... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Clustering/MergeStrategies/HeapLinkage.php#L143-L179 |
angeloskath/php-nlp-tools | src/NlpTools/FeatureFactories/FunctionFeatures.php | FunctionFeatures.getFeatureArray | public function getFeatureArray($class, DocumentInterface $d)
{
$features = array_filter(
array_map( function ($feature) use ($class,$d) {
return call_user_func($feature, $class, $d);
},
$this->functions
));
$set = array();
foreach ($features as $f) {
if (is_array($f)) {
foreach ($f as $ff) {
if (!isset($set[$ff]))
$set[$ff] = 0;
$set[$ff]++;
}
} else {
if (!isset($set[$f]))
$set[$f] = 0;
$set[$f]++;
}
}
if ($this->frequency)
return $set;
else
return array_keys($set);
} | php | public function getFeatureArray($class, DocumentInterface $d)
{
$features = array_filter(
array_map( function ($feature) use ($class,$d) {
return call_user_func($feature, $class, $d);
},
$this->functions
));
$set = array();
foreach ($features as $f) {
if (is_array($f)) {
foreach ($f as $ff) {
if (!isset($set[$ff]))
$set[$ff] = 0;
$set[$ff]++;
}
} else {
if (!isset($set[$f]))
$set[$f] = 0;
$set[$f]++;
}
}
if ($this->frequency)
return $set;
else
return array_keys($set);
} | [
"public",
"function",
"getFeatureArray",
"(",
"$",
"class",
",",
"DocumentInterface",
"$",
"d",
")",
"{",
"$",
"features",
"=",
"array_filter",
"(",
"array_map",
"(",
"function",
"(",
"$",
"feature",
")",
"use",
"(",
"$",
"class",
",",
"$",
"d",
")",
"... | Compute the features that "fire" for a given class,document pair.
Call each function one by one. Eliminate each return value that
evaluates to false. If the return value is a string add it to
the feature set. If the return value is an array iterate over it
and add each value to the feature set.
@param string $class The class for which we are calculating features
@param DocumentInterface $d The document for which we are calculating features
@return array | [
"Compute",
"the",
"features",
"that",
"fire",
"for",
"a",
"given",
"class",
"document",
"pair",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/FeatureFactories/FunctionFeatures.php#L65-L91 |
angeloskath/php-nlp-tools | src/NlpTools/Documents/TrainingSet.php | TrainingSet.setAsKey | public function setAsKey($what)
{
switch ($what) {
case self::CLASS_AS_KEY:
case self::OFFSET_AS_KEY:
$this->keytype = $what;
break;
default:
$this->keytype = self::CLASS_AS_KEY;
break;
}
} | php | public function setAsKey($what)
{
switch ($what) {
case self::CLASS_AS_KEY:
case self::OFFSET_AS_KEY:
$this->keytype = $what;
break;
default:
$this->keytype = self::CLASS_AS_KEY;
break;
}
} | [
"public",
"function",
"setAsKey",
"(",
"$",
"what",
")",
"{",
"switch",
"(",
"$",
"what",
")",
"{",
"case",
"self",
"::",
"CLASS_AS_KEY",
":",
"case",
"self",
"::",
"OFFSET_AS_KEY",
":",
"$",
"this",
"->",
"keytype",
"=",
"$",
"what",
";",
"break",
"... | Decide what should be returned as key when iterated upon | [
"Decide",
"what",
"should",
"be",
"returned",
"as",
"key",
"when",
"iterated",
"upon"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Documents/TrainingSet.php#L51-L62 |
angeloskath/php-nlp-tools | src/NlpTools/Documents/TrainingSet.php | TrainingSet.applyTransformations | public function applyTransformations(array $transforms)
{
foreach ($this->documents as $doc) {
foreach ($transforms as $transform) {
$doc->applyTransformation($transform);
}
}
} | php | public function applyTransformations(array $transforms)
{
foreach ($this->documents as $doc) {
foreach ($transforms as $transform) {
$doc->applyTransformation($transform);
}
}
} | [
"public",
"function",
"applyTransformations",
"(",
"array",
"$",
"transforms",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"documents",
"as",
"$",
"doc",
")",
"{",
"foreach",
"(",
"$",
"transforms",
"as",
"$",
"transform",
")",
"{",
"$",
"doc",
"->",
... | Apply an array of transformations to all documents in this container.
@param array An array of TransformationInterface instances | [
"Apply",
"an",
"array",
"of",
"transformations",
"to",
"all",
"documents",
"in",
"this",
"container",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Documents/TrainingSet.php#L69-L76 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Maxent.php | Maxent.train | public function train(FeatureFactoryInterface $ff, TrainingSet $tset, MaxentOptimizerInterface $opt)
{
$classSet = $tset->getClassSet();
$features = $this->calculateFeatureArray($classSet,$tset,$ff);
$this->l = $opt->optimize($features);
} | php | public function train(FeatureFactoryInterface $ff, TrainingSet $tset, MaxentOptimizerInterface $opt)
{
$classSet = $tset->getClassSet();
$features = $this->calculateFeatureArray($classSet,$tset,$ff);
$this->l = $opt->optimize($features);
} | [
"public",
"function",
"train",
"(",
"FeatureFactoryInterface",
"$",
"ff",
",",
"TrainingSet",
"$",
"tset",
",",
"MaxentOptimizerInterface",
"$",
"opt",
")",
"{",
"$",
"classSet",
"=",
"$",
"tset",
"->",
"getClassSet",
"(",
")",
";",
"$",
"features",
"=",
"... | Calculate all the features for every possible class. Pass the
information to the optimizer to find the weights that satisfy the
constraints and maximize the entropy
@param $ff The feature factory
@param $tset A collection of training documents
@param $opt An optimizer, we need a maxent optimizer
@return void | [
"Calculate",
"all",
"the",
"features",
"for",
"every",
"possible",
"class",
".",
"Pass",
"the",
"information",
"to",
"the",
"optimizer",
"to",
"find",
"the",
"weights",
"that",
"satisfy",
"the",
"constraints",
"and",
"maximize",
"the",
"entropy"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Maxent.php#L29-L35 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Maxent.php | Maxent.calculateFeatureArray | protected function calculateFeatureArray(array $classes, TrainingSet $tset, FeatureFactoryInterface $ff)
{
$features = array();
$tset->setAsKey(TrainingSet::OFFSET_AS_KEY);
foreach ($tset as $offset=>$doc) {
$features[$offset] = array();
foreach ($classes as $class) {
$features[$offset][$class] = $ff->getFeatureArray($class,$doc);
}
$features[$offset]['__label__'] = $doc->getClass();
}
return $features;
} | php | protected function calculateFeatureArray(array $classes, TrainingSet $tset, FeatureFactoryInterface $ff)
{
$features = array();
$tset->setAsKey(TrainingSet::OFFSET_AS_KEY);
foreach ($tset as $offset=>$doc) {
$features[$offset] = array();
foreach ($classes as $class) {
$features[$offset][$class] = $ff->getFeatureArray($class,$doc);
}
$features[$offset]['__label__'] = $doc->getClass();
}
return $features;
} | [
"protected",
"function",
"calculateFeatureArray",
"(",
"array",
"$",
"classes",
",",
"TrainingSet",
"$",
"tset",
",",
"FeatureFactoryInterface",
"$",
"ff",
")",
"{",
"$",
"features",
"=",
"array",
"(",
")",
";",
"$",
"tset",
"->",
"setAsKey",
"(",
"TrainingS... | Calculate all the features for each possible class of each
document. This is done so that we can optimize without the need
of the FeatureFactory.
We do not want to use the FeatureFactoryInterface both because it would
be slow to calculate the features over and over again, but also
because we want to be able to optimize externally to
gain speed (PHP is slow!).
@param $classes A set of the classes in the training set
@param $tset A collection of training documents
@param $ff The feature factory
@return array An array that contains every feature for every possible class of every document | [
"Calculate",
"all",
"the",
"features",
"for",
"each",
"possible",
"class",
"of",
"each",
"document",
".",
"This",
"is",
"done",
"so",
"that",
"we",
"can",
"optimize",
"without",
"the",
"need",
"of",
"the",
"FeatureFactory",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Maxent.php#L52-L65 |
angeloskath/php-nlp-tools | src/NlpTools/Models/Maxent.php | Maxent.P | public function P(array $classes,FeatureFactoryInterface $ff,DocumentInterface $d,$class)
{
$exps = array();
foreach ($classes as $cl) {
$tmp = 0.0;
foreach ($ff->getFeatureArray($cl,$d) as $i) {
$tmp += $this->l[$i];
}
$exps[$cl] = exp($tmp);
}
return $exps[$class]/array_sum($exps);
} | php | public function P(array $classes,FeatureFactoryInterface $ff,DocumentInterface $d,$class)
{
$exps = array();
foreach ($classes as $cl) {
$tmp = 0.0;
foreach ($ff->getFeatureArray($cl,$d) as $i) {
$tmp += $this->l[$i];
}
$exps[$cl] = exp($tmp);
}
return $exps[$class]/array_sum($exps);
} | [
"public",
"function",
"P",
"(",
"array",
"$",
"classes",
",",
"FeatureFactoryInterface",
"$",
"ff",
",",
"DocumentInterface",
"$",
"d",
",",
"$",
"class",
")",
"{",
"$",
"exps",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"classes",
"as",
"$",
... | Calculate the probability that document $d belongs to the class
$class given a set of possible classes, a feature factory and
the model's weights l[i]
@param $classes The set of possible classes
@param $ff The feature factory
@param $d The document
@param string $class A class for which we calculate the probability
@return float The probability that document $d belongs to class $class | [
"Calculate",
"the",
"probability",
"that",
"document",
"$d",
"belongs",
"to",
"the",
"class",
"$class",
"given",
"a",
"set",
"of",
"possible",
"classes",
"a",
"feature",
"factory",
"and",
"the",
"model",
"s",
"weights",
"l",
"[",
"i",
"]"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/Maxent.php#L78-L90 |
angeloskath/php-nlp-tools | src/NlpTools/Optimizers/MaxentGradientDescent.php | MaxentGradientDescent.initParameters | protected function initParameters(array &$feature_array, array &$l)
{
$this->numerators = array();
$this->fprime_vector = array();
foreach ($feature_array as $doc) {
foreach ($doc as $class=>$features) {
if (!is_array($features)) continue;
foreach ($features as $fi) {
$l[$fi] = 0;
$this->fprime_vector[$fi] = 0;
if (!isset($this->numerators[$fi])) {
$this->numerators[$fi] = 0;
}
}
}
foreach ($doc[$doc['__label__']] as $fi) {
$this->numerators[$fi]++;
}
}
} | php | protected function initParameters(array &$feature_array, array &$l)
{
$this->numerators = array();
$this->fprime_vector = array();
foreach ($feature_array as $doc) {
foreach ($doc as $class=>$features) {
if (!is_array($features)) continue;
foreach ($features as $fi) {
$l[$fi] = 0;
$this->fprime_vector[$fi] = 0;
if (!isset($this->numerators[$fi])) {
$this->numerators[$fi] = 0;
}
}
}
foreach ($doc[$doc['__label__']] as $fi) {
$this->numerators[$fi]++;
}
}
} | [
"protected",
"function",
"initParameters",
"(",
"array",
"&",
"$",
"feature_array",
",",
"array",
"&",
"$",
"l",
")",
"{",
"$",
"this",
"->",
"numerators",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"fprime_vector",
"=",
"array",
"(",
")",
";",
... | We initialize all weight for any feature we find to 0. We also
compute the empirical expectation (the count) for each feature in
the training data (which of course remains constant for a
specific set of data).
@param $feature_array All the data known about the training set
@param $l The current set of weights to be initialized
@return void | [
"We",
"initialize",
"all",
"weight",
"for",
"any",
"feature",
"we",
"find",
"to",
"0",
".",
"We",
"also",
"compute",
"the",
"empirical",
"expectation",
"(",
"the",
"count",
")",
"for",
"each",
"feature",
"in",
"the",
"training",
"data",
"(",
"which",
"of... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Optimizers/MaxentGradientDescent.php#L30-L49 |
angeloskath/php-nlp-tools | src/NlpTools/Optimizers/MaxentGradientDescent.php | MaxentGradientDescent.prepareFprime | protected function prepareFprime(array &$feature_array, array &$l)
{
$this->denominators = array();
foreach ($feature_array as $offset=>$doc) {
$numerator = array_fill_keys(array_keys($doc),0.0);
$denominator = 0.0;
foreach ($doc as $cl=>$f) {
if (!is_array($f)) continue;
$tmp = 0.0;
foreach ($f as $i) {
$tmp += $l[$i];
}
$tmp = exp($tmp);
$numerator[$cl] += $tmp;
$denominator += $tmp;
}
foreach ($doc as $class=>$features) {
if (!is_array($features)) continue;
foreach ($features as $fi) {
if (!isset($this->denominators[$fi])) {
$this->denominators[$fi] = 0;
}
$this->denominators[$fi] += $numerator[$class]/$denominator;
}
}
}
} | php | protected function prepareFprime(array &$feature_array, array &$l)
{
$this->denominators = array();
foreach ($feature_array as $offset=>$doc) {
$numerator = array_fill_keys(array_keys($doc),0.0);
$denominator = 0.0;
foreach ($doc as $cl=>$f) {
if (!is_array($f)) continue;
$tmp = 0.0;
foreach ($f as $i) {
$tmp += $l[$i];
}
$tmp = exp($tmp);
$numerator[$cl] += $tmp;
$denominator += $tmp;
}
foreach ($doc as $class=>$features) {
if (!is_array($features)) continue;
foreach ($features as $fi) {
if (!isset($this->denominators[$fi])) {
$this->denominators[$fi] = 0;
}
$this->denominators[$fi] += $numerator[$class]/$denominator;
}
}
}
} | [
"protected",
"function",
"prepareFprime",
"(",
"array",
"&",
"$",
"feature_array",
",",
"array",
"&",
"$",
"l",
")",
"{",
"$",
"this",
"->",
"denominators",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"feature_array",
"as",
"$",
"offset",
"=>",
"... | Compute the denominators which is the predicted expectation of
each feature given a set of weights L and a set of features for
each document for each class.
@param $feature_array All the data known about the training set
@param $l The current set of weights to be initialized
@return void | [
"Compute",
"the",
"denominators",
"which",
"is",
"the",
"predicted",
"expectation",
"of",
"each",
"feature",
"given",
"a",
"set",
"of",
"weights",
"L",
"and",
"a",
"set",
"of",
"features",
"for",
"each",
"document",
"for",
"each",
"class",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Optimizers/MaxentGradientDescent.php#L60-L86 |
angeloskath/php-nlp-tools | src/NlpTools/Optimizers/MaxentGradientDescent.php | MaxentGradientDescent.Fprime | protected function Fprime(array &$feature_array, array &$l)
{
foreach ($this->fprime_vector as $i=>&$fprime_i_val) {
$fprime_i_val = $this->denominators[$i] - $this->numerators[$i];
}
} | php | protected function Fprime(array &$feature_array, array &$l)
{
foreach ($this->fprime_vector as $i=>&$fprime_i_val) {
$fprime_i_val = $this->denominators[$i] - $this->numerators[$i];
}
} | [
"protected",
"function",
"Fprime",
"(",
"array",
"&",
"$",
"feature_array",
",",
"array",
"&",
"$",
"l",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"fprime_vector",
"as",
"$",
"i",
"=>",
"&",
"$",
"fprime_i_val",
")",
"{",
"$",
"fprime_i_val",
"=",
... | The partial Fprime for each i is
empirical expectation - predicted expectation . We need to
maximize the CLogLik (CLogLik is the f whose Fprime we calculate)
so we instead minimize the -CLogLik.
See page 28 of http://nlp.stanford.edu/pubs/maxent-tutorial-slides.pdf
@param $feature_array All the data known about the training set
@param $l The current set of weights to be initialized
@return void | [
"The",
"partial",
"Fprime",
"for",
"each",
"i",
"is",
"empirical",
"expectation",
"-",
"predicted",
"expectation",
".",
"We",
"need",
"to",
"maximize",
"the",
"CLogLik",
"(",
"CLogLik",
"is",
"the",
"f",
"whose",
"Fprime",
"we",
"calculate",
")",
"so",
"we... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Optimizers/MaxentGradientDescent.php#L100-L105 |
angeloskath/php-nlp-tools | src/NlpTools/Similarity/Euclidean.php | Euclidean.dist | public function dist(&$A, &$B)
{
if (is_int(key($A)))
$v1 = array_count_values($A);
else
$v1 = &$A;
if (is_int(key($B)))
$v2 = array_count_values($B);
else
$v2 = &$B;
$r = array();
foreach ($v1 as $k=>$v) {
$r[$k] = $v;
}
foreach ($v2 as $k=>$v) {
if (isset($r[$k]))
$r[$k] -= $v;
else
$r[$k] = $v;
}
return sqrt(
array_sum(
array_map(
function ($x) {
return $x*$x;
},
$r
)
)
);
} | php | public function dist(&$A, &$B)
{
if (is_int(key($A)))
$v1 = array_count_values($A);
else
$v1 = &$A;
if (is_int(key($B)))
$v2 = array_count_values($B);
else
$v2 = &$B;
$r = array();
foreach ($v1 as $k=>$v) {
$r[$k] = $v;
}
foreach ($v2 as $k=>$v) {
if (isset($r[$k]))
$r[$k] -= $v;
else
$r[$k] = $v;
}
return sqrt(
array_sum(
array_map(
function ($x) {
return $x*$x;
},
$r
)
)
);
} | [
"public",
"function",
"dist",
"(",
"&",
"$",
"A",
",",
"&",
"$",
"B",
")",
"{",
"if",
"(",
"is_int",
"(",
"key",
"(",
"$",
"A",
")",
")",
")",
"$",
"v1",
"=",
"array_count_values",
"(",
"$",
"A",
")",
";",
"else",
"$",
"v1",
"=",
"&",
"$",
... | see class description
@param array $A Either a vector or a collection of tokens to be transformed to a vector
@param array $B Either a vector or a collection of tokens to be transformed to a vector
@return float The euclidean distance between $A and $B | [
"see",
"class",
"description"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Similarity/Euclidean.php#L17-L49 |
angeloskath/php-nlp-tools | src/NlpTools/Models/FeatureBasedNB.php | FeatureBasedNB.getCondProb | public function getCondProb($term,$class)
{
if (!isset($this->condprob[$term][$class])) {
return isset($this->unknown[$class])
? $this->unknown[$class]
: 0;
} else {
return $this->condprob[$term][$class];
}
} | php | public function getCondProb($term,$class)
{
if (!isset($this->condprob[$term][$class])) {
return isset($this->unknown[$class])
? $this->unknown[$class]
: 0;
} else {
return $this->condprob[$term][$class];
}
} | [
"public",
"function",
"getCondProb",
"(",
"$",
"term",
",",
"$",
"class",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"condprob",
"[",
"$",
"term",
"]",
"[",
"$",
"class",
"]",
")",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
... | Return the conditional probability of a term for a given class.
@param string $term The term (word, feature id, ...)
@param string $class The class
@return float | [
"Return",
"the",
"conditional",
"probability",
"of",
"a",
"term",
"for",
"a",
"given",
"class",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/FeatureBasedNB.php#L49-L60 |
angeloskath/php-nlp-tools | src/NlpTools/Models/FeatureBasedNB.php | FeatureBasedNB.train_with_context | public function train_with_context(array &$train_ctx, FeatureFactoryInterface $ff, TrainingSet $tset, $a_smoothing=1)
{
$this->countTrainingSet(
$ff,
$tset,
$train_ctx['termcount_per_class'],
$train_ctx['termcount'],
$train_ctx['ndocs_per_class'],
$train_ctx['voc'],
$train_ctx['ndocs']
);
$voccount = count($train_ctx['voc']);
$this->computeProbabilitiesFromCounts(
$tset->getClassSet(),
$train_ctx['termcount_per_class'],
$train_ctx['termcount'],
$train_ctx['ndocs_per_class'],
$train_ctx['ndocs'],
$voccount,
$a_smoothing
);
return $train_ctx;
} | php | public function train_with_context(array &$train_ctx, FeatureFactoryInterface $ff, TrainingSet $tset, $a_smoothing=1)
{
$this->countTrainingSet(
$ff,
$tset,
$train_ctx['termcount_per_class'],
$train_ctx['termcount'],
$train_ctx['ndocs_per_class'],
$train_ctx['voc'],
$train_ctx['ndocs']
);
$voccount = count($train_ctx['voc']);
$this->computeProbabilitiesFromCounts(
$tset->getClassSet(),
$train_ctx['termcount_per_class'],
$train_ctx['termcount'],
$train_ctx['ndocs_per_class'],
$train_ctx['ndocs'],
$voccount,
$a_smoothing
);
return $train_ctx;
} | [
"public",
"function",
"train_with_context",
"(",
"array",
"&",
"$",
"train_ctx",
",",
"FeatureFactoryInterface",
"$",
"ff",
",",
"TrainingSet",
"$",
"tset",
",",
"$",
"a_smoothing",
"=",
"1",
")",
"{",
"$",
"this",
"->",
"countTrainingSet",
"(",
"$",
"ff",
... | Train on the given set and fill the model's variables. Use the
training context provided to update the counts as if the training
set was appended to the previous one that provided the context.
It can be used for incremental training. It is not meant to be used
with the same training set twice.
@param array $train_ctx The previous training context
@param FeatureFactoryInterface $ff A feature factory to compute features from a training document
@param TrainingSet The training set
@param integer $a_smoothing The parameter for additive smoothing. Defaults to add-one smoothing.
@return array Return a training context to be used for further incremental training,
although this is not necessary since the changes also happen in place | [
"Train",
"on",
"the",
"given",
"set",
"and",
"fill",
"the",
"model",
"s",
"variables",
".",
"Use",
"the",
"training",
"context",
"provided",
"to",
"update",
"the",
"counts",
"as",
"if",
"the",
"training",
"set",
"was",
"appended",
"to",
"the",
"previous",
... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/FeatureBasedNB.php#L77-L102 |
angeloskath/php-nlp-tools | src/NlpTools/Models/FeatureBasedNB.php | FeatureBasedNB.train | public function train(FeatureFactoryInterface $ff, TrainingSet $tset, $a_smoothing=1)
{
$class_set = $tset->getClassSet();
$ctx = array(
'termcount_per_class'=>array_fill_keys($class_set,0),
'termcount'=>array_fill_keys($class_set,array()),
'ndocs_per_class'=>array_fill_keys($class_set,0),
'voc'=>array(),
'ndocs'=>0
);
return $this->train_with_context($ctx,$ff,$tset,$a_smoothing);
} | php | public function train(FeatureFactoryInterface $ff, TrainingSet $tset, $a_smoothing=1)
{
$class_set = $tset->getClassSet();
$ctx = array(
'termcount_per_class'=>array_fill_keys($class_set,0),
'termcount'=>array_fill_keys($class_set,array()),
'ndocs_per_class'=>array_fill_keys($class_set,0),
'voc'=>array(),
'ndocs'=>0
);
return $this->train_with_context($ctx,$ff,$tset,$a_smoothing);
} | [
"public",
"function",
"train",
"(",
"FeatureFactoryInterface",
"$",
"ff",
",",
"TrainingSet",
"$",
"tset",
",",
"$",
"a_smoothing",
"=",
"1",
")",
"{",
"$",
"class_set",
"=",
"$",
"tset",
"->",
"getClassSet",
"(",
")",
";",
"$",
"ctx",
"=",
"array",
"(... | Train on the given set and fill the models variables
priors[c] = NDocs[c]/NDocs
condprob[t][c] = count( t in c) + 1 / sum( count( t' in c ) + 1 , for every t' )
unknown[c] = condbrob['word that doesnt exist in c'][c] ( so that count(t in c)==0 )
More information on the algorithm can be found at
http://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html
@param FeatureFactoryInterface A feature factory to compute features from a training document
@param TrainingSet The training set
@param integer $a_smoothing The parameter for additive smoothing. Defaults to add-one smoothing.
@return array Return a training context to be used for incremental training | [
"Train",
"on",
"the",
"given",
"set",
"and",
"fill",
"the",
"models",
"variables"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/FeatureBasedNB.php#L119-L132 |
angeloskath/php-nlp-tools | src/NlpTools/Models/FeatureBasedNB.php | FeatureBasedNB.countTrainingSet | protected function countTrainingSet(FeatureFactoryInterface $ff, TrainingSet $tset, array &$termcount_per_class, array &$termcount, array &$ndocs_per_class, array &$voc, &$ndocs)
{
foreach ($tset as $tdoc) {
$ndocs++;
$c = $tdoc->getClass();
$ndocs_per_class[$c]++;
$features = $ff->getFeatureArray($c,$tdoc);
if (is_int(key($features)))
$features = array_count_values($features);
foreach ($features as $f=>$fcnt) {
if (!isset($voc[$f]))
$voc[$f] = 0;
$termcount_per_class[$c]+=$fcnt;
if (isset($termcount[$c][$f]))
$termcount[$c][$f]+=$fcnt;
else
$termcount[$c][$f] = $fcnt;
}
}
} | php | protected function countTrainingSet(FeatureFactoryInterface $ff, TrainingSet $tset, array &$termcount_per_class, array &$termcount, array &$ndocs_per_class, array &$voc, &$ndocs)
{
foreach ($tset as $tdoc) {
$ndocs++;
$c = $tdoc->getClass();
$ndocs_per_class[$c]++;
$features = $ff->getFeatureArray($c,$tdoc);
if (is_int(key($features)))
$features = array_count_values($features);
foreach ($features as $f=>$fcnt) {
if (!isset($voc[$f]))
$voc[$f] = 0;
$termcount_per_class[$c]+=$fcnt;
if (isset($termcount[$c][$f]))
$termcount[$c][$f]+=$fcnt;
else
$termcount[$c][$f] = $fcnt;
}
}
} | [
"protected",
"function",
"countTrainingSet",
"(",
"FeatureFactoryInterface",
"$",
"ff",
",",
"TrainingSet",
"$",
"tset",
",",
"array",
"&",
"$",
"termcount_per_class",
",",
"array",
"&",
"$",
"termcount",
",",
"array",
"&",
"$",
"ndocs_per_class",
",",
"array",
... | Count all the features for each document. All parameters are passed
by reference and they are filled in this function. Useful for not
making copies of big arrays.
@param FeatureFactoryInterface $ff A feature factory to create the features for each document in the set
@param TrainingSet $tset The training set (collection of labeled documents)
@param array $termcount_per_class The count of occurences of each feature in each class
@param array $termcount The total count of occurences of each term
@param array $ndocs_per_class The total number of documents per class
@param array $voc A set of the found features
@param integer $ndocs The number of documents
@return void | [
"Count",
"all",
"the",
"features",
"for",
"each",
"document",
".",
"All",
"parameters",
"are",
"passed",
"by",
"reference",
"and",
"they",
"are",
"filled",
"in",
"this",
"function",
".",
"Useful",
"for",
"not",
"making",
"copies",
"of",
"big",
"arrays",
".... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/FeatureBasedNB.php#L148-L168 |
angeloskath/php-nlp-tools | src/NlpTools/Models/FeatureBasedNB.php | FeatureBasedNB.computeProbabilitiesFromCounts | protected function computeProbabilitiesFromCounts(array $class_set, array &$termcount_per_class, array &$termcount, array &$ndocs_per_class, $ndocs, $voccount, $a_smoothing=1)
{
$denom_smoothing = $a_smoothing*$voccount;
foreach ($class_set as $class) {
$this->priors[$class] = $ndocs_per_class[$class] / $ndocs;
foreach ($termcount[$class] as $term=>$count) {
$this->condprob[$term][$class] = ($count + $a_smoothing) / ($termcount_per_class[$class] + $denom_smoothing);
}
}
foreach ($class_set as $class) {
$this->unknown[$class] = $a_smoothing / ($termcount_per_class[$class] + $denom_smoothing);
}
} | php | protected function computeProbabilitiesFromCounts(array $class_set, array &$termcount_per_class, array &$termcount, array &$ndocs_per_class, $ndocs, $voccount, $a_smoothing=1)
{
$denom_smoothing = $a_smoothing*$voccount;
foreach ($class_set as $class) {
$this->priors[$class] = $ndocs_per_class[$class] / $ndocs;
foreach ($termcount[$class] as $term=>$count) {
$this->condprob[$term][$class] = ($count + $a_smoothing) / ($termcount_per_class[$class] + $denom_smoothing);
}
}
foreach ($class_set as $class) {
$this->unknown[$class] = $a_smoothing / ($termcount_per_class[$class] + $denom_smoothing);
}
} | [
"protected",
"function",
"computeProbabilitiesFromCounts",
"(",
"array",
"$",
"class_set",
",",
"array",
"&",
"$",
"termcount_per_class",
",",
"array",
"&",
"$",
"termcount",
",",
"array",
"&",
"$",
"ndocs_per_class",
",",
"$",
"ndocs",
",",
"$",
"voccount",
"... | Compute the probabilities given the counts of the features in the
training set.
@param array $class_set Just the array that contains the classes
@param array $termcount_per_class The count of occurences of each feature in each class
@param array $termcount The total count of occurences of each term
@param array $ndocs_per_class The total number of documents per class
@param integer $ndocs The total number of documents
@param integer $voccount The total number of features found
@return void | [
"Compute",
"the",
"probabilities",
"given",
"the",
"counts",
"of",
"the",
"features",
"in",
"the",
"training",
"set",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Models/FeatureBasedNB.php#L182-L194 |
angeloskath/php-nlp-tools | src/NlpTools/Similarity/Simhash.php | Simhash.simhash | public function simhash(array &$set)
{
$boxes = array_fill(0,$this->length,0);
if (is_int(key($set)))
$dict = array_count_values($set);
else
$dict = &$set;
foreach ($dict as $m=>$w) {
$h = call_user_func($this->h,$m);
for ($bit_idx=0;$bit_idx<$this->length;$bit_idx++) {
$boxes[$bit_idx] += ($h[$bit_idx]=='1') ? $w : -$w;
}
}
$s = '';
foreach ($boxes as $box) {
if ($box>0)
$s .= '1';
else
$s .= '0';
}
return $s;
} | php | public function simhash(array &$set)
{
$boxes = array_fill(0,$this->length,0);
if (is_int(key($set)))
$dict = array_count_values($set);
else
$dict = &$set;
foreach ($dict as $m=>$w) {
$h = call_user_func($this->h,$m);
for ($bit_idx=0;$bit_idx<$this->length;$bit_idx++) {
$boxes[$bit_idx] += ($h[$bit_idx]=='1') ? $w : -$w;
}
}
$s = '';
foreach ($boxes as $box) {
if ($box>0)
$s .= '1';
else
$s .= '0';
}
return $s;
} | [
"public",
"function",
"simhash",
"(",
"array",
"&",
"$",
"set",
")",
"{",
"$",
"boxes",
"=",
"array_fill",
"(",
"0",
",",
"$",
"this",
"->",
"length",
",",
"0",
")",
";",
"if",
"(",
"is_int",
"(",
"key",
"(",
"$",
"set",
")",
")",
")",
"$",
"... | Compute the locality sensitive hash for this set.
Maintain a vector ($boxes) of length $this->length initialized to
0. Each member of the set is hashed to a {$this->length} bit vector.
For each of these bits we either increment or decrement the
corresponding $boxes dimension depending on the bit being either
1 or 0. Finally the signs of each dimension of the boxes vector
is the locality sensitive hash.
We have departed from the original implementation at the
following points:
1. Each feature has a weight of 1, but feature duplication is
allowed.
@param array $set
@return string The bits of the hash as a string | [
"Compute",
"the",
"locality",
"sensitive",
"hash",
"for",
"this",
"set",
".",
"Maintain",
"a",
"vector",
"(",
"$boxes",
")",
"of",
"length",
"$this",
"-",
">",
"length",
"initialized",
"to",
"0",
".",
"Each",
"member",
"of",
"the",
"set",
"is",
"hashed",... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Similarity/Simhash.php#L62-L84 |
angeloskath/php-nlp-tools | src/NlpTools/Similarity/Simhash.php | Simhash.dist | public function dist(&$A, &$B)
{
$h1 = $this->simhash($A);
$h2 = $this->simhash($B);
$d = 0;
for ($i=0;$i<$this->length;$i++) {
if ($h1[$i]!=$h2[$i])
$d++;
}
return $d;
} | php | public function dist(&$A, &$B)
{
$h1 = $this->simhash($A);
$h2 = $this->simhash($B);
$d = 0;
for ($i=0;$i<$this->length;$i++) {
if ($h1[$i]!=$h2[$i])
$d++;
}
return $d;
} | [
"public",
"function",
"dist",
"(",
"&",
"$",
"A",
",",
"&",
"$",
"B",
")",
"{",
"$",
"h1",
"=",
"$",
"this",
"->",
"simhash",
"(",
"$",
"A",
")",
";",
"$",
"h2",
"=",
"$",
"this",
"->",
"simhash",
"(",
"$",
"B",
")",
";",
"$",
"d",
"=",
... | Computes the hamming distance of the simhashes of two sets.
@param array $A
@param array $B
@return int [0,$this->length] | [
"Computes",
"the",
"hamming",
"distance",
"of",
"the",
"simhashes",
"of",
"two",
"sets",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Similarity/Simhash.php#L93-L104 |
angeloskath/php-nlp-tools | src/NlpTools/Similarity/Simhash.php | Simhash.similarity | public function similarity(&$A, &$B)
{
return ($this->length-$this->dist($A,$B))/$this->length;
} | php | public function similarity(&$A, &$B)
{
return ($this->length-$this->dist($A,$B))/$this->length;
} | [
"public",
"function",
"similarity",
"(",
"&",
"$",
"A",
",",
"&",
"$",
"B",
")",
"{",
"return",
"(",
"$",
"this",
"->",
"length",
"-",
"$",
"this",
"->",
"dist",
"(",
"$",
"A",
",",
"$",
"B",
")",
")",
"/",
"$",
"this",
"->",
"length",
";",
... | Computes a similarity measure from two sets. The similarity is
computed as 1 - (sets' distance) / (maximum possible distance).
@param array $A
@param array $B
@return float [0,1] | [
"Computes",
"a",
"similarity",
"measure",
"from",
"two",
"sets",
".",
"The",
"similarity",
"is",
"computed",
"as",
"1",
"-",
"(",
"sets",
"distance",
")",
"/",
"(",
"maximum",
"possible",
"distance",
")",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Similarity/Simhash.php#L114-L117 |
angeloskath/php-nlp-tools | src/NlpTools/Tokenizers/RegexTokenizer.php | RegexTokenizer.tokenize | public function tokenize($str)
{
$str = array($str);
foreach ($this->patterns as $p) {
if (!is_array($p)) $p = array($p);
if (count($p)==1) { // split pattern
$this->split($str, $p[0]);
} elseif (is_int($p[1])) { // match pattern
$this->match($str, $p[0], $p[1]);
} else { // replace pattern
$this->replace($str, $p[0], $p[1]);
}
}
return $str;
} | php | public function tokenize($str)
{
$str = array($str);
foreach ($this->patterns as $p) {
if (!is_array($p)) $p = array($p);
if (count($p)==1) { // split pattern
$this->split($str, $p[0]);
} elseif (is_int($p[1])) { // match pattern
$this->match($str, $p[0], $p[1]);
} else { // replace pattern
$this->replace($str, $p[0], $p[1]);
}
}
return $str;
} | [
"public",
"function",
"tokenize",
"(",
"$",
"str",
")",
"{",
"$",
"str",
"=",
"array",
"(",
"$",
"str",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"patterns",
"as",
"$",
"p",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"p",
")",
")",
"$... | Iteratively run for each pattern. The tokens resulting from one pattern are
fed to the next as strings.
If the pattern is given alone, it is assumed that it is a pattern used
for splitting with preg_split.
If the pattern is given together with an integer then it is assumed to be
a pattern used with preg_match
If a pattern is given with a string it is assumed to be a transformation
pattern used with preg_replace
@param string $str The string to be tokenized
@return array The tokens | [
"Iteratively",
"run",
"for",
"each",
"pattern",
".",
"The",
"tokens",
"resulting",
"from",
"one",
"pattern",
"are",
"fed",
"to",
"the",
"next",
"as",
"strings",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Tokenizers/RegexTokenizer.php#L39-L54 |
angeloskath/php-nlp-tools | src/NlpTools/Tokenizers/RegexTokenizer.php | RegexTokenizer.split | protected function split(array &$str, $pattern)
{
$tokens = array();
foreach ($str as $s) {
$tokens = array_merge(
$tokens,
preg_split($pattern, $s, null, PREG_SPLIT_NO_EMPTY)
);
}
$str = $tokens;
} | php | protected function split(array &$str, $pattern)
{
$tokens = array();
foreach ($str as $s) {
$tokens = array_merge(
$tokens,
preg_split($pattern, $s, null, PREG_SPLIT_NO_EMPTY)
);
}
$str = $tokens;
} | [
"protected",
"function",
"split",
"(",
"array",
"&",
"$",
"str",
",",
"$",
"pattern",
")",
"{",
"$",
"tokens",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"str",
"as",
"$",
"s",
")",
"{",
"$",
"tokens",
"=",
"array_merge",
"(",
"$",
"tokens... | Execute the SPLIT mode
@param array &$str The tokens to be further tokenized | [
"Execute",
"the",
"SPLIT",
"mode"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Tokenizers/RegexTokenizer.php#L61-L72 |
angeloskath/php-nlp-tools | src/NlpTools/Tokenizers/RegexTokenizer.php | RegexTokenizer.match | protected function match(array &$str, $pattern, $keep)
{
$tokens = array();
foreach ($str as $s) {
preg_match_all($pattern, $s, $m);
$tokens = array_merge(
$tokens,
$m[$keep]
);
}
$str = $tokens;
} | php | protected function match(array &$str, $pattern, $keep)
{
$tokens = array();
foreach ($str as $s) {
preg_match_all($pattern, $s, $m);
$tokens = array_merge(
$tokens,
$m[$keep]
);
}
$str = $tokens;
} | [
"protected",
"function",
"match",
"(",
"array",
"&",
"$",
"str",
",",
"$",
"pattern",
",",
"$",
"keep",
")",
"{",
"$",
"tokens",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"str",
"as",
"$",
"s",
")",
"{",
"preg_match_all",
"(",
"$",
"patte... | Execute the KEEP_MATCHES mode
@param array &$str The tokens to be further tokenized | [
"Execute",
"the",
"KEEP_MATCHES",
"mode"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Tokenizers/RegexTokenizer.php#L79-L91 |
angeloskath/php-nlp-tools | src/NlpTools/Tokenizers/RegexTokenizer.php | RegexTokenizer.replace | protected function replace(array &$str, $pattern, $replacement)
{
foreach ($str as &$s) {
$s = preg_replace($pattern, $replacement, $s);
}
} | php | protected function replace(array &$str, $pattern, $replacement)
{
foreach ($str as &$s) {
$s = preg_replace($pattern, $replacement, $s);
}
} | [
"protected",
"function",
"replace",
"(",
"array",
"&",
"$",
"str",
",",
"$",
"pattern",
",",
"$",
"replacement",
")",
"{",
"foreach",
"(",
"$",
"str",
"as",
"&",
"$",
"s",
")",
"{",
"$",
"s",
"=",
"preg_replace",
"(",
"$",
"pattern",
",",
"$",
"r... | Execute the TRANSFORM mode.
@param string $str The string to be tokenized | [
"Execute",
"the",
"TRANSFORM",
"mode",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Tokenizers/RegexTokenizer.php#L98-L103 |
angeloskath/php-nlp-tools | src/NlpTools/Documents/WordDocument.php | WordDocument.applyTransformation | public function applyTransformation(TransformationInterface $transform)
{
$null_filter = function ($token) {
return $token!==null;
};
$this->word = $transform->transform($this->word);
// array_values for re-indexing
$this->before = array_values(
array_filter(
array_map(
array($transform,"transform"),
$this->before
),
$null_filter
)
);
$this->after = array_values(
array_filter(
array_map(
array($transform,"transform"),
$this->after
),
$null_filter
)
);
} | php | public function applyTransformation(TransformationInterface $transform)
{
$null_filter = function ($token) {
return $token!==null;
};
$this->word = $transform->transform($this->word);
// array_values for re-indexing
$this->before = array_values(
array_filter(
array_map(
array($transform,"transform"),
$this->before
),
$null_filter
)
);
$this->after = array_values(
array_filter(
array_map(
array($transform,"transform"),
$this->after
),
$null_filter
)
);
} | [
"public",
"function",
"applyTransformation",
"(",
"TransformationInterface",
"$",
"transform",
")",
"{",
"$",
"null_filter",
"=",
"function",
"(",
"$",
"token",
")",
"{",
"return",
"$",
"token",
"!==",
"null",
";",
"}",
";",
"$",
"this",
"->",
"word",
"=",... | Apply the transformation to the token and the surrounding context.
Filter out the null tokens from the context. If the word is transformed
to null it is for the feature factory to decide what to do.
@param TransformationInterface $transform The transformation to be applied | [
"Apply",
"the",
"transformation",
"to",
"the",
"token",
"and",
"the",
"surrounding",
"context",
".",
"Filter",
"out",
"the",
"null",
"tokens",
"from",
"the",
"context",
".",
"If",
"the",
"word",
"is",
"transformed",
"to",
"null",
"it",
"is",
"for",
"the",
... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Documents/WordDocument.php#L51-L77 |
angeloskath/php-nlp-tools | src/NlpTools/Analysis/FreqDist.php | FreqDist.getTokenWeight | public function getTokenWeight($string)
{
if($this->getTotalByToken($string)){
return $this->getTotalByToken($string)/$this->getTotalTokens();
} else {
return false;
}
} | php | public function getTokenWeight($string)
{
if($this->getTotalByToken($string)){
return $this->getTotalByToken($string)/$this->getTotalTokens();
} else {
return false;
}
} | [
"public",
"function",
"getTokenWeight",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getTotalByToken",
"(",
"$",
"string",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getTotalByToken",
"(",
"$",
"string",
")",
"/",
"$",
"this",
"->",
... | Return a token's weight (for user's own tf-idf/pdf/iduf implem)
@param string $string
@return mixed | [
"Return",
"a",
"token",
"s",
"weight",
"(",
"for",
"user",
"s",
"own",
"tf",
"-",
"idf",
"/",
"pdf",
"/",
"iduf",
"implem",
")"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Analysis/FreqDist.php#L121-L128 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.cons | protected function cons($i)
{
if ($i>$this->k) {
return true;
}
$c = $this->b[$i];
if (isset(self::$vowels[$c])) {
return false;
} elseif ($c==='y') {
return ($i===0) ? true : !$this->cons($i-1);
} else {
return true;
}
} | php | protected function cons($i)
{
if ($i>$this->k) {
return true;
}
$c = $this->b[$i];
if (isset(self::$vowels[$c])) {
return false;
} elseif ($c==='y') {
return ($i===0) ? true : !$this->cons($i-1);
} else {
return true;
}
} | [
"protected",
"function",
"cons",
"(",
"$",
"i",
")",
"{",
"if",
"(",
"$",
"i",
">",
"$",
"this",
"->",
"k",
")",
"{",
"return",
"true",
";",
"}",
"$",
"c",
"=",
"$",
"this",
"->",
"b",
"[",
"$",
"i",
"]",
";",
"if",
"(",
"isset",
"(",
"se... | /* cons(i) is TRUE <=> b[i] is a consonant. | [
"/",
"*",
"cons",
"(",
"i",
")",
"is",
"TRUE",
"<",
"=",
">",
"b",
"[",
"i",
"]",
"is",
"a",
"consonant",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L49-L62 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.m | protected function m()
{
$n = 0;
$i = 0;
while (true) {
if ($i > $this->j)
return $n;
if (! $this->cons($i))
break;
$i++;
}
$i++;
while (true) {
while (true) {
if ($i > $this->j)
return $n;
if ($this->cons($i))
break;
$i++;
}
$i++;
$n++;
while (true) {
if ($i > $this->j)
return $n;
if (! $this->cons($i))
break;
$i++;
}
$i++;
}
} | php | protected function m()
{
$n = 0;
$i = 0;
while (true) {
if ($i > $this->j)
return $n;
if (! $this->cons($i))
break;
$i++;
}
$i++;
while (true) {
while (true) {
if ($i > $this->j)
return $n;
if ($this->cons($i))
break;
$i++;
}
$i++;
$n++;
while (true) {
if ($i > $this->j)
return $n;
if (! $this->cons($i))
break;
$i++;
}
$i++;
}
} | [
"protected",
"function",
"m",
"(",
")",
"{",
"$",
"n",
"=",
"0",
";",
"$",
"i",
"=",
"0",
";",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"$",
"i",
">",
"$",
"this",
"->",
"j",
")",
"return",
"$",
"n",
";",
"if",
"(",
"!",
"$",
"this",
... | /*
m() measures the number of consonant sequences between 0 and j. if c is
a consonant sequence and v a vowel sequence, and <..> indicates arbitrary
presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvcvc<v> gives 3
.... | [
"/",
"*",
"m",
"()",
"measures",
"the",
"number",
"of",
"consonant",
"sequences",
"between",
"0",
"and",
"j",
".",
"if",
"c",
"is",
"a",
"consonant",
"sequence",
"and",
"v",
"a",
"vowel",
"sequence",
"and",
"<",
"..",
">",
"indicates",
"arbitrary",
"pr... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L75-L106 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.vowelinstem | protected function vowelinstem()
{
for ($i = 0; $i <= $this->j; $i++) {
if (! $this->cons($i))
return true;
}
return false;
} | php | protected function vowelinstem()
{
for ($i = 0; $i <= $this->j; $i++) {
if (! $this->cons($i))
return true;
}
return false;
} | [
"protected",
"function",
"vowelinstem",
"(",
")",
"{",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<=",
"$",
"this",
"->",
"j",
";",
"$",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"cons",
"(",
"$",
"i",
")",
")",
"return",... | /* vowelinstem() is TRUE <=> 0,...j contains a vowel | [
"/",
"*",
"vowelinstem",
"()",
"is",
"TRUE",
"<",
"=",
">",
"0",
"...",
"j",
"contains",
"a",
"vowel"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L109-L117 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.doublec | protected function doublec($j)
{
if ($j < 1)
return false;
if ($this->b[$j] != $this->b[$j-1])
return false;
return $this->cons($j);
} | php | protected function doublec($j)
{
if ($j < 1)
return false;
if ($this->b[$j] != $this->b[$j-1])
return false;
return $this->cons($j);
} | [
"protected",
"function",
"doublec",
"(",
"$",
"j",
")",
"{",
"if",
"(",
"$",
"j",
"<",
"1",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"b",
"[",
"$",
"j",
"]",
"!=",
"$",
"this",
"->",
"b",
"[",
"$",
"j",
"-",
"1",
"]",
")... | /* doublec(j) is TRUE <=> j,(j-1) contain a double consonant. | [
"/",
"*",
"doublec",
"(",
"j",
")",
"is",
"TRUE",
"<",
"=",
">",
"j",
"(",
"j",
"-",
"1",
")",
"contain",
"a",
"double",
"consonant",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L120-L127 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.cvc | protected function cvc($i)
{
if ($i < 2 || !$this->cons($i) || $this->cons($i-1) || !$this->cons($i-2))
return false;
$ch = $this->b[$i];
if ($ch === 'w' || $ch === 'x' || $ch === 'y')
return false;
return true;
} | php | protected function cvc($i)
{
if ($i < 2 || !$this->cons($i) || $this->cons($i-1) || !$this->cons($i-2))
return false;
$ch = $this->b[$i];
if ($ch === 'w' || $ch === 'x' || $ch === 'y')
return false;
return true;
} | [
"protected",
"function",
"cvc",
"(",
"$",
"i",
")",
"{",
"if",
"(",
"$",
"i",
"<",
"2",
"||",
"!",
"$",
"this",
"->",
"cons",
"(",
"$",
"i",
")",
"||",
"$",
"this",
"->",
"cons",
"(",
"$",
"i",
"-",
"1",
")",
"||",
"!",
"$",
"this",
"->",... | /*
cvc(i) is TRUE <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short word. e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray. | [
"/",
"*",
"cvc",
"(",
"i",
")",
"is",
"TRUE",
"<",
"=",
">",
"i",
"-",
"2",
"i",
"-",
"1",
"i",
"has",
"the",
"form",
"consonant",
"-",
"vowel",
"-",
"consonant",
"and",
"also",
"if",
"the",
"second",
"c",
"is",
"not",
"w",
"x",
"or",
"y",
... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L138-L147 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.ends | protected function ends($s,$length)
{
if ($s[$length-1] != $this->b[$this->k])
return false;
if ($length >= $this->k+1)
return false;
if (substr_compare($this->b,$s,$this->k-$length+1,$length)!=0)
return false;
$this->j = $this->k-$length;
return true;
} | php | protected function ends($s,$length)
{
if ($s[$length-1] != $this->b[$this->k])
return false;
if ($length >= $this->k+1)
return false;
if (substr_compare($this->b,$s,$this->k-$length+1,$length)!=0)
return false;
$this->j = $this->k-$length;
return true;
} | [
"protected",
"function",
"ends",
"(",
"$",
"s",
",",
"$",
"length",
")",
"{",
"if",
"(",
"$",
"s",
"[",
"$",
"length",
"-",
"1",
"]",
"!=",
"$",
"this",
"->",
"b",
"[",
"$",
"this",
"->",
"k",
"]",
")",
"return",
"false",
";",
"if",
"(",
"$... | /*
ends(s) is TRUE <=> 0...k ends with the string s.
$length is passed as a parameter because it provides a speedup. | [
"/",
"*",
"ends",
"(",
"s",
")",
"is",
"TRUE",
"<",
"=",
">",
"0",
"...",
"k",
"ends",
"with",
"the",
"string",
"s",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L154-L166 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.setto | protected function setto($s,$length)
{
$this->b = substr_replace($this->b,$s,$this->j+1);
$this->k = $this->j+$length;
} | php | protected function setto($s,$length)
{
$this->b = substr_replace($this->b,$s,$this->j+1);
$this->k = $this->j+$length;
} | [
"protected",
"function",
"setto",
"(",
"$",
"s",
",",
"$",
"length",
")",
"{",
"$",
"this",
"->",
"b",
"=",
"substr_replace",
"(",
"$",
"this",
"->",
"b",
",",
"$",
"s",
",",
"$",
"this",
"->",
"j",
"+",
"1",
")",
";",
"$",
"this",
"->",
"k",... | /*
setto(s) sets (j+1),...k to the characters in the string s,
readjusting k.
Again $length is passed for speedup | [
"/",
"*",
"setto",
"(",
"s",
")",
"sets",
"(",
"j",
"+",
"1",
")",
"...",
"k",
"to",
"the",
"characters",
"in",
"the",
"string",
"s",
"readjusting",
"k",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L174-L178 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.step1ab | protected function step1ab()
{
if ($this->b[$this->k] === 's') {
if ($this->ends("sses",4))
$this->k -= 2;
else if ($this->ends("ies",3))
$this->setto("i",1);
else if ($this->b[$this->k-1] !== 's')
$this->k--;
}
if ($this->ends("eed",3)) {
if ($this->m() > 0)
$this->k--;
} elseif (($this->ends("ed",2) || $this->ends("ing",3)) && $this->vowelinstem()) {
$this->k = $this->j;
if ($this->ends("at",2))
$this->setto("ate",3);
else if ($this->ends("bl",2))
$this->setto("ble",3);
else if ($this->ends("iz",2))
$this->setto("ize",3);
else if ($this->doublec($this->k)) {
$this->k--;
$ch = $this->b[$this->k];
if ($ch === 'l' || $ch === 's' || $ch === 'z')
$this->k++;
} elseif ($this->m() === 1 && $this->cvc($this->k)) {
$this->setto("e",1);
}
}
} | php | protected function step1ab()
{
if ($this->b[$this->k] === 's') {
if ($this->ends("sses",4))
$this->k -= 2;
else if ($this->ends("ies",3))
$this->setto("i",1);
else if ($this->b[$this->k-1] !== 's')
$this->k--;
}
if ($this->ends("eed",3)) {
if ($this->m() > 0)
$this->k--;
} elseif (($this->ends("ed",2) || $this->ends("ing",3)) && $this->vowelinstem()) {
$this->k = $this->j;
if ($this->ends("at",2))
$this->setto("ate",3);
else if ($this->ends("bl",2))
$this->setto("ble",3);
else if ($this->ends("iz",2))
$this->setto("ize",3);
else if ($this->doublec($this->k)) {
$this->k--;
$ch = $this->b[$this->k];
if ($ch === 'l' || $ch === 's' || $ch === 'z')
$this->k++;
} elseif ($this->m() === 1 && $this->cvc($this->k)) {
$this->setto("e",1);
}
}
} | [
"protected",
"function",
"step1ab",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"b",
"[",
"$",
"this",
"->",
"k",
"]",
"===",
"'s'",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"ends",
"(",
"\"sses\"",
",",
"4",
")",
")",
"$",
"this",
"->",
"k",... | /*
step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting -> mat
mating -> mate
meeting -> meet
milling -> mill
messing -> mess
meetings -> meet | [
"/",
"*",
"step1ab",
"()",
"gets",
"rid",
"of",
"plurals",
"and",
"-",
"ed",
"or",
"-",
"ing",
".",
"e",
".",
"g",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L208-L238 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.step2 | protected function step2()
{
switch ($this->b[$this->k-1]) {
case 'a':
if ($this->ends("ational",7)) { $this->r("ate",3); break; }
if ($this->ends("tional",6)) { $this->r("tion",4); break; }
break;
case 'c':
if ($this->ends("enci",4)) { $this->r("ence",4); break; }
if ($this->ends("anci",4)) { $this->r("ance",4); break; }
break;
case 'e':
if ($this->ends("izer",4)) { $this->r("ize",3); break; }
break;
case 'l':
if ($this->ends("bli",3)) { $this->r("ble",3); break; }
// -DEPARTURE-
// To match the published algorithm, replace the above line with
// if ($this->ends("abli",4)) { $this->r("able",4); break; }
if ($this->ends("alli",4)) { $this->r("al",2); break; }
if ($this->ends("entli",5)) { $this->r("ent",3); break; }
if ($this->ends("eli",3)) { $this->r("e",1); break; }
if ($this->ends("ousli",5)) { $this->r("ous",3); break; }
break;
case 'o':
if ($this->ends("ization",7)) { $this->r("ize",3); break; }
if ($this->ends("ation",5)) { $this->r("ate",3); break; }
if ($this->ends("ator",4)) { $this->r("ate",3); break; }
break;
case 's':
if ($this->ends("alism",5)) { $this->r("al",2); break; }
if ($this->ends("iveness",7)) { $this->r("ive",3); break; }
if ($this->ends("fulness",7)) { $this->r("ful",3); break; }
if ($this->ends("ousness",7)) { $this->r("ous",3); break; }
break;
case 't':
if ($this->ends("aliti",5)) { $this->r("al",2); break; }
if ($this->ends("iviti",5)) { $this->r("ive",3); break; }
if ($this->ends("biliti",6)) { $this->r("ble",3); break; }
break;
case 'g':
if ($this->ends("logi",4)) { $this->r("log",3); break; }
// -DEPARTURE-
// To match the published algorithm delete the above line
}
} | php | protected function step2()
{
switch ($this->b[$this->k-1]) {
case 'a':
if ($this->ends("ational",7)) { $this->r("ate",3); break; }
if ($this->ends("tional",6)) { $this->r("tion",4); break; }
break;
case 'c':
if ($this->ends("enci",4)) { $this->r("ence",4); break; }
if ($this->ends("anci",4)) { $this->r("ance",4); break; }
break;
case 'e':
if ($this->ends("izer",4)) { $this->r("ize",3); break; }
break;
case 'l':
if ($this->ends("bli",3)) { $this->r("ble",3); break; }
// -DEPARTURE-
// To match the published algorithm, replace the above line with
// if ($this->ends("abli",4)) { $this->r("able",4); break; }
if ($this->ends("alli",4)) { $this->r("al",2); break; }
if ($this->ends("entli",5)) { $this->r("ent",3); break; }
if ($this->ends("eli",3)) { $this->r("e",1); break; }
if ($this->ends("ousli",5)) { $this->r("ous",3); break; }
break;
case 'o':
if ($this->ends("ization",7)) { $this->r("ize",3); break; }
if ($this->ends("ation",5)) { $this->r("ate",3); break; }
if ($this->ends("ator",4)) { $this->r("ate",3); break; }
break;
case 's':
if ($this->ends("alism",5)) { $this->r("al",2); break; }
if ($this->ends("iveness",7)) { $this->r("ive",3); break; }
if ($this->ends("fulness",7)) { $this->r("ful",3); break; }
if ($this->ends("ousness",7)) { $this->r("ous",3); break; }
break;
case 't':
if ($this->ends("aliti",5)) { $this->r("al",2); break; }
if ($this->ends("iviti",5)) { $this->r("ive",3); break; }
if ($this->ends("biliti",6)) { $this->r("ble",3); break; }
break;
case 'g':
if ($this->ends("logi",4)) { $this->r("log",3); break; }
// -DEPARTURE-
// To match the published algorithm delete the above line
}
} | [
"protected",
"function",
"step2",
"(",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"b",
"[",
"$",
"this",
"->",
"k",
"-",
"1",
"]",
")",
"{",
"case",
"'a'",
":",
"if",
"(",
"$",
"this",
"->",
"ends",
"(",
"\"ational\"",
",",
"7",
")",
")",
"{... | /*
step2() maps double suffices to single ones. so -ization
( = -ize plus -ation) maps to -ize etc. note that the string
before the suffix must give m() > 0. | [
"/",
"*",
"step2",
"()",
"maps",
"double",
"suffices",
"to",
"single",
"ones",
".",
"so",
"-",
"ization",
"(",
"=",
"-",
"ize",
"plus",
"-",
"ation",
")",
"maps",
"to",
"-",
"ize",
"etc",
".",
"note",
"that",
"the",
"string",
"before",
"the",
"suff... | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L257-L302 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.step3 | protected function step3()
{
switch ($this->b[$this->k]) {
case 'e':
if ($this->ends("icate",5)) { $this->r("ic",2); break; }
if ($this->ends("ative",5)) { $this->r("",0); break; }
if ($this->ends("alize",5)) { $this->r("al",2); break; }
break;
case 'i':
if ($this->ends("iciti",5)) { $this->r("ic",2); break; }
break;
case 'l':
if ($this->ends("ical",4)) { $this->r("ic",2); break; }
if ($this->ends("ful",3)) { $this->r("",0); break; }
break;
case 's':
if ($this->ends("ness",4)) { $this->r("",0); break; }
break;
}
} | php | protected function step3()
{
switch ($this->b[$this->k]) {
case 'e':
if ($this->ends("icate",5)) { $this->r("ic",2); break; }
if ($this->ends("ative",5)) { $this->r("",0); break; }
if ($this->ends("alize",5)) { $this->r("al",2); break; }
break;
case 'i':
if ($this->ends("iciti",5)) { $this->r("ic",2); break; }
break;
case 'l':
if ($this->ends("ical",4)) { $this->r("ic",2); break; }
if ($this->ends("ful",3)) { $this->r("",0); break; }
break;
case 's':
if ($this->ends("ness",4)) { $this->r("",0); break; }
break;
}
} | [
"protected",
"function",
"step3",
"(",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"b",
"[",
"$",
"this",
"->",
"k",
"]",
")",
"{",
"case",
"'e'",
":",
"if",
"(",
"$",
"this",
"->",
"ends",
"(",
"\"icate\"",
",",
"5",
")",
")",
"{",
"$",
"thi... | /*
step3() deals with -ic-, -full, -ness etc. similar strategy
to step2. | [
"/",
"*",
"step3",
"()",
"deals",
"with",
"-",
"ic",
"-",
"-",
"full",
"-",
"ness",
"etc",
".",
"similar",
"strategy",
"to",
"step2",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L309-L328 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.step4 | protected function step4()
{
switch ($this->b[$this->k-1]) {
case 'a':
if ($this->ends("al",2))
break;
return;
case 'c':
if ($this->ends("ance",4))
break;
if ($this->ends("ence",4))
break;
return;
case 'e':
if ($this->ends("er",2))
break;
return;
case 'i':
if ($this->ends("ic",2))
break;
return;
case 'l':
if ($this->ends("able",4))
break;
if ($this->ends("ible",4))
break;
return;
case 'n':
if ($this->ends("ant",3))
break;
if ($this->ends("ement",5))
break;
if ($this->ends("ment",4))
break;
if ($this->ends("ent",3))
break;
return;
case 'o':
if ($this->ends("ion",3) && ($this->b[$this->j] === 's' || $this->b[$this->j] === 't'))
break;
if ($this->ends("ou",2))
break;
return;
/* takes care of -ous */
case 's':
if ($this->ends("ism",3))
break;
return;
case 't':
if ($this->ends("ate",3))
break;
if ($this->ends("iti",3))
break;
return;
case 'u':
if ($this->ends("ous",3))
break;
return;
case 'v':
if ($this->ends("ive",3))
break;
return;
case 'z':
if ($this->ends("ize",3))
break;
return;
default:
return;
}
if ($this->m() > 1) $this->k = $this->j;
} | php | protected function step4()
{
switch ($this->b[$this->k-1]) {
case 'a':
if ($this->ends("al",2))
break;
return;
case 'c':
if ($this->ends("ance",4))
break;
if ($this->ends("ence",4))
break;
return;
case 'e':
if ($this->ends("er",2))
break;
return;
case 'i':
if ($this->ends("ic",2))
break;
return;
case 'l':
if ($this->ends("able",4))
break;
if ($this->ends("ible",4))
break;
return;
case 'n':
if ($this->ends("ant",3))
break;
if ($this->ends("ement",5))
break;
if ($this->ends("ment",4))
break;
if ($this->ends("ent",3))
break;
return;
case 'o':
if ($this->ends("ion",3) && ($this->b[$this->j] === 's' || $this->b[$this->j] === 't'))
break;
if ($this->ends("ou",2))
break;
return;
/* takes care of -ous */
case 's':
if ($this->ends("ism",3))
break;
return;
case 't':
if ($this->ends("ate",3))
break;
if ($this->ends("iti",3))
break;
return;
case 'u':
if ($this->ends("ous",3))
break;
return;
case 'v':
if ($this->ends("ive",3))
break;
return;
case 'z':
if ($this->ends("ize",3))
break;
return;
default:
return;
}
if ($this->m() > 1) $this->k = $this->j;
} | [
"protected",
"function",
"step4",
"(",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"b",
"[",
"$",
"this",
"->",
"k",
"-",
"1",
"]",
")",
"{",
"case",
"'a'",
":",
"if",
"(",
"$",
"this",
"->",
"ends",
"(",
"\"al\"",
",",
"2",
")",
")",
"break"... | /* step4() takes off -ant, -ence etc., in context <c>vcvc<v>. | [
"/",
"*",
"step4",
"()",
"takes",
"off",
"-",
"ant",
"-",
"ence",
"etc",
".",
"in",
"context",
"<c",
">",
"vcvc<v",
">",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L331-L413 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.step5 | protected function step5()
{
$this->j = $this->k;
if ($this->b[$this->k] === 'e') {
$a = $this->m();
if ($a > 1 || $a == 1 && !$this->cvc($this->k-1))
$this->k--;
}
if ($this->b[$this->k] === 'l' && $this->doublec($this->k) && $this->m() > 1)
$this->k--;
} | php | protected function step5()
{
$this->j = $this->k;
if ($this->b[$this->k] === 'e') {
$a = $this->m();
if ($a > 1 || $a == 1 && !$this->cvc($this->k-1))
$this->k--;
}
if ($this->b[$this->k] === 'l' && $this->doublec($this->k) && $this->m() > 1)
$this->k--;
} | [
"protected",
"function",
"step5",
"(",
")",
"{",
"$",
"this",
"->",
"j",
"=",
"$",
"this",
"->",
"k",
";",
"if",
"(",
"$",
"this",
"->",
"b",
"[",
"$",
"this",
"->",
"k",
"]",
"===",
"'e'",
")",
"{",
"$",
"a",
"=",
"$",
"this",
"->",
"m",
... | /*
step5() removes a final -e if m() > 1, and
changes -ll to -l if m() > 1. | [
"/",
"*",
"step5",
"()",
"removes",
"a",
"final",
"-",
"e",
"if",
"m",
"()",
">",
"1",
"and",
"changes",
"-",
"ll",
"to",
"-",
"l",
"if",
"m",
"()",
">",
"1",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L420-L430 |
angeloskath/php-nlp-tools | src/NlpTools/Stemmers/PorterStemmer.php | PorterStemmer.stem | public function stem($word)
{
$this->j=0;
$this->b = $word;
$this->k = strlen($word)-1;
if ($this->k<=1)
return $word;
$this->step1ab();
$this->step1c();
$this->step2();
$this->step3();
$this->step4();
$this->step5();
return substr($this->b,0,$this->k+1);
} | php | public function stem($word)
{
$this->j=0;
$this->b = $word;
$this->k = strlen($word)-1;
if ($this->k<=1)
return $word;
$this->step1ab();
$this->step1c();
$this->step2();
$this->step3();
$this->step4();
$this->step5();
return substr($this->b,0,$this->k+1);
} | [
"public",
"function",
"stem",
"(",
"$",
"word",
")",
"{",
"$",
"this",
"->",
"j",
"=",
"0",
";",
"$",
"this",
"->",
"b",
"=",
"$",
"word",
";",
"$",
"this",
"->",
"k",
"=",
"strlen",
"(",
"$",
"word",
")",
"-",
"1",
";",
"if",
"(",
"$",
"... | The word must be a lower case one byte per character string (in
English). | [
"The",
"word",
"must",
"be",
"a",
"lower",
"case",
"one",
"byte",
"per",
"character",
"string",
"(",
"in",
"English",
")",
"."
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Stemmers/PorterStemmer.php#L437-L453 |
angeloskath/php-nlp-tools | src/NlpTools/Clustering/Clusterer.php | Clusterer.getDocumentArray | protected function getDocumentArray(TrainingSet $documents, FeatureFactoryInterface $ff)
{
$docs = array();
foreach ($documents as $d) {
$docs[] = $ff->getFeatureArray('',$d);
}
return $docs;
} | php | protected function getDocumentArray(TrainingSet $documents, FeatureFactoryInterface $ff)
{
$docs = array();
foreach ($documents as $d) {
$docs[] = $ff->getFeatureArray('',$d);
}
return $docs;
} | [
"protected",
"function",
"getDocumentArray",
"(",
"TrainingSet",
"$",
"documents",
",",
"FeatureFactoryInterface",
"$",
"ff",
")",
"{",
"$",
"docs",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"documents",
"as",
"$",
"d",
")",
"{",
"$",
"docs",
"["... | Helper function to transform a TrainingSet to an array of feature vectors | [
"Helper",
"function",
"to",
"transform",
"a",
"TrainingSet",
"to",
"an",
"array",
"of",
"feature",
"vectors"
] | train | https://github.com/angeloskath/php-nlp-tools/blob/476e07c27fc032e4ca03ee599e7cd1ad0901af33/src/NlpTools/Clustering/Clusterer.php#L22-L30 |
thephpleague/uri-manipulations | src/Modifiers/AppendLabel.php | AppendLabel.modifyHost | protected function modifyHost(string $str): string
{
return (string) $this->filterHost($str)->append($this->label);
} | php | protected function modifyHost(string $str): string
{
return (string) $this->filterHost($str)->append($this->label);
} | [
"protected",
"function",
"modifyHost",
"(",
"string",
"$",
"str",
")",
":",
"string",
"{",
"return",
"(",
"string",
")",
"$",
"this",
"->",
"filterHost",
"(",
"$",
"str",
")",
"->",
"append",
"(",
"$",
"this",
"->",
"label",
")",
";",
"}"
] | Modify a URI part
@param string $str the URI part string representation
@return string the modified URI part string representation | [
"Modify",
"a",
"URI",
"part"
] | train | https://github.com/thephpleague/uri-manipulations/blob/a9092d28abfca7db443871c84944f5e5c643c31b/src/Modifiers/AppendLabel.php#L55-L58 |
thephpleague/uri-manipulations | src/Modifiers/Subdomain.php | Subdomain.modifyHost | protected function modifyHost(string $str): string
{
return (string) $this->filterHost($str, $this->resolver)->withSubDomain($this->label);
} | php | protected function modifyHost(string $str): string
{
return (string) $this->filterHost($str, $this->resolver)->withSubDomain($this->label);
} | [
"protected",
"function",
"modifyHost",
"(",
"string",
"$",
"str",
")",
":",
"string",
"{",
"return",
"(",
"string",
")",
"$",
"this",
"->",
"filterHost",
"(",
"$",
"str",
",",
"$",
"this",
"->",
"resolver",
")",
"->",
"withSubDomain",
"(",
"$",
"this",... | Modify a URI part
@param string $str the URI part string representation
@return string the modified URI part string representation | [
"Modify",
"a",
"URI",
"part"
] | train | https://github.com/thephpleague/uri-manipulations/blob/a9092d28abfca7db443871c84944f5e5c643c31b/src/Modifiers/Subdomain.php#L69-L72 |
thephpleague/uri-manipulations | src/Modifiers/DataUriParameters.php | DataUriParameters.modifyPath | protected function modifyPath(string $str): string
{
return (string) $this->filterDataPath($str)->withParameters($this->parameters);
} | php | protected function modifyPath(string $str): string
{
return (string) $this->filterDataPath($str)->withParameters($this->parameters);
} | [
"protected",
"function",
"modifyPath",
"(",
"string",
"$",
"str",
")",
":",
"string",
"{",
"return",
"(",
"string",
")",
"$",
"this",
"->",
"filterDataPath",
"(",
"$",
"str",
")",
"->",
"withParameters",
"(",
"$",
"this",
"->",
"parameters",
")",
";",
... | Modify a URI part
@param string $str the URI part string representation
@return string the modified URI part string representation | [
"Modify",
"a",
"URI",
"part"
] | train | https://github.com/thephpleague/uri-manipulations/blob/a9092d28abfca7db443871c84944f5e5c643c31b/src/Modifiers/DataUriParameters.php#L55-L58 |
thephpleague/uri-manipulations | src/Modifiers/RemoveQueryParams.php | RemoveQueryParams.modifyQuery | protected function modifyQuery(string $str): string
{
return (string) $this->filterQuery($str)->withoutParams($this->keys);
} | php | protected function modifyQuery(string $str): string
{
return (string) $this->filterQuery($str)->withoutParams($this->keys);
} | [
"protected",
"function",
"modifyQuery",
"(",
"string",
"$",
"str",
")",
":",
"string",
"{",
"return",
"(",
"string",
")",
"$",
"this",
"->",
"filterQuery",
"(",
"$",
"str",
")",
"->",
"withoutParams",
"(",
"$",
"this",
"->",
"keys",
")",
";",
"}"
] | Modify a URI part
@param string $str the URI part string representation
@return string the modified URI part string representation | [
"Modify",
"a",
"URI",
"part"
] | train | https://github.com/thephpleague/uri-manipulations/blob/a9092d28abfca7db443871c84944f5e5c643c31b/src/Modifiers/RemoveQueryParams.php#L54-L57 |
thephpleague/uri-manipulations | src/Modifiers/ReplaceLabel.php | ReplaceLabel.modifyHost | protected function modifyHost(string $str): string
{
return (string) $this->filterHost($str)->replaceLabel($this->offset, $this->label);
} | php | protected function modifyHost(string $str): string
{
return (string) $this->filterHost($str)->replaceLabel($this->offset, $this->label);
} | [
"protected",
"function",
"modifyHost",
"(",
"string",
"$",
"str",
")",
":",
"string",
"{",
"return",
"(",
"string",
")",
"$",
"this",
"->",
"filterHost",
"(",
"$",
"str",
")",
"->",
"replaceLabel",
"(",
"$",
"this",
"->",
"offset",
",",
"$",
"this",
... | Modify a URI part
@param string $str the URI part string representation
@return string the modified URI part string representation | [
"Modify",
"a",
"URI",
"part"
] | train | https://github.com/thephpleague/uri-manipulations/blob/a9092d28abfca7db443871c84944f5e5c643c31b/src/Modifiers/ReplaceLabel.php#L63-L66 |
thephpleague/uri-manipulations | src/Modifiers/Resolve.php | Resolve.execute | protected function execute($uri)
{
$target_path = $uri->getPath();
if ('' !== $uri->getScheme()) {
return $uri
->withPath((string) $this->filterPath($target_path)->withoutDotSegments());
}
if ('' !== $uri->getAuthority()) {
return $uri
->withScheme($this->base_uri->getScheme())
->withPath((string) $this->filterPath($target_path)->withoutDotSegments());
}
list($user, $pass) = explode(':', $this->base_uri->getUserInfo(), 2) + ['', null];
$components = $this->resolvePathAndQuery($target_path, $uri->getQuery());
return $uri
->withPath($this->formatPath($components['path']))
->withQuery($components['query'])
->withHost($this->base_uri->getHost())
->withPort($this->base_uri->getPort())
->withUserInfo($user, $pass)
->withScheme($this->base_uri->getScheme());
} | php | protected function execute($uri)
{
$target_path = $uri->getPath();
if ('' !== $uri->getScheme()) {
return $uri
->withPath((string) $this->filterPath($target_path)->withoutDotSegments());
}
if ('' !== $uri->getAuthority()) {
return $uri
->withScheme($this->base_uri->getScheme())
->withPath((string) $this->filterPath($target_path)->withoutDotSegments());
}
list($user, $pass) = explode(':', $this->base_uri->getUserInfo(), 2) + ['', null];
$components = $this->resolvePathAndQuery($target_path, $uri->getQuery());
return $uri
->withPath($this->formatPath($components['path']))
->withQuery($components['query'])
->withHost($this->base_uri->getHost())
->withPort($this->base_uri->getPort())
->withUserInfo($user, $pass)
->withScheme($this->base_uri->getScheme());
} | [
"protected",
"function",
"execute",
"(",
"$",
"uri",
")",
"{",
"$",
"target_path",
"=",
"$",
"uri",
"->",
"getPath",
"(",
")",
";",
"if",
"(",
"''",
"!==",
"$",
"uri",
"->",
"getScheme",
"(",
")",
")",
"{",
"return",
"$",
"uri",
"->",
"withPath",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/thephpleague/uri-manipulations/blob/a9092d28abfca7db443871c84944f5e5c643c31b/src/Modifiers/Resolve.php#L62-L86 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.