我正在尝试使用 Pandas 和 scikit-learn 在 Python 中执行分类。我的数据集包含文本变量、数值变量和分类变量的混合。
假设我的数据集如下所示:
Project Cost Project Category Project Description Project Outcome
12392.2 ABC This is a description Fully Funded
493992.4 DEF Stack Overflow rocks Expired
我需要预测变量 Project Outcome
。这是我所做的(假设 df
包含我的数据集):
我将类别
Project Category
和Project Outcome
转换为数值df['Project Category'] = df['Project Category'].factorize()[0] df['Project Outcome'] = df['Project Outcome'].factorize()[0]
数据集现在看起来像这样:
Project Cost Project Category Project Description Project Outcome
12392.2 0 This is a description 0
493992.4 1 Stack Overflow rocks 1
然后我使用
处理文本列TF-IDF
tfidf_vectorizer = TfidfVectorizer() df['Project Description'] = tfidf_vectorizer.fit_transform(df['Project Description'])
数据集现在看起来像这样:
Project Cost Project Category Project Description Project Outcome
12392.2 0 (0, 249)\t0.17070240732941433\n (0, 304)\t0.. 0
493992.4 1 (0, 249)\t0.17070240732941433\n (0, 304)\t0.. 1
既然所有变量现在都是数值,我想我可以开始训练我的模型了
X = df.drop(columns=['Project Outcome'], axis=1) y = df['Project Outcome'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) model = MultinomialNB() model.fit(X_train, y_train)
但我在尝试执行 model.fit
时收到错误 ValueError: setting an array element with a sequence.
。当我打印 X_train
时,我注意到 Project Description
由于某种原因被替换为 NaN
。
有什么帮助吗?使用具有各种数据类型的变量进行分类有什么好的方法吗?谢谢。
最佳答案
替换这个
df['Project Description'] = tfidf_vectorizer.fit_transform(df['Project Description'])
与
df['Project Description'] = tfidf_vectorizer.fit_transform(df['Project Description']).toarray()
您还可以使用:tfidf_vectorizer.fit_transform(df['项目描述']).todense()
此外,您不应该简单地将类别转换为数字。例如,如果将 A、B 和 C 转换为 0,1 和 2。它们被视为 2>1>0,因此 C>B>A 通常不是这种情况,因为 A 只是不同于 B 和 C。对于您可以使用 One-Hot-Encoding(在 Pandas 中,您可以为此使用“get_dummies”)。您可以将以下代码用于所有分类特征。
#df has all not categorical features
featurelist_categorical = ['Project Category', 'Feature A',
'Feature B']
for i,j in zip(featurelist_categorical, ['Project Category','A','B']):
df = pd.concat([df, pd.get_dummies(data[i],prefix=j)], axis=1)
特征前缀不是必需的,但在多个分类特征的情况下会特别帮助你。
此外,如果您出于某种原因不想将特征拆分为数字,您可以使用 H2O.ai。使用 H2O,您可以直接将分类变量作为文本输入到模型中。
关于具有混合数据类型(文本、数字、分类)的 Python scikit-learn 分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53023341/