PHP-ML (php機器學習庫)詳細學習

github : https://github.com/php-ai/php-ml

建議 composer 

composer require php-ai/php-ml

文檔地址:http://php-ml.readthedocs.io/en/latest/

代碼:

require_once '../vendor/autoload.php';
use Phpml\Classification\KNearestNeighbors;
use Phpml\Association\Apriori;
use Phpml\Regression\LeastSquares;
use Phpml\Math\Statistic\StandardDeviation;
use Phpml\Math\Statistic\Correlation;
use Phpml\Dataset\CsvDataset;
use Phpml\Classification\Ensemble\RandomForest;


/**K近鄰算法**/
//應用於 文本分類、聚類分析、預測分析、模式識別、圖像處理
$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
$labels = ['a', 'a', 'a', 'b', 'b', 'b'];
$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);
$res = $classifier->predict([[3, 2],[1, 3]]);
//print_r($res); // return b a


/**先驗算法**/
//根據數據列出樣本,和提供的一個樣本,算出含有提供的樣本的所有數據(以數組形式返回)
$samples = [['alpha', 'beta', 'epsilon'], ['alpha', 'beta', 'theta'], ['alpha', 'beta', 'epsilon'], ['alpha', 'beta', 'theta']];
$labels  = [];
$associator = new Apriori($support = 0.5, $confidence = 0.5);
$associator->train($samples, $labels);
$res = $associator->predict(['alpha','theta']);
//print_r($res);
// return [['beta']]

$res = $associator->predict([['alpha','epsilon'],['beta','theta']]);
//print_r($res);
// return [[['beta']], [['alpha']]]

//獲取生成的關聯規則只需使用rules方法。
$res = $associator->getRules();
//print_r($res);
// return [['antecedent' => ['alpha', 'theta'], 'consequent' => ['beta'], 'support' => 1.0, 'confidence' => 1.0], ... ]

//生成k長度的頻繁項集只需使用apriori方法即可。
$res = $associator->apriori();
//print_r($res);
// return [ 1 => [['alpha'], ['beta'], ['theta'], ['epsilon']], 2 => [...], ...]


/**多元線性迴歸**/
$samples = [[73676, 1996], [77006, 1998], [10565, 2000], [146088, 1995], [15000, 2001], [65940, 2000], [9300, 2000], [93739, 1996], [153260, 1994], [17764, 2002], [57000, 1998], [15000, 2000]];//【里程 年份】
$targets = [2000, 2750, 15500, 960, 4400, 8800, 7100, 2550, 1025, 5900, 4600, 4400]; //價格
$regression = new LeastSquares();
$regression->train($samples, $targets);
$res = $regression->predict([60000, 1996]); //計算出 1996 年,60000里程的車,預測價格 是  4094.82
//print_r($res);
//return 4094.82

/**計算標準差**/
$population = [5, 6, 8, 9];
$res = StandardDeviation::population($population);
//print_r($res);
// return 1.825
$population = [7100, 15500, 4400, 4400, 5900, 4600, 8800, 2000, 2750, 2550,  960, 1025];
$res = StandardDeviation::population($population);
//print_r($res);
//return 4079

/**皮爾遜相關**/
$x = [43, 21, 25, 42, 57, 59];
$y = [99, 65, 79, 75, 87, 82];
$res = Correlation::pearson($x, $y);
//print_r($res);
//return 0.549
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章