【问题标题】:Merge numeric and text features for category classification合并数字和文本特征以进行类别分类
【发布时间】:2015-01-07 11:34:52
【问题描述】:

我正在尝试对产品进行分类,以便根据产品标题和基本价格预测它们的类别。

一个例子(产品名称、价格、类别):

['notebook sony vaio vgn-z770td dockstation', 3000.0, u'MLA54559']

以前我只将产品标题用于预测任务,但我想包括价格以查看准确性是否提高。

我的代码的问题是我无法合并文本/数字特征,我一直在 SO 中阅读一些问题,这是我的代码摘录:

#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,)

【问题讨论】:

标签: python machine-learning scipy scikit-learn


【解决方案1】:

在我看来,这应该像堆叠数组一样简单。如果 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,) 的数组。我可能会遗漏一些东西,因为您使用的是 sparse 数组。尽管如此,原则应该是相同的。根据上面的代码,我不知道你使用的是什么稀疏格式,所以我只选择了一个来测试:

>>> 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]])

【讨论】:

    猜你喜欢
    • 2015-12-13
    • 2019-02-18
    • 2019-06-30
    • 2016-09-02
    • 2017-10-27
    • 2017-05-16
    • 2017-10-05
    • 1970-01-01
    • 2020-01-12
    相关资源
    最近更新 更多