我试图对产品进行分类,以便根据产品名称和基本价格来预测产品的类别。
一个例子(产品名称、价格、类别):
['notebook sony vaio vgn-z770td dockstation', 3000.0, u'MLA54559']以前,我只使用产品标题进行预测任务,但我想包括价格,看看是否提高了准确性。
我的代码的问题是我不能合并文本/数字特性,我在这里阅读了一些问题,这是我的代码摘录:
#extracting features from text
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform([e[0] for e in training_set])
tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
#extracting numerical features
X_train_price = np.array([e[1] for e in training_set])
X = sparse.hstack([X_train_tfidf, X_train_price]) #this is where the problem begins
clf = svm.LinearSVC().fit(X, [e[2] for e in training_set])我试图将数据类型与sparse.hstack合并,但我得到了以下错误:
ValueError: blocks[0,:] has incompatible row dimensions我想问题在于X_train_price(价格列表),但我不知道如何为稀疏函数设置格式,以便成功地工作。
这两个数组的形状如下:
>>> X_train_tfidf.shape
(65845, 23136)
>>>X_train_price.shape
(65845,)发布于 2014-11-11 03:05:13
在我看来,这应该像堆叠数组一样简单。如果scikit-learn遵循我熟悉的惯例,那么X_train_tfidf中的每一行都是一个训练数据点,总共有65845分。所以你只需要做一个hstack --就像你说的那样。
但是,您需要确保维度是兼容的!在vanilla numpy中,否则会出现此错误:
>>> a = numpy.arange(15).reshape(5, 3)
>>> b = numpy.arange(15, 20)
>>> numpy.hstack((a, b))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/
Extras/lib/python/numpy/core/shape_base.py", line 270, in hstack
return _nx.concatenate(map(atleast_1d,tup),1)
ValueError: arrays must have same number of dimensions重塑b以具有正确的维度--注意到形状(5,)的一维数组与形状(5, 1)的二维数组完全不同。
>>> b
array([15, 16, 17, 18, 19])
>>> b.reshape(5, 1)
array([[15],
[16],
[17],
[18],
[19]])
>>> numpy.hstack((a, b.reshape(5, 1)))
array([[ 0, 1, 2, 15],
[ 3, 4, 5, 16],
[ 6, 7, 8, 17],
[ 9, 10, 11, 18],
[12, 13, 14, 19]])因此,在您的例子中,您需要一个形状(65845, 1)的数组,而不是(65845,)。我可能遗漏了什么,因为您使用的是稀疏数组。然而,原则应该是相同的。我不知道您根据上面的代码使用的是什么稀疏格式,所以我只选择了一种来测试:
>>> a = scipy.sparse.lil_matrix(numpy.arange(15).reshape(5, 3))
>>> scipy.sparse.hstack((a, b.reshape(5, 1))).toarray()
array([[ 0, 1, 2, 15],
[ 3, 4, 5, 16],
[ 6, 7, 8, 17],
[ 9, 10, 11, 18],
[12, 13, 14, 19]])https://stackoverflow.com/questions/26856095
复制相似问题