刚好看到有篇关于人工智能数据分析的文章,于是就有了下面的操作, 方便 Laravel 快捷使用, 使用前请先阅读 介绍文

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
<?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);
} else {
$predict = ['香烟'];
}

$this->setRule(0.5, 0.5, $this->filepath);
$getModel = $this->getModel($this->filepath, $predict);

if(!empty($getModel)) {
return $getModel;
} else {
return "对不起,没有找到 ‘" . implode(",", $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);
}
}