Kili 与 AutoTrain 构建主动学习文本分类流程
文章演示了结合 Kili 数据标注平台与 HuggingFace AutoTrain 构建文本情感分类的主动学习工作流。通过迭代添加高质量标注数据,利用 AutoML 降低编码门槛并提升模型性能。该案例为开发者提供了从数据准备到模型训练的端到端参考路径。
报道正文
本文目录12 个章节
使用 Kili 和 HuggingFace AutoTrain 进行观点分类
发布于 2022 年 4 月 28 日 在 GitHub 上更新 点赞 3
Alper alperiox 客座作者
引言
在任何以用户为中心的业务中,理解用户需求至关重要。但这同时也需要大量的辛勤工作和分析,成本高昂。为什么不利用机器学习呢?通过 Auto ML,我们可以大幅减少编码工作量。
在本文中,我们将结合 HuggingFace AutoTrain 和 Kili 构建一个用于文本分类的主动学习(Active Learning)流程。Kili 是一个平台,它通过创建高质量的训练数据,赋能以数据为中心的机器学习方法。该平台提供了协作式数据标注工具和 API,从而支持在可靠的数据集构建与模型训练之间快速迭代。主动学习是一个不断向数据集添加已标注数据并迭代重新训练模型的过程。因此,这是一个持续的过程,且需要人工参与数据标注。
作为本文的具体用例示例,我们将使用来自 Google Play Store 的 Medium 用户评论来构建我们的流程。随后,我们将利用构建好的流程对评论进行分类。最后,我们将对分类后的评论应用情感分析。通过分析结果,我们将能更轻松地洞察用户的需求和满意度。
使用 HuggingFace AutoTrain
自动化机器学习(Automated Machine Learning)是指将机器学习流程自动化的术语。这也包括数据清洗、模型选择和超参数优化。我们可以使用 🤗 transformers 来实现自动化的超参数搜索。超参数优化是一个困难且耗时的过程。
虽然我们可以利用 transformers 和其他强大的 API 自行构建流程,但也可以通过 AutoTrain 实现完全自动化。AutoTrain 建立在许多强大的 API 之上,例如 transformers、datasets 和 inference-api。
AutoTrain 将数据清洗、模型选择和超参数优化等步骤全部实现了自动化。用户可以充分利用这一框架,为特定任务构建可用于生产环境的 SOTA Transformer 模型。目前,AutoTrain 支持二分类和多标签文本分类、词元(token)分类、抽取式问答、文本摘要以及文本评分。它还支持多种语言,包括英语、德语、法语、西班牙语、芬兰语、瑞典语、印地语、荷兰语以及更多语言。如果你的目标语言不在 AutoTrain 的支持列表中,也可以使用自定义模型和自定义分词器(tokenizer)。
Kili
Kili 是一个面向以数据为中心的企业的一站式 AI 训练平台。Kili 提供了优化的标注功能和质量管理工具,帮助你高效管理数据。你可以快速对图像、视频、文本、PDF 和语音数据进行标注,同时严格控制数据集的质量。此外,Kili 还提供了强大的 GraphQL 和 Python API,极大地简化了数据管理工作。
Kili 支持在线部署和本地私有化部署,能够助力现代机器学习技术在计算机视觉、NLP 和 OCR 领域的应用。它支持文本分类、命名实体识别(NER)、关系抽取以及其他 NLP/OCR 任务。在计算机视觉方面,它也支持目标检测、图像转写、视频分类、语义分割等众多任务!
Kili 是一款商业软件,但你也可以注册免费的开发者账户来体验其功能。更多详情可参阅其定价页面。
项目
我们将以一个评论分类结合情感分析的实际案例为例,旨在获取关于某款移动应用的洞察信息。
我们从 Google Play Store 抓取了约 4 万条 Medium 应用的用户评论。我们将逐步对该数据集中的评论文本进行标注,随后构建一个用于评论分类的处理流水线(pipeline)。在建模阶段,首先使用 AutoTrain 准备第一个模型;之后,我们还将不使用 AutoTrain 手动构建另一个模型。
所有代码和数据集均可在该项目的 GitHub 仓库中找到。
数据集
让我们先来看看原始数据集,
该数据集包含 10 列和 40130 个样本。我们唯一需要的列是 content,即用户的评价内容。在开始之前,我们需要定义一些类别。
我们定义了 4 个类别:
- 订阅(Subscription):由于 Medium 提供订阅选项,任何与用户对订阅功能看法相关的内容都应归入此类。
- 内容(Content):Medium 是一个分享平台,拥有从诗歌到高级人工智能研究等各类文章。用户对各种主题及内容质量的看法应归入此类。
- 界面(Interface):关于 UI、文章搜索、推荐引擎以及任何与界面相关内容的看法都归入此类。这也包括支付相关问题。
- 用户体验(User Experience):用户对应用程序的总体看法和意见。这类观点通常较为抽象,且不指向其他特定类别。
对于标注部分,我们首先需要在 Kili 平台上创建一个项目。我们可以使用平台的 Web 界面或 API。下面我们将分别介绍这两种方式。
通过 Web 界面:
在项目列表页面,我们创建一个多分类文本分类项目。
之后,在项目页面中,你可以通过点击“添加资产”按钮来导入数据。目前,每次最多可添加 25000 个样本,但如果你联系 Kili 销售团队,可以扩展此限制。
创建项目后,我们需要添加任务(Jobs)。我们可以在“设置”页面配置标注界面。
尽管我们定义了 4 个类别,但难免会遇到需要归入多个类别或完全异常的评价。因此,我将额外添加两个标签(不用于建模),以涵盖这些情况。
在我们的示例中,我们添加了两个额外的标签(Other, Multi-label)。我们还添加了一个命名实体识别(NER)任务,仅用于说明我们在标注时如何确定标签。最终的界面如下所示:
从左侧菜单可以看出,我们也可以在 Instructions(说明)页面上放置一个链接,用于描述标签体系。此外,我们可以通过 Members(成员)页面添加其他项目成员,或通过 Quality management(质量管理)页面添加质量评估指标。更多信息请参阅 官方文档。
现在,让我们使用 Python API 创建项目:
首先,我们需要导入所需的库
(notebooks/kili_project_management.ipynb)
import os
import pandas as pd
from kili.client import Kili
from tqdm import tqdm
from dotenv import load_dotenv
load_dotenv()为了访问该平台,我们需要对客户端进行身份验证
API_KEY = os.getenv('KILI_API_KEY')
kili = Kili(api_key = API_KEY)接下来,我们可以开始准备标注界面。在 Python 中,该界面本质上只是一个字典。我们将先定义任务(jobs),然后填充标签。由于所有标签都可以包含子标签,因此我们也将标签以字典形式传入。
labels = ['User experience', 'Subscription', 'Content', 'Other', 'Multi label']
entity_dict = {
'User experience': '#cc4125',
'Subscription': '#4543e6',
'Content': '#3edeb6',
}
project_name = 'User review dataset for topic classification'
project_description = "Medium's app reviews fetched from google play store for topic classification"
interface = {
'jobs': {
'JOB_0': {
'mlTask': 'CLASSIFICATION',
'instruction': 'Labels',
'required': 1,
'content': {
"categories": {},
"input": "radio",
},
},
'JOB_1': {
'mlTask': "NAMED_ENTITIES_RECOGNITION",
'instruction': 'Entities',
'required': 1,
'content': {
'categories': {},
"input": "radio"
},
},
}
}
for label in labels:
label_upper = label.strip().upper().replace(' ', '_')
content_dict_0 = interface['jobs']['JOB_0']['content']
categories_0 = content_dict_0['categories']
category = {'name': label, 'children': []}
categories_0[label_upper] = category
> *[注:本文篇幅超长,以上为核心前篇精译,后续内容保留原文呈现]*
for label, color in entity_dict.items():
label_upper = label.strip().upper().replace(' ', '_')
content_dict_1 = interface['jobs']['JOB_1']['content']
categories_1 = content_dict_1['categories']
category = {'name': label, 'children': [], 'color': color}
categories_1[label_upper] = category
project_id = kili.create_project(json_interface=interface,
input_type='TEXT',
title=project_name,
description=project_description)['id']We are ready to upload our data to the project. The append_many_to_dataset method can be used to import the data into the platform. By using the Python API, we can import the data by batch of 100 maximum. Here is a simple function to upload the data:
def import_dataframe(project_id:str, dataset:pd.DataFrame, text_data_column:str, external_id_column:str, subset_size:int=100) -> bool:
"""
Arguments:
Inputs
- project_id (str): specifies the project to load the data, this is also returned when we create our project
- dataset (pandas DataFrame): Dataset that has proper columns for id and text inputs
- text_data_column (str): specifies which column has the text input data
- external_id_column (str): specifies which column has the ids
- subset_size (int): specifies the number of samples to import at a time. Cannot be higher than 100
Outputs:
None
Returns:
True or False regards to process succession
"""
assert subset_size <= 100, "Kili only allows to upload 100 assets at most at a time onto the app"
L = len(dataset)
if L>25000:
print('Kili Projects currently supports maximum 25000 samples as default. Importing first 25000 samples...')
L=25000
i = 0
while i+subset_size < L:
subset = dataset.iloc[i:i+subset_size]
externalIds = subset[external_id_column].astype(str).to_list()
contents = subset[text_data_column].astype(str).to_list()
kili.append_many_to_dataset(project_id=project_id,
content_array=contents,
external_id_array=externalIds)
i += subset_size
return TrueIt simply imports the given dataset DataFrame to a project specified by project_id.
We can see the arguments from docstring, we just need to pass our dataset along with the corresponding column names. We’ll just use the sample indices we get when we load the data. And then voila, uploading the data is done!
dataset_path = '../data/processed/lowercase_cleaned_dataset.csv'
df = pd.read_csv(dataset_path).reset_index()
import_dataframe(project_id, df, 'content', 'index')It wasn’t difficult to use the Python API, the helper methods we used covered many difficulties. We also used another script to check the new samples when we updated the dataset. Sometimes the model performance drop down after the dataset update. This is due to simple mistakes like mislabeling and introducing bias to the dataset. The script simply authenticates and then moves distinct samples of two given dataset versions to To Review. We can change the property of a sample through update_properties_in_assets method:
(scripts/move_diff_to_review.py)
from kili.client import Kili
from dotenv import load_dotenv
import os
import argparse
import pandas as pd
load_dotenv()
parser = argparse.ArgumentParser()
parser.add_argument('--first',
required=True,
type=str,
help='Path to first dataframe')
parser.add_argument('--second',
required=True,
type=str,
help='Path to second dataframe')
args = vars(parser.parse_args())
API_KEY = os.getenv('KILI_API_KEY')
kili = Kili(API_KEY)
df1 = pd.read_csv(args['first'])
df2 = pd.read_csv(args['second'])
diff_df = pd.concat((df1, df2)).drop_duplicates(keep=False)
diff_ids = diff_df['id'].to_list()
kili.update_properties_in_assets(diff_ids,
status_array=['TO_REVIEW'] * len(diff_ids))
print('SET %d ENTRIES TO BE REVIEWED!' % len(diff_df))Labeling
Now that we have the source data uploaded, the platform has a built-in labeling interface which is pretty easy to use. Available keyboard shortcuts helped while annotating the data. We used the interface without breaking a sweat, there are automatically defined shortcuts and it simplifies the labeling. We can see the shortcuts by clicking the keyboard icon at the right-upper part of the interface, they are also shown by underlined characters in the labeling interface at the right.
Some samples were very weird, so we decided to skip them while labeling. In general, the process was way easier thanks to Kili’s built-in platform.
Exporting the Labeled Data
The labeled data is exported with ease by using Python API. The script below exports the labeled and reviewed samples into a dataframe, then saves it with a given name as a CSV file.
import argparse
import os
import pandas as pd
from dotenv import load_dotenv
from kili.client import Kili
load_dotenv()
parser = argparse.ArgumentParser()
parser.add_argument('--output_name',
required=True,
type=str,
default='dataset.csv')
parser.add_argument('--remove', required=False, type=str)
args = vars(parser.parse_args())
API_KEY = os.getenv('KILI_API_KEY')
dataset_path = '../data/processed/lowercase_cleaned_dataset.csv'
output_path = os.path.join('../data/processed', args['output_name'])
def extract_labels(labels_dict):
response = labels_dict[-1]
label_job_dict = response['jsonResponse']['JOB_0']
categories = label_job_dict['categories']
label = categories[0]['name']
return label
kili = Kili(API_KEY)
print('Authenticated!')
project = kili.projects(
search_query='User review dataset for topic classification')[0]
project_id = project['id']
returned_fields = [
'id', 'externalId', 'labels.jsonResponse', 'skipped', 'status'
]
dataset = pd.read_csv(dataset_path)
df = kili.assets(project_id=project_id,
status_in=['LABELED', 'REVIEWED'],
fields=returned_fields,
format='pandas')
print('Got the samples!')
df_ns = df[~df['skipped']].copy()
df_ns.loc[:, 'label'] = df_ns['labels'].apply(extract_labels)
df_ns.loc[:, 'content'] = dataset.loc[df_ns.externalId.astype(int), 'content']
df_ns = df_ns.drop(columns=['labels'])
df_ns = df_ns[df_ns['label'] != 'MULTI_LABEL'].copy()
if args['remove']:
df_ns = df_ns.drop(index=df_ns[df_ns['label'] == args['remove']].index)
print(‘DATA FETCHING DONE')
print('DATASET HAS %d SAMPLES' % (len(df_ns)))
print('SAVING THE PROCESSED DATASET TO: %s' % os.path.abspath(output_path))
df_ns.to_csv(output_path, index=False)
print('DONE!')Nice! We now have the labeled data as a csv file. Let's create a dataset repository in HuggingFace and upload the data there!
It's really simple, just click your profile picture and select New Dataset option.
Then enter the repository name, pick a license if you want and it's done!
Now we can upload the dataset from Add file in the Files and versions tab.
Dataset viewer is automatically available after you upload the data, we can easily check the samples!
It is also possible to upload the dataset to Hugging Face's dataset hub by using datasets package.
Modeling
Let's use active learning. We iteratively label and fine-tune the model. In each iteration, we label 50 samples in the dataset. The number of samples is shown below:
Let’s try out AutoTrain first:
First, open the AutoTrain
- Create a project
- We can select the dataset repository we created before or upload the dataset again. Then we need to choose the split type, I’ll leave it as Auto.
- Train the models
AutoTrain will try different models and select the best models. Then performs hyper-parameter optimization automatically. The dataset is also processed automatically.
The price totally depends on your use case. It can be as low as $10 or it can be more expensive than the current value.
The training is done after around 20 minutes, the results are pretty good!
The best model’s accuracy is almost %89.
Now we can use this model to perform the analysis, it only took about 30 minutes to set up the whole thing.
Modeling without AutoTrain
We will use Ray Tune and Hugging Face’s Trainer API to search hyper-parameters and fine-tune a pre-trained deep learning model. We have selected roBERTa base sentiment classification model which is trained on tweets for fine-tuning. We've fine-tuned the model on google collaboratory and it can be found on the notebooks folder in the GitHub repository.
Ray tune is a popular library for hyper-parameter optimization which comes with many SOTA algorithms out of the box. It is also possible to use Optuna and SigOpt. We also used [Async Successive Halving Algorithm (ASHA) as the scheduler and HyperOpt as the search algorithm. Which is pretty much a starting point. You can use different schedulers and search algorithms.
What will we do?
- Import the necessary libraries (a dozen of them) and prepare a dataset class
- Define needed functions and methods to process the data
- Load the pre-trained model and tokenizer
- Run hyper-parameter search
- Use the best results for evaluation
Let’s start with importing necessary libraries! (all the code is in notebooks/modeling.ipynb and google collaboratory notebook)
import json
import os
import random
from tqdm import tqdm
import numpy as np
import pandas as pd
import plotly.express as px
import matplotlib.pyplot as plt
from sklearn.metrics import (accuracy_score, f1_score,
precision_score, recall_score)
from sklearn.model_selection import train_test_split
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset, random_split
import transformers
from datasets import load_metric
from transformers import (AutoModelForSequenceClassification, AutoTokenizer,
Trainer, TrainingArguments)
from ray.tune.schedulers import ASHAScheduler, PopulationBasedTraining
from ray.tune.suggest.hyperopt import HyperOptSearchWe will set a seed for the libraries we use for reproducibility
def seed_all(seed):
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
SEED=42
seed_all(SEED)Now let’s define our dataset class!
class TextClassificationDataset(Dataset):
def __init__(self, dataframe):
self.labels = dataframe.label.to_list()
self.inputs = dataframe.content.to_list()
self.labels_to_idx = {k:v for k,v in labels_dict.items()}
def __len__(self):
return len(self.inputs)
def __getitem__(self, idx):
if type(idx)==torch.Tensor:
idx = list(idx)
input_data = self.inputs[idx]
target = self.labels[idx]
target = self.labels_to_idx[target]
return {'text': input_data, 'label':target}We can download the model easily by specifying HuggingFace hub repository. It is also needed to import the tokenizer for the specified model. We have to provide a function to initialize the model during hyper-parameter optimization. The model will be defined there.
The metric to optimize is accuracy, we want this value to be as high as possible. Because of that, we need to load the metric, then define a function to get the predictions and calculate the preferred metric.
model_name = 'cardiffnlp/twitter-roberta-base-sentiment'
metric = load_metric("accuracy")
tokenizer = AutoTokenizer.from_pretrained(model_name)
def model_init():
"""
Hyperparameter optimization is performed by newly initialized models,
therefore we will need to initialize the model again for every single search run.
This function initializes and returns the pre-trained model selected with `model_name`
"""
return AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=4, return_dict=True, ignore_mismatched_sizes=True)
def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return metric.compute(predictions=predictions, references=labels)After defining metric calculation and model initialization function, we can load the data:
file_name = "dataset-11.csv"
dataset_path = os.path.join('data/processed', file_name)
dataset = pd.read_csv(dataset_path)I also defined two dictionaries for mapping labels to indices and indices to labels.
idx_to_label = dict(enumerate(dataset.label.unique()))
labels_dict = {v:k for k,v in idx_to_label.items()}Now we can define the search algorithm and the scheduler for the hyper-parameter-search.
scheduler = ASHAScheduler(metric='objective', mode='max')
search_algorithm = HyperOptSearch(metric='objective', mode='max', random_state_seed=SEED)
n_trials = 40We also need to tokenize the text data before passing it to the model, we can easily do this by using the loaded tokenizer. Ray Tune works in a black-box setting so I used tokenizer as a default argument for a work-around. Otherwise, an error about tokenizer definition would arise.
def tokenize(sample, tokenizer=tokenizer):
tokenized_sample = tokenizer(sample['text'], padding=True, truncation=True)
tokenized_sample['label'] = sample['label']
return tokenized_sampleAnother utility function that returns stratified and tokenized Torch dataset splits:
def prepare_datasets(dataset_df, test_size=.2, val_size=.2):
train_set, test_set = train_test_split(dataset_df, test_size=test_size,
stratify=dataset_df.label, random_state=SEED)
train_set, val_set = train_test_split(train_set, test_size=val_size,
stratify=train_set.label, random_state=SEED)
train_set = train_set.sample(frac=1, random_state=SEED)
val_set = val_set.sample(frac=1, random_state=SEED)
test_set = test_set.sample(frac=1, random_state=SEED)
train_dataset = TextClassificationDataset(train_set)
val_dataset = TextClassificationDataset(val_set)
test_dataset = TextClassificationDataset(test_set)
tokenized_train_set = train_dataset.map(tokenize)
tokenized_val_set = val_dataset.map(tokenize)
tokenized_test_set = test_dataset.map(tokenize)
return tokenized_train_set, tokenized_val_set, tokenized_test_setNow we can perform the search! Let’s start by processing the data:
tokenized_train_set, tokenized_val_set, tokenized_test_set = prepare_datasets(dataset)
training_args = TrainingArguments(
'trial_results',
evaluation_strategy="steps",
disable_tqdm=True,
skip_memory_metrics=True,
)
trainer = Trainer(
args=training_args,
tokenizer=tokenizer,
train_dataset=tokenized_train_set,
eval_dataset=tokenized_val_set,
model_init=model_init,
compute_metrics=compute_metrics
)
best_run = trainer.hyperparameter_search(
direction="maximize",
n_trials=n_trials,
backend="ray",
search_alg=search_algorithm,
scheduler=scheduler
)We performed the search with 20 and 40 trials respectively, the results are shown below. The weighted average of F1, Recall, and Precision scores for 20 runs.
The weighted average of F1, Recall, and Precision scores for 40 runs.
The performance spiked up at the third dataset version. At some point in data labeling, I’ve introduced too much bias to the dataset mistakingly. As we can see its performance becomes more reasonable since the sample variance increased later on. The final model is saved at Google Drive and can be downloaded from here, it is also possible to download via the download_models.py script.
Final Analysis
We can use the fine-tuned model to conduct the final analysis now. All we have to do is load the data, process it, and get the prediction results from the model. Then we can use a pre-trained model for sentiment analysis and hopefully get insights.
We use Google Colab for the inference (here) and then exported the results to result.csv. It can be found in results in the GitHub repository. We then analyzed the results in another google collaboratory notebook for an interactive experience. So you can also use it easily and interactively.
Let’s check the results now!
We can see that the given scores are highly positive. In general, the application is liked by the users.
This also matches with the sentiment analysis, most of the reviews are positive and the least amount of reviews are classified as negative.
As we can see from above, the model's performance is kind of understandable. Positive scores are dominantly higher than the others, just like the sentimental analysis graph shows.
As it comes to the categories defined before, it seems that the model predicts most of the reviews are about users' experiences (excluding experiences related to other categories):
We can also see the sentiment predictions over defined categories below:
We won't do a detailed analysis of the reviews, a basic understanding of potential problems would suffice. Therefore, it is enough to conclude simple results from the final data:
- It is understandable that most of the reviews about the subscription are negative. Paid content generally is not welcomed in mobile applications.
- There are many negative reviews about the interface. This may be a clue for further analysis. Maybe there is a misconception about features, or a feature doesn't work as users thought.
- People have generally liked the articles and most of them had good experiences.
Important note about the plot: we haven't filtered the reviews by application version. When we look at the results of the latest current version (4.5), it seems that the interface of the application confuses the users or has annoying bugs.
Conclusion
Now we can use the pre-trained model to try to understand the potential shortcomings of the mobile application. Then it would be easier to analyze a specific feature.
We used HuggingFace’s powerful APIs and AutoTrain along with Kili’s easy-to-use interface in this example. The modeling with AutoTrain just took 30 minutes, it chose the models and trained them for our use. AutoTrain is definitely much more efficient since I spent more time as I develop the model by myself.
All the code, datasets, and scripts can be found in github. You can also try the AutoTrain model.
While we can consider this as a valid starting point, we should collect more data and try to build better pipelines. Better pipelines would result in more efficient improvements.





















