关于 PHP-ML 用户习惯分析 Laravel 实验代码整理
刚好看到有篇关于人工智能数据分析的文章,于是就有了下面的操作, 方便
Laravel
快捷使用, 使用前请先阅读 介绍文 。
<?php
/*
* phpml 人工智能
* 启蒙链接: https://learnku.com/articles/41793
* */
namespace App\Http\Controllers\Api;
use App\Http\Controllers\PublicController;
use Illuminate\Http\Request;
use Phpml\Association\Apriori;
use Phpml\ModelManager;
class phpMlController extends PublicController
{
private $manager;
private $request;
private $filepath;
public function __construct()
{
$this->manager = new ModelManager();
$this->request = new Request();
$this->filepath = public_path("phpmlModel.txt");
}
// 主进程
public function index(String $predict = Null) {
if($predict) {
$predict = explode(",", $predict);
}
$this->setRule(0.5, 0.5, $this->filepath);
return $this->getModel($this->filepath, $predict);
}
// 配置规则
public function setRule(float $support, float $confidence, String $filepath) : void {
$associator = new Apriori($support, $confidence);
$samples = $this->samples();
$associator->train($samples, []);
$associator->getRules();
$this->saveModel($associator, $filepath);
}
// 数据对象
private function samples() {
return [
['香烟','打火机'],
['香烟','炸鸡','啤酒','鸡排'],
['打火机','炸鸡','啤酒','可乐'],
['香烟','打火机','炸鸡','啤酒'],
['香烟','打火机','炸鸡','可乐']
];
}
// 保存模型
private function saveModel($associator, String $filepath) : void {
$this->manager->saveToFile($associator, $filepath);
}
// 使用模型
private function getModel(String $filepath, Array $samples) {
$restoredAssociator = $this->manager->restoreFromFile($filepath);
return $restoredAssociator->predict($samples);
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: