iOS使用CoreML來分類垃圾信息

前言


蘋果Create ML目前已支持Natural Language處理,這里介紹一個簡單的使用CoreML來分類垃圾信息的應(yīng)用贪庙。

使用到的數(shù)據(jù)來源于英文短信SMS Spam Collection v. 1:

Application File format # Spam # Ham Total Link
General Plain text 747 4,827 5,574 Link 1
Weka ARFF 747 4,827 5,574 Link 2
垃圾短信

構(gòu)建模型


首先,下載的數(shù)據(jù)已經(jīng)基本是標注好的题诵,但是缺少列名懂酱,我們需要給數(shù)據(jù)加上label各墨,text兩列名逛裤,方便后面訓練模型使用瘩绒。

添加列名

然后,我們利用xcode創(chuàng)建一個MacOS的playground工程带族,因為目前CreateML庫iOS不支持锁荔。然后編寫訓練模型,可以參考官方教程Creating a Text Classifier Model炉菲。
以下是我們工程代碼:

import CreateML
import Cocoa

let data = try MLDataTable(contentsOf: URL(fileURLWithPath: "/Users/Jiao/Desktop/SecurityKeeper/SMSSpamDetect/SMSSpamCollection.csv"))
let (trainData, testData) = data.randomSplit(by: 0.8, seed: 10)
let SMSClassifier = try MLTextClassifier(trainingData: trainData, textColumn: "text", labelColumn: "label")
let trainAcc = (1 - SMSClassifier.trainingMetrics.classificationError) * 100
let validAcc = (1 - SMSClassifier.validationMetrics.classificationError) * 100

let evalMetrics = SMSClassifier.evaluation(on: testData)
let evalAcc = (1 - evalMetrics.classificationError) * 100
print(trainAcc, validAcc, evalAcc)

let metadata = MLModelMetadata(author: "Jiao", shortDescription: "SMS SPAM Detect", license: "MIT", version: "1.0", additional: nil)
try SMSClassifier.write(to: URL(fileURLWithPath: "/Users/Jiao/Desktop/SecurityKeeper/SMSSpamDetect/mlmodel/SMSClassifier.mlmodel"), metadata: metadata)

// test
let l = try SMSClassifier.prediction(from: "free phone")

非常傻瓜式的使用堕战,不需要關(guān)心具體的分類實現(xiàn)過程坤溃,準確率能達到97%~98%拍霜。

iOS上使用模型


有了mlmodel,在移動端使用就很簡單了薪介,直接導入model進工程祠饺,然后初始化,在需要使用的地方調(diào)用predict就行了汁政。


xcode導入模型

代碼如下:

//
//  TableViewController.m
//  MessageDetect
//
//  Created by Jiao Liu on 5/29/19.
//  Copyright ? 2019 ChangHong. All rights reserved.
//

#import "TableViewController.h"
#import "SMSClassifier.h"

@interface TableViewController ()
{
    NSMutableArray *data;
    SMSClassifier *classifier;
}

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    classifier = [[SMSClassifier alloc] init];
    NSArray *initD = @[@"Did you hear about the new \"Divorce Barbie\"? It comes with all of Ken's stuff!",
             @"100 dating service cal;l 09064012103 box334sk38ch",
             @"Hello, I'm james",
             @"Even my brother is not like to speak with me. They treat me like aids patent.",
             @"HOT LIVE FANTASIES call now 08707509020 Just 20p per min NTT Ltd, PO Box 1327 Croydon CR9 5WB 0870..k",
             @"Ok...",
             @"Yeah!!",
             @"Oh my God.",
             @"Our brand new mobile music service is now live. The free music player will arrive shortly. Just install on your phone to browse content from the top artists."];
    data = [NSMutableArray arrayWithArray:initD];
    self.tableView.allowsSelection = NO;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return data.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Message" forIndexPath:indexPath];
    
    cell.textLabel.text = data[indexPath.row];
    NSString *type = [classifier predictionFromText:data[indexPath.row] error:nil].label;
    if ([type isEqualToString:@"spam"]) {
        cell.textLabel.textColor = [UIColor redColor];
        cell.accessoryType = UITableViewCellAccessoryDetailButton;
    }
    else
    {
        cell.textLabel.textColor = [UIColor blackColor];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    cell.textLabel.numberOfLines = 0;
    
    return cell;
}

- (IBAction)AddMessage:(id)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"New Message" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"message";
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *newMsg = alert.textFields.firstObject.text;
        if (newMsg.length != 0) {
            [self->data insertObject:alert.textFields.firstObject.text atIndex:0];
            [self.tableView reloadData];
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

@end

運行效果


源碼地址:https://github.com/JiaoLiu/SMSSpamDetect ??

demo.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末道偷,一起剝皮案震驚了整個濱河市缀旁,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌勺鸦,老刑警劉巖并巍,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異换途,居然都是意外死亡懊渡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進店門军拟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來剃执,“玉大人,你說我怎么就攤上這事懈息∩龅担” “怎么了?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵辫继,是天一觀的道長怒见。 經(jīng)常有香客問我,道長骇两,這世上最難降的妖魔是什么速种? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮低千,結(jié)果婚禮上配阵,老公的妹妹穿的比我還像新娘。我一直安慰自己示血,他們只是感情好棋傍,可當我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著难审,像睡著了一般瘫拣。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上告喊,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天麸拄,我揣著相機與錄音,去河邊找鬼黔姜。 笑死拢切,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的秆吵。 我是一名探鬼主播淮椰,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了主穗?” 一聲冷哼從身側(cè)響起泻拦,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎忽媒,沒想到半個月后争拐,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡晦雨,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年陆错,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片金赦。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡音瓷,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出夹抗,到底是詐尸還是另有隱情绳慎,我是刑警寧澤,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布漠烧,位于F島的核電站杏愤,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏已脓。R本人自食惡果不足惜珊楼,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望度液。 院中可真熱鬧厕宗,春花似錦、人聲如沸堕担。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽霹购。三九已至佑惠,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間齐疙,已是汗流浹背膜楷。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留贞奋,地道東北人赌厅。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像忆矛,于是被迫代替她去往敵國和親察蹲。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,573評論 2 359