CountVectorizer值在分类器中单独工作,添加其他功能时无法工作

2024-10-03 21:25:11 发布

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

我有一个twitter个人资料的CSV,包含:姓名,描述,追随者数量,追随者数量,bot(我想预测的类)

仅使用CountVectorizer值(xtrain)和Bot(ytrain)时,我成功地执行了一个分类模型。但我无法将此功能添加到我的其他功能集。你知道吗

vectorizer = CountVectorizer()
CountVecTest = vectorizer.fit_transform(training_data.description.values.astype('U'))
CountVecTest = CountVecTest.toarray()
arr = sparse.coo_matrix(CountVecTest)
training_data["NewCol"] = arr.toarray().tolist()

rf = RandomForestClassifier(criterion='entropy', min_samples_leaf=10, min_samples_split=20)
rf = rf.fit(training_data[["followers_count","friends_count","NewCol","bot"]], training_data.bot)

错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-54-7d67a6586592> in <module>()
      1 rf = RandomForestClassifier(criterion='entropy', min_samples_leaf=10, min_samples_split=20)
----> 2 rf = rf.fit(training_data[["followers_count","friends_count","NewCol","bot"]], training_data.bot)

D:\0_MyFiles\0_Libraries\Documents\Anaconda3\lib\site-packages\sklearn\ensemble\forest.py in fit(self, X, y, sample_weight)
    245         """
    246         # Validate or convert input data
--> 247         X = check_array(X, accept_sparse="csc", dtype=DTYPE)
    248         y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None)
    249         if sample_weight is not None:

D:\0_MyFiles\0_Libraries\Documents\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    431                                       force_all_finite)
    432     else:
--> 433         array = np.array(array, dtype=dtype, order=order, copy=copy)
    434 
    435         if ensure_2d:

ValueError: setting an array element with a sequence.

我做了一些调试:

print(type(training_data.NewCol))
print(type(training_data.NewCol[0]))
>>> <class 'pandas.core.series.Series'>
>>> <class 'numpy.ndarray'>

任何帮助都将不胜感激。你知道吗


Tags: indatabotcounttrainingminarrayfit
1条回答
网友
1楼 · 发布于 2024-10-03 21:25:11

我会反过来做,把你的特征添加到你的矢量化中。以下是我用一个玩具例子的意思:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
from scipy.sparse import hstack, csr_matrix

假设现在您在一个名为df的数据帧中拥有特性,在y_train中拥有标签:

df = pd.DataFrame({"a":[1,2],"b":[2,3],"c":['we love cars', 'we love cakes']})
y_train = np.array([0,1])

您希望对列c执行文本向量化,并将特性ab添加到向量化中。你知道吗

vectorizer = CountVectorizer()
CountVecTest = vectorizer.fit_transform(df.c)

CountVecTest.toarray()

这将返回:

array([[0, 1, 1, 1],
       [1, 0, 1, 1]], dtype=int64)

但是CountVecTest现在是一个scipy稀疏矩阵。所以你需要做的就是把你的特征添加到这个矩阵中。像这样:

X_train = hstack([CountVecTest, csr_matrix(df[['a','b']])])

X_train.toarray()

这将如预期的那样返回:

array([[0, 1, 1, 1, 1, 2],
       [1, 0, 1, 1, 2, 3]], dtype=int64)

然后你可以训练你的随机森林:

rf = RandomForestClassifier(criterion='entropy', min_samples_leaf=10, min_samples_split=20)
rf.fit(X_train, y_train)

注意:在您提供的代码片段中,您将label info(“bot”列)传递给了training特性,显然您不应该这样做。你知道吗

相关问题 更多 >