Numpy hstack - "ValueError: 所有输入数组必须具有相同的维数" - 但它们确实有

21 投票
3 回答
51535 浏览
提问于 2025-04-17 21:20

我正在尝试把两个numpy数组合并在一起。在一个数组里,我有一组经过TF-IDF处理的列/特征,这些特征是从一列文本中提取的。在另一个数组里,我有一列特征,它是一个整数。所以我读取了训练和测试数据的一列,运行了TF-IDF处理,然后我想添加另一列整数,因为我觉得这会帮助我的分类器更准确地学习应该如何工作。

不幸的是,当我尝试使用hstack将这一列添加到我的另一个numpy数组时,出现了标题中的错误。

这是我的代码:

  #reading in test/train data for TF-IDF
  traindata = list(np.array(p.read_csv('FinalCSVFin.csv', delimiter=";"))[:,2])
  testdata = list(np.array(p.read_csv('FinalTestCSVFin.csv', delimiter=";"))[:,2])

  #reading in labels for training
  y = np.array(p.read_csv('FinalCSVFin.csv', delimiter=";"))[:,-2]

  #reading in single integer column to join
  AlexaTrainData = p.read_csv('FinalCSVFin.csv', delimiter=";")[["alexarank"]]
  AlexaTestData = p.read_csv('FinalTestCSVFin.csv', delimiter=";")[["alexarank"]]
  AllAlexaAndGoogleInfo = AlexaTestData.append(AlexaTrainData)

  tfv = TfidfVectorizer(min_df=3,  max_features=None, strip_accents='unicode',  
        analyzer='word',token_pattern=r'\w{1,}',ngram_range=(1, 2), use_idf=1,smooth_idf=1,sublinear_tf=1) #tf-idf object
  rd = lm.LogisticRegression(penalty='l2', dual=True, tol=0.0001, 
                             C=1, fit_intercept=True, intercept_scaling=1.0, 
                             class_weight=None, random_state=None) #Classifier
  X_all = traindata + testdata #adding test and train data to put into tf-idf
  lentrain = len(traindata) #find length of train data
  tfv.fit(X_all) #fit tf-idf on all our text
  X_all = tfv.transform(X_all) #transform it
  X = X_all[:lentrain] #reduce to size of training set
  AllAlexaAndGoogleInfo = AllAlexaAndGoogleInfo[:lentrain] #reduce to size of training set
  X_test = X_all[lentrain:] #reduce to size of training set

  #printing debug info, output below : 
  print "X.shape => " + str(X.shape)
  print "AllAlexaAndGoogleInfo.shape => " + str(AllAlexaAndGoogleInfo.shape)
  print "X_all.shape => " + str(X_all.shape)

  #line we get error on
  X = np.hstack((X, AllAlexaAndGoogleInfo))

下面是输出和错误信息:

X.shape => (7395, 238377)
AllAlexaAndGoogleInfo.shape => (7395, 1)
X_all.shape => (10566, 238377)



---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-2b310887b5e4> in <module>()
     31 print "X_all.shape => " + str(X_all.shape)
     32 #X = np.column_stack((X, AllAlexaAndGoogleInfo))
---> 33 X = np.hstack((X, AllAlexaAndGoogleInfo))
     34 sc = preprocessing.StandardScaler().fit(X)
     35 X = sc.transform(X)

C:\Users\Simon\Anaconda\lib\site-packages\numpy\core\shape_base.pyc in hstack(tup)
    271     # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
    272     if arrs[0].ndim == 1:
--> 273         return _nx.concatenate(arrs, 0)
    274     else:
    275         return _nx.concatenate(arrs, 1)

ValueError: all the input arrays must have same number of dimensions

是什么导致了我的问题?我该如何解决?就我所见,我应该能够将这些列合并在一起?我哪里理解错了?

谢谢。

编辑:

使用下面答案中的方法时出现了以下错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-640ef6dd335d> in <module>()
---> 36 X = np.column_stack((X, AllAlexaAndGoogleInfo))
     37 sc = preprocessing.StandardScaler().fit(X)
     38 X = sc.transform(X)

C:\Users\Simon\Anaconda\lib\site-packages\numpy\lib\shape_base.pyc in column_stack(tup)
    294             arr = array(arr,copy=False,subok=True,ndmin=2).T
    295         arrays.append(arr)
--> 296     return _nx.concatenate(arrays,1)
    297 
    298 def dstack(tup):

ValueError: all the input array dimensions except for the concatenation axis must match exactly

有趣的是,我尝试打印dtype(数据类型)时,X的打印结果正常:

X.dtype => float64

但是,尝试像这样打印AllAlexaAndGoogleInfo的dtype时:

print "AllAlexaAndGoogleInfo.dtype => " + str(AllAlexaAndGoogleInfo.dtype) 

结果是:

'DataFrame' object has no attribute 'dtype'

3 个回答

1

试试这个:

X = np.hstack((X, AllAlexaAndGoogleInfo.values))

我没有运行中的Pandas模块,所以没法测试。不过,DataFrame的文档里提到过 values Numpy表示的NDFramenp.hstack 是一个 numpy 的函数,因此它对 DataFrame 的内部结构是完全不知情的。

15

使用 .column_stack。像这样:

X = np.column_stack((X, AllAlexaAndGoogleInfo))

来自 文档

把一系列一维数组当作列堆叠起来,形成一个二维数组。二维数组会直接堆叠,就像用 hstack 一样。

23

因为X是一个稀疏数组,所以在连接数组时,不要用numpy.hstack,而应该用scipy.sparse.hstack。我觉得这里的错误信息有点误导人。

下面这个简单的例子说明了这个情况:

import numpy as np
from scipy import sparse

X = sparse.rand(10, 10000)
xt = np.random.random((10, 1))
print 'X shape:', X.shape
print 'xt shape:', xt.shape
print 'Stacked shape:', np.hstack((X,xt)).shape
#print 'Stacked shape:', sparse.hstack((X,xt)).shape #This works

根据下面的输出

X shape: (10, 10000)
xt shape: (10, 1)

你可能会期待下面这行的hstack能正常工作,但实际上它会抛出这个错误:

ValueError: all the input arrays must have same number of dimensions

所以,当你有一个稀疏数组需要合并时,记得用scipy.sparse.hstack


实际上,我在你另一个问题的评论中已经回答过这个,你提到又出现了另一个错误信息:

TypeError: no supported conversion for types: (dtype('float64'), dtype('O'))

首先,AllAlexaAndGoogleInfo是一个DataFrame,所以它没有dtype。要获取它底层的numpy数组,只需使用AllAlexaAndGoogleInfo.values。检查一下它的dtype。根据错误信息,它的dtypeobject,这意味着它可能包含一些非数字的元素,比如字符串。

这是一个简单的例子,能重现这个情况:

X = sparse.rand(100, 10000)
xt = np.random.random((100, 1))
xt = xt.astype('object') # Comment this to fix the error
print 'X:', X.shape, X.dtype
print 'xt:', xt.shape, xt.dtype
print 'Stacked shape:', sparse.hstack((X,xt)).shape

错误信息:

TypeError: no supported conversion for types: (dtype('float64'), dtype('O'))

所以,在进行合并之前,检查一下AllAlexaAndGoogleInfo中是否有任何非数字的值,并进行修正。

撰写回答