Skip to content

Instantly share code, notes, and snippets.

@celsowm
Created September 22, 2019 14:09
Show Gist options
  • Save celsowm/12a89ae055261742109f94d5a0382b03 to your computer and use it in GitHub Desktop.
Save celsowm/12a89ae055261742109f94d5a0382b03 to your computer and use it in GitHub Desktop.
<?php
include_once './vendor/autoload.php';
//source: https://www.softnix.co.th/2018/08/19/naive-bays-text-classification-with-php/
use Phpml\Classification\NaiveBayes;
use Phpml\FeatureExtraction\TfIdfTransformer;
use Phpml\FeatureExtraction\TokenCountVectorizer;
use Phpml\Tokenization\WordTokenizer;
$arr_text = [
"London bridge is falling down",
"Beatles in abbey road Apple Records",
"japan samurai Universal Studio spider man",
"2020 Olympic games in Tokyo",
"China beijing olympic games 2008",
"bailu village in shenmue 3",
"Hamburger Donald Trump Mickey Mouse",
"Universal Studio Hollywood Orlando Florida",
];
$arr_label = [
"London", "London","Japan","Japan","China","China","USA","USA"
];
$tokenize = new WordTokenizer();
$vectorizer = new TokenCountVectorizer($tokenize);
$vectorizer->fit($arr_text);
$vocabulary = $vectorizer->getVocabulary();
$arr_transform = $arr_text;
$vectorizer->transform($arr_transform);
$transformer = new TfIdfTransformer($arr_transform);
$transformer->transform($arr_transform);
$classifier = new NaiveBayes();
$classifier->train($arr_transform, $arr_label);
$arr_testset = [
'Yu Suzuki developed Shenmue',
'I want to go Universal Studio',
'I want to go Universal Studio because I want to watch spider man',
'Sonic in 2020',
'Shenmue'
];
$vectorizer->transform($arr_testset);
$transformer->transform($arr_testset);
$result = $classifier->predict($arr_testset);
var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment