Repository navigation
Expand file tree
/
Copy pathml.php
More file actions
84 lines (69 loc) · 2.82 KB
/
Copy pathml.php
File metadata and controls
84 lines (69 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/**
* @see https://stovepipe.systems/post/machine-learning-naive-bayes
*/
class Classifier
{
private $types = [Type::POSITIVE, Type::NEGATIVE];
private $words = [Type::POSITIVE => [], Type::NEGATIVE => []];
private $documents = [Type::POSITIVE => 0, Type::NEGATIVE => 0];
public function guess($statement)
{
$words = $this->getWords($statement); // get the words
$best_likelihood = 0;
$best_type = null;
foreach ($this->types as $type) {
$likelihood = $this->totalP($type); // calculate P(Type)
foreach ($words as $word) {
$likelihood *= $this->p($word, $type); // calculate P(word, Type)
}
if ($likelihood > $best_likelihood) {
$best_likelihood = $likelihood;
$best_type = $type;
}
}
return $best_type;
}
public function learn($statement, $type)
{
$words = $this->getWords($statement);
foreach ($words as $word) {
if (!isset($this->words[$type][$word])) {
$this->words[$type][$word] = 0;
}
$this->words[$type][$word]++; // increment the word count for the type
}
$this->documents[$type]++; // increment the document count for the type
}
public function totalP($type)
{
return ($this->documents[$type] + 1) / (array_sum($this->documents) + 1);
}
public function p($word, $type)
{
$count = isset($this->words[$type][$word]) ? $this->words[$type][$word] : 0;
return ($count + 1) / (array_sum($this->words[$type]) + 1);
}
public function getWords($string)
{
return preg_split('/\s+/', preg_replace('/[^А-Яа-яA-Za-z0-9\s]/', '', strtolower($string)));
}
}
class Type
{
const POSITIVE = 'positive';
const NEGATIVE = 'negative';
}
$classifier = new Classifier();
$classifier->learn('Symfony is the best', Type::POSITIVE);
$classifier->learn('PhpStorm is great', Type::POSITIVE);
$classifier->learn('Iltar complains a lot', Type::NEGATIVE);
$classifier->learn('No Symfony is bad', Type::NEGATIVE);
//$classifier->learn('Зомби очень это плохо', Type::NEGATIVE);
//$classifier->learn('Ипотечное рабство убивает', Type::NEGATIVE);
//$classifier->learn('Кофе по утрам это очень хорошо', Type::POSITIVE);
//$classifier->learn('Котики спасут мир', Type::POSITIVE);
var_dump($classifier->guess('Symfony is great')); // string(8) "positive"
var_dump($classifier->guess('I complain a lot')); // string(8) "negative"
//var_dump($classifier->guess('Зомби едят мозги')); // string(8) "positive"
//var_dump($classifier->guess('Котики не пьют кофе с утра')); // string(8) "negative"