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