前言
上一篇【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