iOS使用CoreML分類汽車評(píng)論

前言


上一篇【iOS使用CoreML來(lái)分類垃圾信息】文章中用的是英文語(yǔ)料,而蘋果的文本分類其實(shí)是支持多語(yǔ)言的,而中文的訓(xùn)練在國(guó)內(nèi)更具實(shí)用價(jià)值,所以本文介紹如何針對(duì)中文語(yǔ)料進(jìn)行訓(xùn)練。

使用的數(shù)據(jù)來(lái)自汽車論壇的評(píng)論,有9000+條數(shù)據(jù),已經(jīng)進(jìn)行了標(biāo)記。

構(gòu)建模型


使用的原始數(shù)據(jù)格式如下,包含評(píng)論和已經(jīng)標(biāo)記的主題、ID、觀點(diǎn)等,我們模型只使用了評(píng)論和主題:

train.csv

模型訓(xùn)練:

import Cocoa
import CreateML
import NaturalLanguage

let data = try MLDataTable(contentsOf: URL(fileURLWithPath: "/Users/Jiao/Desktop/SecurityKeeper/CommentClassify/data.json"))
var (trainData, testData) = data.randomSplit(by: 0.8, seed: 5);
let param = MLTextClassifier.ModelParameters(validationData: testData, algorithm: MLTextClassifier.ModelAlgorithmType.maxEnt(revision: 1), language: NLLanguage.simplifiedChinese)
let commentClassifier = try MLTextClassifier(trainingData: data, textColumn: "content", labelColumn: "subject", parameters: param)
let evalMetrics = commentClassifier.evaluation(on: testData)
let evalAcc = 1 - evalMetrics.classificationError
print(evalAcc)

let metadata = MLModelMetadata(author: "Jiao", shortDescription: "comment classify", license: "MIT", version: "1.0", additional: nil)
try commentClassifier.write(to: URL(fileURLWithPath: "/Users/Jiao/Desktop/SecurityKeeper/CommentClassify/mlmodel/classifier.mlmodel"), metadata: metadata)

這里原始數(shù)據(jù)的中文中有很多格式是CreateML無(wú)法處理的,如果不清洗的話會(huì)卡在文本映射向量階段,而且內(nèi)存會(huì)一直上漲,有其他帖子說(shuō)中文訓(xùn)練很耗內(nèi)存可能就是這個(gè)原因。最后我將數(shù)據(jù)中部分格式清洗過后就能正常訓(xùn)練,9000多條評(píng)論訓(xùn)練速度也就幾十秒還是可以接受。

模型使用


有了模型后使用就很簡(jiǎn)單了,跟英文語(yǔ)料生成模型使用一樣,導(dǎo)入mlmodel后,xcode會(huì)自動(dòng)生成類和接口函數(shù)。

代碼如下:

//
//  MainTableViewController.m
//  CarComment
//
//  Created by Jiao Liu on 6/20/19.
//  Copyright ? 2019 ChangHong. All rights reserved.
//

#import "MainTableViewController.h"
#import "classifier.h"

@interface MainTableViewController () {
    NSMutableArray *data;
    classifier *model;
}

@end

@implementation MainTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    data = [NSMutableArray arrayWithObjects:@"這玩意都是給有錢任性又不懂車的土豪用的,這價(jià)格換一次我妹夫EP020可以換三鍋了",
            @"聽過,價(jià)格太貴,但一直念念不忘",
            @"說(shuō)實(shí)話,基本上用不上車上導(dǎo)航,用手機(jī)更方便!音響效果不用糾結(jié),畢竟不是想成為移動(dòng)音樂廳。",
            @"換4條靜音輪胎才是正道",
            @"2.0 平均油耗10個(gè) 不到四千公里",
            @"同樣的顏色 你們覺得是16款好看還是19款好看",
            @"女孩子打算買國(guó)六1.5t中配,12萬(wàn)多,首付20%不到3萬(wàn),上路5萬(wàn)左右,分4年,一月還2500左右。貴嗎?",
            @"我想問一下 16寸輪轂要比17寸輪轂小,那車子底盤離地面的距離是不是16寸的比17寸的還要矮上很多???",
            @"這車沒有自動(dòng)落鎖嗎",
            @"想要?jiǎng)恿?qiáng)提速快就菲斯塔 情懷就思域 我們開本田125長(zhǎng)大的就是喜歡買本田",
            nil];
    model = [[classifier alloc] init];
    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:@"Cell" forIndexPath:indexPath];
    
    NSString *comment = [data objectAtIndex:indexPath.row];
    cell.textLabel.text = comment;
    cell.textLabel.numberOfLines = 0;
    cell.detailTextLabel.text = [[model predictionFromText:comment error:nil] label];
    
    return cell;
}

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

@end

運(yùn)行效果


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

demo.gif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 中文自然語(yǔ)言處理開放平臺(tái) 由中國(guó)科學(xué)院計(jì)算技術(shù)研究所·數(shù)字化室&軟件室創(chuàng)立一個(gè)研究自然語(yǔ)言處理的一個(gè)平臺(tái),里面包含...
    Paddle閱讀 9,626評(píng)論 0 6
  • 要查看原文,請(qǐng)參看:原文地址 簡(jiǎn)介 自然語(yǔ)言處理是當(dāng)今十分熱門的數(shù)據(jù)科學(xué)研究項(xiàng)目。情感分析則是自然語(yǔ)言處理中一個(gè)很...
    凌冰_lonny閱讀 14,169評(píng)論 0 55
  • 1 文本分類 文本分類是自然語(yǔ)言處理領(lǐng)域最活躍的研究方向之一,目前文本分類在工業(yè)界的應(yīng)用場(chǎng)景非常普遍,從新聞的分類...
    高永峰_GYF閱讀 28,672評(píng)論 4 21
  • 今天我們繼續(xù)分享諸葛越的精品課《如何培養(yǎng)面對(duì)未來(lái)的孩子》 是第四節(jié)課《用工作方法培養(yǎng)孩子》,那我們看看精英媽媽是如...
    白天的前奏閱讀 223評(píng)論 2 0
  • 60是一個(gè)神奇的數(shù)字,我把它稱為“輪回之?dāng)?shù)”。 秒針走了六十下,是一個(gè)輪回,進(jìn)入了幾世前的分針歷程;分針走了六十下...
    夏念念閱讀 171評(píng)論 0 1

友情鏈接更多精彩內(nèi)容