我有一个Twitter个人资料数据的CSV,其中包含:名称,描述,关注者人数,关注人数,机器人(我要预测的类)
仅使用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'>
任何帮助将不胜感激。
答案 0 :(得分:0)
我会反过来做,并将您的功能添加到矢量化中。这是我的玩具示例的意思:
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
上执行文本向量化,并将功能a
和b
添加到向量化。
vectorizer = CountVectorizer()
CountVecTest = vectorizer.fit_transform(df.c)
CountVecTest.toarray()
这将返回:
array([[0, 1, 1, 1],
[1, 0, 1, 1]], dtype=int64)
但是CountVecTest
现在是一个稀疏的稀疏矩阵。因此,您需要做的就是将功能添加到此矩阵中。像这样:
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)
注意:在您提供的代码段中,您将标签信息(“机器人”列)传递给了培训功能,显然您不应该这样做。