搜尋
首頁後端開發php教程 SPAM、Bayesian跟中文 4 - 在CakePHP中集成贝叶斯算法

SPAM、Bayesian和中文 4 - 在CakePHP中集成贝叶斯算法

上文提到了贝叶斯算法的几种开源实现,本文说说如何将其中一种名为b8的开源实现集成进CakePHP。

下载b8及安装

  1. b8的站点下载最新版本,将其解压至vendors目录,文件位置如vendors/b8/b8.php;
  2. 用文本编辑器打开vendors/b8/etc/config_b8,修改databaseType为mysql;
  3. 用文本编辑器打开vendors/b8/etc/config_storage,修改tableName为你用来存储关键字的数据表的名字,修改createDB为TRUE,要注意的是,当你第一次运行b8后,它会建立上述数据表,然后你要重新把createDB改为FALSE;
  4. 用文本编辑器打开vendors/b8/lexer/shared_functions.php,将38行的代码(在echoError())注释掉,否则b8会直接把错误信息显示在你的Cake应用中,当然这在调试程序时还是有用的。

为b8写一个wrapper component

为了让你的Cake能够调用到b8,你需要写一个component。在controllers/components/新建一个spam_shield.php,加入如下代码:

class SpamShieldComponent extends Object {

??? /** * b8 instance?*/

??? var $b8;

??? /** * standard rating * * comments with ratings which are higher than this one will be considered as SPAM?*/

??? var $standardRating = 0.7;

??? /** * text to be classified */

??? var $text;

??? /** * rating of the text */

??? var $rating;

??? /** * Constructor * * @date 2009-1-20 */

??? function startup(&$controller) {

??????? //register a CommentModel to get the DBO resource link

??????? $comment = ClassRegistry::init('Comment'); //import b8 and create an instance????

?????? ?App::import('Vendor', 'b8/b8');

?????? ?$this->b8 = new b8($comment->getDBOResourceLink()); //set standard rating???

?????? ?$this->standardRating = Configure::read('LT.bayesRating') ? Configure::read('LT.bayesRating') : $this->standardRating;

??? }

?

??? /** * Set the text to be classified * * @param $text String the text to be classified * @date 2009-1-20 */

??? function set($text) {

??????? $this->text = $text;

??? }

?

??? /** * Get Bayesian rating * * @date 2009-1-20 */

??? function rate() {

?????? ?//get Bayes rating and return return

?????? ?$this->rating = $this->b8->classify($this->text);

??? }

?

??? /** * Validate a message based on the rating, return true if it's NOT a SPAM * * @date 2009-1-20 */

??? function validate() {

??????? return $this->rate() standardRating;

??? }

?

??? /** * Learn a SPAM or a HAM * * @date 2009-1-20 */

??? function learn($mode) {

?????? ?$this->b8->learn($this->text, $mode);

??? }

?

??? /** * Unlearn a SPAM or a HAM * * @date 2009-1-20 */

??? function unlearn($mode) {

?????? ?$this->b8->unlearn($this->text, $mode);

??? }

}

几点说明:

  1. $standardRating是一个临界点。如果贝叶斯概率高于这个值,则此留言被认为是spam,否则是ham。我设置为0.7,你可以根据自己的情况修改;
  2. Configure::read('LT.bayesRating')是从系统运行配置中动态地获取上述临界点的值,这是我的做法,你可能用不到,根据情况稍微修改甚至不修改都行;
  3. Comment指的是评论的model;
  4. 由于b8需要获得数据库句柄以便能够操作数据表,所以在startup()中我写了$this->b8 = new b8($comment->getDBOResourceLink())一句,其中用到的getDBOResourceLink()马上会提及。

为b8传入数据库句柄

在models/comment.php中加入如下代码:

/** * get the resource link of MySQL connection */ public function getDBOResourceLink() { return $this->getDataSource()->connection; }

至此,准备工作全部做完,我们终于可以使用贝叶斯算法来分类留言。

使用b8分类留言

在controllers/comments_controller.php中,首先载入SpamShieldComponent:

var $components = array('SpamShield');

然后在add()方法中,做如下操作:

//set data for Bayesian validation

$this->SpamShield->set($this->data['Comment']['body']); //validate the comment with Bayesian

if(!$this->SpamShield->validate()) { //set the status

??? $this->data['Comment']['status'] = 'spam'; //save

??? $this->Comment->save($this->data); //learn it $this->SpamShield->learn("spam"); //render

??? $this->renderView('unmoderated');

??? return;

}

//it's a normal post

$this->data['Comment']['status'] = 'published'; //save for publish

$this->Comment->save($this->data); //learn it

$this->SpamShield->learn("ham");

如此一来,b8就会在留言到来时自动的分类并学习,你基本上已经与spam绝缘了!

提醒一下:第一次运行后,别忘了把刚才提到的createDB改为FALSE。

http://dingyu.me/blog/spam-bayesian-chinese-4

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
高流量網站的PHP性能調整高流量網站的PHP性能調整May 14, 2025 am 12:13 AM

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

PHP中的依賴注入:初學者的代碼示例PHP中的依賴注入:初學者的代碼示例May 14, 2025 am 12:08 AM

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

PHP性能:是否可以優化應用程序?PHP性能:是否可以優化應用程序?May 14, 2025 am 12:04 AM

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

PHP性能優化:最終指南PHP性能優化:最終指南May 14, 2025 am 12:02 AM

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

PHP依賴注入容器:快速啟動PHP依賴注入容器:快速啟動May 13, 2025 am 12:11 AM

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

PHP中的依賴注入與服務定位器PHP中的依賴注入與服務定位器May 13, 2025 am 12:10 AM

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

PHP性能優化策略。PHP性能優化策略。May 13, 2025 am 12:06 AM

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

PHP電子郵件驗證:確保正確發送電子郵件PHP電子郵件驗證:確保正確發送電子郵件May 13, 2025 am 12:06 AM

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

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

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

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。