Vin*_*eet 5 python nlp machine-learning resampling text-classification
我正在做文本分类,并且我有非常不平衡的数据,例如
Category | Total Records
Cate1 | 950
Cate2 | 40
Cate3 | 10
Run Code Online (Sandbox Code Playgroud)
现在我想对 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)
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为它无法生成示例合成文本,现在当我将其转换为矢量时
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)
Run Code Online (Sandbox Code Playgroud)
当我想在分类后预测真实类别时,我不确定这是否是正确的方法以及如何将向量转换为真实文本
我知道这个问题已经有两年多了,我希望你能找到解决方案。如果您仍然感兴趣,可以使用 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
Run Code Online (Sandbox Code Playgroud)
像您在代码中所做的那样导入 SMOTE
from imblearn.over_sampling import SMOTE
Run Code Online (Sandbox Code Playgroud)
按照您在代码中所做的那样进行训练测试拆分
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
)
Run Code Online (Sandbox Code Playgroud)
创建一个以 SMOTE 作为组件之一的管道
textclassifier =Pipeline([
('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('smote', SMOTE(random_state=12)),
('mnb', MultinomialNB(alpha =0.1))
])
Run Code Online (Sandbox Code Playgroud)
根据训练数据训练分类器
textclassifier.fit(X_train, y_train)
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用该分类器执行任何任务,包括评估分类器本身、预测新的观察结果等。
例如预测一个新样本
textclassifier.predict(['sample text'])
Run Code Online (Sandbox Code Playgroud)
将返回一个预测类别。
为了获得更准确的模型,请尝试将词向量作为特征,或者更方便地在管道上执行超参数优化。