3

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

  1. 推文的内容 =预处理
  2. 事件类型(例如,与地震相关的推文 = 'earthquake'、typhoon = 'typhoon' 等) = event_type
  3. 发送推文的纬度 = lat
  4. 发送推文的经度 =
  5. 事件标签(例如与地震相关的推文 = 1、台风 = 2 等)= event_id

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

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

到目前为止(错误地)我所做的只是对推文内容(preprocessedevent_id进行过采样。在下面的代码中,我将推文转换为向量(我不想这样做,但据我所知,我必须这样做)和然后过度代表少数类。这只会过度采样向量化的推文(x_words)和 event_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_sampling 中使用SMOTE需要提供真实值(不是字符串)并且只有 2 个值 - 一个“x”和一个“y”。在这种情况下,“x”是我的向量化推文训练集,“y”是我的事件标签。

有没有办法让我简单地将我的数据框拆分为训练集和测试集,然后对少数类的所有 5 列进行过采样,以便输出是包含所有 5 列的更大数据框?然后我可以使用它来预测 event_id 并希望执行相当于 vlookup 的操作,这样我就可以使用其各自的latlong值加入推文。

4

1 回答 1

0

imblearn.over_sampling 中的 SMOTE 可以接受 sparse_vector 作为输入。您可以进行过采样,然后拆分为您的测试/训练集。

如果我正确理解您的问题,以下内容对我有用;

尝试以下方法:

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)

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

于 2019-07-05T12:58:05.397 回答