Python 如何正确使用numpy hstack

Python 如何正确使用numpy hstack,python,numpy,scikit-learn,tfidfvectorizer,Python,Numpy,Scikit Learn,Tfidfvectorizer,我有一份文件清单。 我使用TfidfVectorizer获取dt\u矩阵,这是一个稀疏矩阵 dt_矩阵是这样的: (0, 642) 0.14738966496831196 (0, 1577) 0.20377626427753473 (0, 1166) 0.2947793299366239 : : (1046, 166) 0.500700591796996 [141 56 79 ... 26 26 26] 现在,我想在这个矩阵中添加文档的长度作为特征。 所以

我有一份文件清单。 我使用
TfidfVectorizer
获取
dt\u矩阵
,这是一个稀疏矩阵

dt_矩阵
是这样的:

  (0, 642)  0.14738966496831196
  (0, 1577) 0.20377626427753473
  (0, 1166) 0.2947793299366239
  : :
 (1046, 166)    0.500700591796996
[141  56  79 ...  26  26  26]
现在,我想在这个矩阵中添加文档的长度作为特征。 所以我有
长度
数组。第i个位置是第i个文档的长度

length=get_comments_length()
length
是一个numpy数组,如下所示:

  (0, 642)  0.14738966496831196
  (0, 1577) 0.20377626427753473
  (0, 1166) 0.2947793299366239
  : :
 (1046, 166)    0.500700591796996
[141  56  79 ...  26  26  26]
我试着做
hstack

features = np.hstack((dt_matrix, length))
In [129]: np.hstack([M, np.arange(5)[:,None]])                                                 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-129-f06fc972039d> in <module>
----> 1 np.hstack([M, np.arange(5)[:,None]])

<__array_function__ internals> in hstack(*args, **kwargs)

/usr/local/lib/python3.6/dist-packages/numpy/core/shape_base.py in hstack(tup)
    341     # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
    342     if arrs and arrs[0].ndim == 1:
--> 343         return _nx.concatenate(arrs, 0)
    344     else:
    345         return _nx.concatenate(arrs, 1)

<__array_function__ internals> in concatenate(*args, **kwargs)

ValueError: all the input arrays must have same number of dimensions, 
but the array at index 0 has 1 dimension(s) and the array at index 1
has 2 dimension(s)
In [130]: sparse.hstack([M, np.arange(5)[:,None]])                                             
Out[130]: 
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 8 stored elements in COOrdinate format>
In [131]: _.A                                                                                  
Out[131]: 
array([[0.        , 0.        , 0.        , 0.00622211, 0.        ],
       [0.71985591, 0.        , 0.        , 0.        , 1.        ],
       [0.36039864, 0.        , 0.        , 0.        , 2.        ],
       [0.        , 0.        , 0.        , 0.        , 3.        ],
       [0.        , 0.        , 0.95199276, 0.        , 4.        ]])
我得到这个输出:

ValueError: Found input variables with inconsistent numbers of samples: [1048, 1047]
我打印了形状:

print(np.shape(length))
print(np.shape(dt_matrix))
输出为:

(1047,)
(1047, 2078)
我做错了什么

编辑

sparse.hstack((dt_矩阵,长度.整形((长度.形状[0],1)))
这是工作代码。使用
scipy
中的
sparse
,感谢@hpaulij和@kederrak的帮助

您可以使用:

np.hstack((dt_matrix, length.reshape((1047, 1))))
或:

从:

参数:tup:ndarray序列

The arrays must have the same shape along all but the second axis
制作一个scipy.sparse矩阵:

In [124]: M = sparse.random(5,4,.2)                                                            
In [125]: M                                                                                    
Out[125]: 
<5x4 sparse matrix of type '<class 'numpy.float64'>'
    with 4 stored elements in COOrdinate format>
In [126]: print(M)                                                                             
  (0, 3)    0.006222105671732758
  (1, 0)    0.7198559134274957
  (2, 0)    0.3603986399431639
  (4, 2)    0.9519927602284366
In [127]: M.A                                                                                  
Out[127]: 
array([[0.        , 0.        , 0.        , 0.00622211],
       [0.71985591, 0.        , 0.        , 0.        ],
       [0.36039864, 0.        , 0.        , 0.        ],
       [0.        , 0.        , 0.        , 0.        ],
       [0.        , 0.        , 0.95199276, 0.        ]])
In [128]: type(M)                                                                              
Out[128]: scipy.sparse.coo.coo_matrix
正确使用sparse.hstack

features = np.hstack((dt_matrix, length))
In [129]: np.hstack([M, np.arange(5)[:,None]])                                                 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-129-f06fc972039d> in <module>
----> 1 np.hstack([M, np.arange(5)[:,None]])

<__array_function__ internals> in hstack(*args, **kwargs)

/usr/local/lib/python3.6/dist-packages/numpy/core/shape_base.py in hstack(tup)
    341     # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
    342     if arrs and arrs[0].ndim == 1:
--> 343         return _nx.concatenate(arrs, 0)
    344     else:
    345         return _nx.concatenate(arrs, 1)

<__array_function__ internals> in concatenate(*args, **kwargs)

ValueError: all the input arrays must have same number of dimensions, 
but the array at index 0 has 1 dimension(s) and the array at index 1
has 2 dimension(s)
In [130]: sparse.hstack([M, np.arange(5)[:,None]])                                             
Out[130]: 
<5x5 sparse matrix of type '<class 'numpy.float64'>'
    with 8 stored elements in COOrdinate format>
In [131]: _.A                                                                                  
Out[131]: 
array([[0.        , 0.        , 0.        , 0.00622211, 0.        ],
       [0.71985591, 0.        , 0.        , 0.        , 1.        ],
       [0.36039864, 0.        , 0.        , 0.        , 2.        ],
       [0.        , 0.        , 0.        , 0.        , 3.        ],
       [0.        , 0.        , 0.95199276, 0.        , 4.        ]])
In[130]:sparse.hstack([M,np.arange(5)[:,None]]
出[130]:
在[131]中:
出[131]:
数组([[0,0,0,0.00622211,0.],
[0.71985591, 0.        , 0.        , 0.        , 1.        ],
[0.36039864, 0.        , 0.        , 0.        , 2.        ],
[0.        , 0.        , 0.        , 0.        , 3.        ],
[0.        , 0.        , 0.95199276, 0.        , 4.        ]])
如果第二个数组是shape(5,)而不是(5,1),我将得到您的最新错误:

In [132]: sparse.hstack([M, np.arange(5)])                                                     
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-132-defd4158f59e> in <module>
----> 1 sparse.hstack([M, np.arange(5)])

/usr/local/lib/python3.6/dist-packages/scipy/sparse/construct.py in hstack(blocks, format, dtype)
    463 
    464     """
--> 465     return bmat([blocks], format=format, dtype=dtype)
    466 
    467 

/usr/local/lib/python3.6/dist-packages/scipy/sparse/construct.py in bmat(blocks, format, dtype)
    584                                                     exp=brow_lengths[i],
    585                                                     got=A.shape[0]))
--> 586                     raise ValueError(msg)
    587 
    588                 if bcol_lengths[j] == 0:

ValueError: blocks[0,:] has incompatible row dimensions. Got blocks[0,1].shape[0] == 1, expected 5.
[132]中的
:稀疏.hstack([M,np.arange(5)])
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在里面
---->1.hstack([M,np.arange(5)])
/hstack中的usr/local/lib/python3.6/dist-packages/scipy/sparse/construct.py(块、格式、数据类型)
463
464     """
-->465返回bmat([blocks],format=format,dtype=dtype)
466
467
/bmat中的usr/local/lib/python3.6/dist-packages/scipy/sparse/construct.py(块、格式、数据类型)
584 exp=眉毛长度[i],
585 got=A.shape[0]))
-->586提升值错误(msg)
587
588如果bcol_长度[j]==0:
ValueError:块[0,:]具有不兼容的行维度。获取块[0,1]。形状[0]==1,应为5。

hi,感谢您的回答,我根本不懂答案,但我将其三次分解,并在两行中都出现此错误:
ValueError:所有输入数组必须具有相同的维数,但索引0处的数组具有1个维数,索引1处的数组具有2个维数。
(编辑后编辑)@如果你必须使用整形,它们需要有相同数量的行,你的错误是第一个数组只有一个维度,你必须整形
length
array,
length.整形((1047,1))
请帮助我理解。我有一个大小为1047的数组和一个形状为1047、2078的矩阵。我想把数组作为矩阵的最后一列。它们实际上都有1047行。我不明白警告,为什么长度应该是二维的?如果你想使用
np.hstack
,他们需要这样做每列都有相同数量的行可以连接为什么?我刚刚试过使用与你在问题中打印的形状相同的np.one,它的
类型是什么
dt_矩阵
?你顺便提到了稀疏,但没有给出任何细节。如果是
scipy.sparse
格式,你就不能使用
np.hstack
在它上面。有一个
稀疏的.hstack
。是的,类型是
@hpaulj与sp.hstack一起尝试,得到了相同的:
ValueError:找到了样本数不一致的输入变量:[10481047]
那1048来自哪里?你声称一个数组是(1047),另一个是(10472078)。我知道,我也很惊讶。我打印了形状,并对数组和矩阵分别说:(1047,)和(1047,2078)谢谢你的回答。运行
sparse.hstack((dt_矩阵,长度))
我得到这个
值错误:块[0,:]的行维度不兼容。得到块[0,1]。形状[0]==1,预期为1047。
您的
长度
是一个列表或1d数组,而不是我使用的2d数组。不要马虎!请密切注意维度。如果您想向(n,m)矩阵/数组添加列,则需要使用(n,1)数组-无论使用
np.hstack
还是
sparse
sparse
sparse.hstack,都是如此((dt_矩阵,length.reforme((length.shape[0],1)))
有效,谢谢:)我对这类任务是新手,我不知道数组可以有(n,)维,而且(n,1)不同:(谢谢你的帮助