介紹
機器學習無所不在-推薦影片、標記影像,現在甚至將新聞文章分類。想像一下如果您可以在 PHP 中做到這一點!透過 Rubix ML,您可以以簡單易懂的方式將機器學習的強大功能引入 PHP。本指南將引導您建立一個簡單的新聞分類器,將文章分類為「體育」或「技術」等類別。最後,您將擁有一個工作分類器,可以根據新文章的內容預測其類別。
這個專案非常適合想要使用 PHP 進行機器學習的初學者,您可以按照 GitHub 上的完整程式碼進行操作。
目錄
- 什麼是 Rubix ML?
- 設定項目
- 建立新聞分類類
- 訓練模型
- 預測新樣本
- 最後的想法
Rubix 機器學習是什麼?
Rubix ML 是一個 PHP 機器學習函式庫,它將 ML 工具和演算法引入 PHP 友善的環境中。無論您從事分類、迴歸、聚類,甚至自然語言處理,Rubix ML 都能滿足您的需求。它允許您加載和預處理資料、訓練模型並評估效能——所有這些都在 PHP 中進行。
Rubix ML 支援廣泛的機器學習任務,例如:
- 分類:將資料分類,例如將電子郵件標記為垃圾郵件或非垃圾郵件。
- 迴歸:預測連續值,例如房價。
- 聚類:將沒有標籤的資料分組,就像尋找客戶群一樣。
- 自然語言處理 (NLP):處理文字數據,例如標記並將其轉換為 ML 可用的格式。
讓我們深入了解如何使用 Rubix ML 在 PHP 中建立簡單的新聞分類器!
設定項目
我們將首先使用 Rubix ML 設定一個新的 PHP 專案並配置自動載入。
步驟1:初始化專案目錄
建立一個新的專案目錄並導航到其中:
mkdir NewsClassifier cd NewsClassifier
第 2 步:安裝 Rubix ML 和 Composer
確保您已安裝 Composer,然後透過執行以下命令將 Rubix ML 新增至您的專案:
composer require rubix/ml
步驟3:在composer.json中配置自動加載
要從專案的 src 目錄自動載入類,請開啟或建立composer.json 檔案並新增以下配置:
{ "autoload": { "psr-4": { "NewsClassifier\": "src/" } }, "require": { "rubix/ml": "^2.5" } }
這告訴 Composer 自動載入 NewsClassifier 命名空間下 src 資料夾中的任何類別。
步驟 4: 執行 Composer Autoload Dump
新增自動載入設定後,執行下列指令重新產生 Composer 的自動載入器:
mkdir NewsClassifier cd NewsClassifier
第5步:目錄結構
您的專案目錄應如下所示:
composer require rubix/ml
- src/:包含您的 PHP 腳本。
- storage/:訓練後的模型的保存位置。
- vendor/:包含 Composer 安裝的依賴項。
建立新聞分類類
在 src/ 中,建立一個名為 Classification.php 的檔案。該文件將包含訓練模型和預測新聞類別的方法。
{ "autoload": { "psr-4": { "NewsClassifier\": "src/" } }, "require": { "rubix/ml": "^2.5" } }
此分類類別包含以下方法:
- 訓練:建立並訓練基於管道的模型。
- 保存模型:將訓練好的模型儲存到指定路徑
- 預測:載入已儲存的模型並預測新樣本的類別。
訓練模型
在 src/ 中建立一個名為 train.php 的腳本來訓練模型。
composer dump-autoload
執行此腳本來訓練模型:
NewsClassifier/ ├── src/ │ ├── Classification.php │ └── train.php ├── storage/ ├── vendor/ ├── composer.json └── composer.lock
如果成功,您將看到:
<?php namespace NewsClassifier; use Rubix\ML\Classifiers\KNearestNeighbors; use Rubix\ML\Datasets\Labeled; use Rubix\ML\Datasets\Unlabeled; use Rubix\ML\PersistentModel; use Rubix\ML\Pipeline; use Rubix\ML\Tokenizers\Word; use Rubix\ML\Transformers\TfIdfTransformer; use Rubix\ML\Transformers\WordCountVectorizer; use Rubix\ML\Persisters\Filesystem; class Classification { private $modelPath; public function __construct($modelPath) { $this->modelPath = $modelPath; } public function train() { // Sample data and corresponding labels $samples = [ ['The team played an amazing game of soccer'], ['The new programming language has been released'], ['The match between the two teams was incredible'], ['The new tech gadget has been launched'], ]; $labels = [ 'sports', 'technology', 'sports', 'technology', ]; // Create a labeled dataset $dataset = new Labeled($samples, $labels); // Set up the pipeline with a text transformer and K-Nearest Neighbors classifier $estimator = new Pipeline([ new WordCountVectorizer(10000, 1, 1, new Word()), new TfIdfTransformer(), ], new KNearestNeighbors(4)); // Train the model $estimator->train($dataset); // Save the model $this->saveModel($estimator); echo "Training completed and model saved.\n"; } private function saveModel($estimator) { $persister = new Filesystem($this->modelPath); $model = new PersistentModel($estimator, $persister); $model->save(); } public function predict(array $samples) { // Load the saved model $persister = new Filesystem($this->modelPath); $model = PersistentModel::load($persister); // Predict categories for new samples $dataset = new Unlabeled($samples); return $model->predict($dataset); } }
預測新樣本
在 src/ 中建立另一個腳本,predict.php,根據訓練的模型對新文章進行分類。
<?php require __DIR__ . '/../vendor/autoload.php'; use NewsClassifier\Classification; // Define the model path $modelPath = __DIR__ . '/../storage/model.rbx'; // Initialize the Classification object $classifier = new Classification($modelPath); // Train the model and save it $classifier->train();
運行預測腳本對樣本進行分類:
php src/train.php
輸出應顯示每個範例文字及其預測類別。
最後的想法
透過本指南,您已經使用 Rubix ML 在 PHP 中成功建立了一個簡單的新聞分類器!這展示了 PHP 如何比您想像的更通用,為文字分類、推薦系統等任務引入機器學習功能。此專案的完整程式碼可在 GitHub 上取得。
嘗試不同的演算法或資料來擴展分類器。誰知道 PHP 可以進行機器學習?現在你知道了。
快樂編碼!
以上是PHP 中的機器學習:使用 Rubix ML 建立新聞分類器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

SublimeText3 Linux新版
SublimeText3 Linux最新版

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中