我的数据集中有 3 列:
评论:产品评论
类型:类别或产品类型
成本:产品成本多少
这是一个多类问题,以 Type 作为目标变量。该数据集中有 64 种不同类型的产品。
审查和成本是我的两个特点。
我已将数据分成 4 组,并删除了Type变量:
X = data.drop('type', axis = 1)
y = data.type
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
对于Review,我使用以下方法对其进行矢量化:
vect = CountVectorizer(stop_words = stop)
X_train_dtm = vect.fit_transform(X_train.review)
这就是我卡住的地方!
为了运行模型,我需要在训练集中同时拥有我的两个特征,但是,由于 X_train_dtm 是一个稀疏矩阵,我不确定如何将我的 pandas 系列成本特征连接到该稀疏矩阵。由于Cost的数据已经是数字的,我认为我不需要转换它,这就是为什么我没有使用像“FeatureUnion”这样结合了两个转换特征的东西。
任何帮助,将不胜感激!!
示例数据:
| Review | Cost | Type |
|:-----------------|------------:|:------------:|
| This is a review | 200 | Toy
| This is a review | 100 | Toy
| This is a review | 800 | Electronics
| This is a review | 35 | Home
更新
应用 tarashypka 的解决方案后,我能够将第二个功能添加到 X_train_dtm。但是,尝试在测试集上运行相同时出现错误:
从 scipy.sparse 导入 hstack
vect = CountVectorizer(stop_words = stop)
X_train_dtm = vect.fit_transform(X_train.review)
prices = X_train.prices.values[:,None]
X_train_dtm = hstack((X_train_dtm, prices))
#Works perfectly for the training set above
#But when I run with test set I get the following error
X_test_dtm = vect.transform(X_test)
prices_test = X_test.prices.values[:,None]
X_test_dtm = hstack((X_test_dtm, prices_test))
Traceback (most recent call last):
File "<ipython-input-10-b2861d63b847>", line 8, in <module>
X_test_dtm = hstack((X_test_dtm, points_test))
File "C:\Users\k\Anaconda3\lib\site-packages\scipy\sparse\construct.py", line 464, in hstack
return bmat([blocks], format=format, dtype=dtype)
File "C:\Users\k\Anaconda3\lib\site-packages\scipy\sparse\construct.py", line 581, in bmat
'row dimensions' % i)
ValueError: blocks[0,:] has incompatible row dimensions