關於 PHP - ML 使用者習慣分析 Laravel 實驗程式碼整理

siYuanJun發表於2020-08-24

剛好看到有篇關於人工智慧資料分析的文章,於是就有了下面的操作, 方便 Laravel 快捷使用 :smiley: , 使用前請先閱讀 介紹文

<?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 協議》,轉載必須註明作者和本文連結
siYuanJun

相關文章