[英]How to return text data as output after oversampling using SMOTE?
我有一個多 class 文本數據,由於少數標簽,我想SMOTE
。 我已經這樣做了,但是我得到了作為我的 output 的稀疏矩陣。
有沒有辦法在 SMOTE 之后取回文本數據?
這是我的代碼示例:
X_train = df['transcript']
y_train = df['label']
from imblearn.over_sampling import SMOTE
sm = SMOTE(random_state = 2)
X_train_res, y_train_res = sm.fit_sample(X_train, y_train)
SMOTE.fit_sample
在內部使用label_binarize
中的 label_binarize: https://github.com/scikit-learn-contrib/imbalanced-learn/blob/12b2e0d/imblearn/base.py#L87
在應用SMOTE
之前,您應該在y
值上手動使用sklearn.preprocessing.LabelBinarizer
。
from imblearn.over_sampling import SMOTE
from sklearn.preprocessing import LabelBinarizer
sm = SMOTE(random_state = 2)
lb = LabelBinarizer()
y_train_bin = lb.fit_transform(y_train)
X_train_res, y_train_res_bin = sm.fit_sample(X_train, y_train_bin)
然后您可以從擬合的LabelBinarizer.inverse_transform
方法中恢復文本標簽:
y_train_res = lb.inverse_transform(y_train_res_bin)
實際上SMOTE
期望X
只是數字數據。 這不是標簽的問題,標簽可以是字符串。
閱讀此處了解 SMOTE 如何在內部工作。 基本上,它使用所選鄰居的凸組合為少數 class 創建合成數據點。
因此,使用TfidfVectorizer
或CountVectorizer
將您的文本數據(成績單)轉換為數字。 您可以使用這些矢量化器的inverse_transform
方法來取回文本,但問題是您會丟失單詞的順序。
import pandas as pd
df = pd.DataFrame({'transcripts': ['I want to check this',
'how about one more sentence',
'hopefully this works well fr you',
'I want to check this',
'This is the last sentence or transcript'],
'labels': ['good','bad', 'bad', 'good','bad']})
from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer()
X = vec.fit_transform(df['transcripts'])
from imblearn.over_sampling import SMOTE
sm = SMOTE(k_neighbors=1, random_state = 2)
X_train_res, y_train_res = sm.fit_sample(X, df.labels)
vec.inverse_transform(X_train_res)
# [array(['this', 'check', 'to', 'want'], dtype='<U10'),
# array(['sentence', 'more', 'one', 'about', 'how'], dtype='<U10'),
# array(['you', 'fr', 'well', 'works', 'hopefully', 'this'], dtype='<U10'),
# array(['this', 'check', 'to', 'want'], dtype='<U10'),
# array(['transcript', 'or', 'last', 'the', 'is', 'sentence', 'this'],
# dtype='<U10'),
# array(['want', 'to', 'check', 'this'], dtype='<U10')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.