多类分类:中多个列的SMOTE过采样

2024-04-26 00:05:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个不平衡的数据集,它包含在一个名为city\u country的数据框中,它由5列组成:

  1. tweet的内容=预处理
  2. 事件类型(如tweet与地震相关=“地震”、台风=“台风”等)=事件类型
  3. 发送tweet的纬度=lat
  4. 发送tweet的经度=long
  5. 事件标签(例如,tweet与地震相关=1,台风=2,等等)=事件编号

在名为city\u country的数据帧中,类(event_id)是不平衡的。在测试不同文本分类器的预测能力之前,为了从tweet的内容(预处理)预测事件,我想对少数类进行过采样。在

重要的是,当我复制属于少数类的条目时,我要复制所有5列。在

到目前为止,我所做的(错误的)只是对tweet内容(预处理的事件进行了过采样。在下面的代码中,我将tweets转换成向量(我不想这么做,但据我所知,我必须这样做),然后过度代表少数族裔类。这只会过采样矢量化tweet(x_words)和事件_id(y)。在

tfidf_words = TfidfVectorizer(sublinear_tf=True, min_df=0, norm='l2', encoding='latin-1', ngram_range=(1,1), stop_words='english')

x_words = tfidf_words.fit_transform(city_country.preprocessed).toarray()

# new dataframe 'label' that contains the event_id for each preprocessed tweet
y = city_country.event_id

x_train_words, x_test_words, y_train, y_test = train_test_split(x_words, y, test_size = 0.25, random_state = 0)

# Use SMOTE to oversample the minority classes
from imblearn.over_sampling import SMOTE
sm = SMOTE(random_state=12)
x_train_words_sm, y_train_words_sm = sm.fit_sample(x_train_words, y_train)

# Count the number of occurences in the y_train sets to ensure that the oversampling worked 
from collections import Counter
class_check_woSMOTE = Counter(y_train)
class_check_words = Counter(y_train_words_sm)

据我所知,在imblearn.over_采样要求您输入实值(而不是字符串),并且只能输入2个值-“x”和“y”。在本例中,'x'是我的矢量化训练tweets集,'y'是我的事件标签。在

有没有一种方法可以让我简单地将数据帧分成训练集和测试集,然后对少数类的所有5列进行过采样,这样输出的是一个包含所有5列的更大的数据帧吗?然后我就可以用它来预测事件,并希望执行类似于vlookup的操作,这样我就可以用tweet各自的latlong值加入tweet。在


Tags: the数据testeventidcity内容事件
1条回答
网友
1楼 · 发布于 2024-04-26 00:05:57

突然袭击imblearn.over_采样稀疏向量可以接受为U。你可以进行过采样,然后分成你的测试/训练集。在

如果我正确地理解了你的问题,以下几点对我很有用

请尝试以下操作:

from sklearn.feature_extraction.text import Tfidfvectorizer
from imblearn.over_sampling import SMOTE

strings = city_country.preprocessed

def create_vec(strings):

    tf = TfidfVectorizer(analyzer = 'char_wb',ngram_range=(2,3))
    tf.fit(strings)
    X = tf.transform(strings)

    return X

vecs = create_vec(strings)

y = city_country.event_id

sm = SMOTE(random_state=42)
X_res, y_res = sm.fit_resample(X, y)

然后可以根据输出进行拆分

相关问题 更多 >