iOS使用CoreML分类汽车评论

前言


上一篇【iOS使用CoreML来分类垃圾信息】文章中用的是英文语料,而苹果的文本分类其实是支持多语言的,而中文的训练在国内更具实用价值,所以本文介绍如何针对中文语料进行训练。

使用的数据来自汽车论坛的评论,有9000+条数据,已经进行了标记。

2641798-2cedcc8f41bcbc39.png

构建模型


使用的原始数据格式如下,包含评论和已经标记的主题、ID、观点等,我们模型只使用了评论和主题:

2641798-9286063ad9d2f130.png
train.csv

模型训练:

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)

这里原始数据的中文中有很多格式是CreateML无法处理的,如果不清洗的话会卡在文本映射向量阶段,而且内存会一直上涨,有其他帖子说中文训练很耗内存可能就是这个原因。最后我将数据中部分格式清洗过后就能正常训练,9000多条评论训练速度也就几十秒还是可以接受。

模型使用


有了模型后使用就很简单了,跟英文语料生成模型使用一样,导入mlmodel后,xcode会自动生成类和接口函数。

代码如下:

//
//  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:@"这玩意都是给有钱任性又不懂车的土豪用的,这价格换一次我妹夫EP020可以换三锅了",
            @"听过,价格太贵,但一直念念不忘",
            @"说实话,基本上用不上车上导航,用手机更方便!音响效果不用纠结,毕竟不是想成为移动音乐厅。",
            @"换4条静音轮胎才是正道",
            @"2.0 平均油耗10个 不到四千公里",
            @"同样的颜色 你们觉得是16款好看还是19款好看",
            @"女孩子打算买国六1.5t中配,12万多,首付20%不到3万,上路5万左右,分4年,一月还2500左右。贵吗?",
            @"我想问一下 16寸轮毂要比17寸轮毂小,那车子底盘离地面的距离是不是16寸的比17寸的还要矮上很多???",
            @"这车没有自动落锁吗",
            @"想要动力强提速快就菲斯塔 情怀就思域 我们开本田125长大的就是喜欢买本田",
            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

运行效果


源码地址:https://github.com/JiaoLiu/CommentClassify 🏎️

2641798-b8d4db0babce9bb3.gif
demo.gif
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值