关于 PHP-ML 用户习惯分析 Laravel 实验代码整理

刚好看到有篇关于人工智能数据分析的文章,于是就有了下面的操作, 方便 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
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!