[英]SMOTE, Oversampling on text classification in Python
我正在做一个文本分类,我有非常不平衡的数据,比如
Category | Total Records
Cate1 | 950
Cate2 | 40
Cate3 | 10
现在我想对 Cate2 和 Cate3 进行过采样,所以它至少有 400-500 条记录,我更喜欢使用 SMOTE 而不是随机采样,代码
from sklearn.model_selection import train_test_split
from imblearn.over_sampling import SMOTE
X_train, X_test, y_train, y_test = train_test_split(fewRecords['text'],
fewRecords['category'])
sm = SMOTE(random_state=12, ratio = 1.0)
x_train_res, y_train_res = sm.fit_sample(X_train, y_train)
它不起作用,因为它无法生成示例合成文本,现在当我将其转换为向量时
count_vect = CountVectorizer(analyzer='word', token_pattern=r'\w{1,}')
count_vect.fit(fewRecords['category'])
# transform the training and validation data using count vectorizer object
xtrain_count = count_vect.transform(X_train)
ytrain_train = count_vect.transform(y_train)
当我想在分类后预测真实类别时,我不确定这是否是正确的方法以及如何将向量转换为真实文本
我知道这个问题已经超过 2 年了,我希望你找到了解决办法。 如果您仍然感兴趣,这可以通过 imblearn 管道轻松完成。
我将假设您将使用与 sklearn 兼容的估计器来执行分类。 假设多项式朴素贝叶斯。
请注意我如何从 imblearn 而不是 sklearn 导入 Pipeline
from imblearn.pipeline import Pipeline, make_pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
像您在代码中所做的那样导入 SMOTE
from imblearn.over_sampling import SMOTE
像您在代码中所做的那样进行训练测试拆分
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(fewRecords['text'],
fewRecords['category'],stratify=fewRecords['category'], random_state=0
)
使用 SMOTE 作为组件之一创建管道
textclassifier =Pipeline([
('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('smote', SMOTE(random_state=12)),
('mnb', MultinomialNB(alpha =0.1))
])
在训练数据上训练分类器
textclassifier.fit(X_train, y_train)
然后您可以将此分类器用于任何任务,包括评估分类器本身、预测新观察等。
例如预测一个新样本
textclassifier.predict(['sample text'])
将返回一个预测类别。
为了获得更准确的模型,尝试将词向量作为特征或更方便,在管道上执行超参数优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.