SMOTE - 无法将字符串转换为浮点数

4

我觉得下面的代码缺少了些什么。

from sklearn.model_selection import train_test_split
from imblearn.over_sampling import SMOTE


# Split into training and test sets

# Testing Count Vectorizer

X = df[['Spam']]
y = df['Value']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=40)
X_resample, y_resampled = SMOTE().fit_resample(X_train, y_train)


sm =  pd.concat([X_resampled, y_resampled], axis=1)

由于我遇到了以下错误

ValueError: 无法将字符串转换为浮点数: ---> 19 X_resampled, y_resampled = SMOTE().fit_resample(X_train, y_train)

数据示例为

Spam                                             Value
Your microsoft account was compromised             1
Manchester United lost against PSG                 0
I like cooking                                     0

我考虑将训练集和测试集都进行转换以解决导致错误的问题,但我不知道如何同时应用于两者。我在谷歌上尝试了一些示例,但它们并没有解决这个问题。


再次将它们放入数据框的原因是什么?向量化计数是一个稀疏矩阵,如果转换为数组,则可能占用大量内存。 - StupidWolf
@StupidWolf,这是为了质量检查和将其分成训练集、测试集和验证集。我还需要创建特征向量-文档术语矩阵。 - Math
所以,正如下面的答案建议的那样,您需要将向量化计数传递给SMOTE。我认为在此之后将它们放入数据框中是不明智的。您不需要为任何下游操作使用数据框。 - StupidWolf
当我对数据集进行过采样时,我做了类似的事情。因此,我创建了一些函数并使用了一些已经内置的函数,这些函数将原始数据集分割为训练集、测试集和验证集,并以这些作为参数。 - Math
class_1 = tr_set[tr_set.Label == 1] class_0 = tr_set[tr_set.Label == 0]oversample = resample(class_1, replace=True, n_samples=len(class_0), random_state=1) over_train = pd.concat([class_0, oversample])在使用SMOTE后,我该如何做类似的事情?我为oversample所做的事情是否没有意义?我正在阅读很多关于这个主题的论文、网站...每个人似乎都不知道如何使用重新采样。我正在学习,所以我正在遵循其他人的建议。 - Math
3个回答

8

在应用SMOTE之前,将文本数据转换为数字格式,例如以下方式。

from sklearn.feature_extraction.text import CountVectorizer

vectorizer = CountVectorizer()
vectorizer.fit(X_train.values.ravel())
X_train=vectorizer.transform(X_train.values.ravel())
X_test=vectorizer.transform(X_test.values.ravel())
X_train=X_train.toarray()
X_test=X_test.toarray()

然后添加您的SMOTE代码

x_train = pd.DataFrame(X_train)
X_resample, y_resampled = SMOTE().fit_resample(X_train, y_train)

X_train的形状是什么? - Ravi
我认为计数向量化器没有按预期工作。你在df中有多少数据点? - Ravi
感谢Ravi。然而,由于toarray()的原因,当我尝试将x_resampled和y_resampled连接成一个唯一的数据集时,似乎这种方法不起作用:TypeError: cannot concatenate object of type '<class 'numpy.ndarray'>'; only Series and DataFrame objs are valid。 - Math
在调用smote之前添加以下代码行: "x_train = pd.DataFrame(X_train)" - Ravi
但是在SMOTE之前,这一行仍然应该使用未采样的数据,不是吗?因为我需要将我在SMOTE之后使用的内容视为训练集。 - Math
显示剩余2条评论

1

在将字符串数据输入SMOTE之前进行标记化是一种选择。您可以使用任何分词器,下面是torch的实现示例:

dataloader = torch.utils.data.DataLoader(dataset, batch_size=64)

X, y = [], []

for batch in dataloader:
    input_ids = batch['input_ids']
    labels = batch['labels']

    X.append(input_ids)
    y.append(labels)

X_tensor = torch.cat(X, dim=0)
y_tensor = torch.cat(y, dim=0)

X = X_tensor.numpy()
y = y_tensor.numpy()

smote = SMOTE(random_state=42, sampling_strategy=0.6)
X_resampled, y_resampled = smote.fit_resample(X, y)

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接