Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Numpy hstack-”的英文缩写;ValueError:所有输入数组必须具有相同数量的维度但他们确实如此_Python_Arrays_Numpy_Pandas_Scikit Learn - Fatal编程技术网

Python Numpy hstack-”的英文缩写;ValueError:所有输入数组必须具有相同数量的维度但他们确实如此

Python Numpy hstack-”的英文缩写;ValueError:所有输入数组必须具有相同数量的维度但他们确实如此,python,arrays,numpy,pandas,scikit-learn,Python,Arrays,Numpy,Pandas,Scikit Learn,我正在尝试加入两个numpy阵列。在其中一个例子中,我在一列文本上运行TF-IDF后,有一组列/特性。在另一列中,我有一个列/特征是整数。因此,我读入一列训练和测试数据,在此基础上运行TF-IDF,然后我想添加另一个整数列,因为我认为这将帮助我的分类器更准确地了解其行为 不幸的是,当我尝试运行hstack将这一列添加到我的另一个numpy数组时,标题中出现了错误 这是我的密码: #reading in test/train data for TF-IDF traindata = list

我正在尝试加入两个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
但是,尝试打印
AllAlexaAndGoogleInfo
的数据类型,如下所示:

print "AllAlexaAndGoogleInfo.dtype => " + str(AllAlexaAndGoogleInfo.dtype) 
产生:

'DataFrame' object has no attribute 'dtype'

使用
.column\u stack
。像这样:

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

获取一个一维数组序列,并将它们作为列进行堆栈,以生成一个 单个二维阵列。二维阵列按原样堆叠,就像hstack一样

尝试:


我没有正在运行的Pandas模块,因此无法测试它。但是DataFrame文档描述了NDFrame的数值Numpy表示形式
np.hstack
是一个
numpy
函数,因此对
数据帧的内部结构一无所知,因为
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 = 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
基于以下输出

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
没有
dtype
,因为它是一个
DataFrame
。要获取它的底层numpy数组,只需使用
AllAlexaAndGoogleInfo.values
。检查其
dtype
。根据错误消息,它的
dtype
object
,这意味着它可能包含字符串等非数字元素

这是一个再现这种情况的最小示例:

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 = 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'))

因此,在进行堆叠之前,请检查Allalexaa和GoogleInfo中是否存在任何非数值,并对其进行修复。

感谢您的回复。我已经更新了上面的问题,以显示由此产生的错误消息。3
str(*.shape)
行的输出是什么?如果上面的标记变得烦人,则在上面的问题中,但输出是:
X.shape=>(7395238377)
AllAlexaAndGoogleInfo.shape=>(7395,1)
X\u all.shape=>(10566238377)
。谢谢:)尝试
X.resize(AllAlexaAndGoogleInfo.shape)
然后
X=np.hstack((X,AllAlexaAndGoogleInfo))
。这一行然后抛出错误
属性错误:resize not found
。不过谢谢你的想法!:)
allAlexaAndGoogleInfo.append(X)
有效吗?我的猜测是,如果要将
DataFrame
对象与
numpy.ndarray
相结合,则需要使用Pandas提供的方法。或者将
数据帧
转换为普通的
numpy
数组。感谢您的响应,不幸的是,这也会导致:
值错误:所有输入数组必须具有相同的维数
:(我试图打印此内容;但我相信pandas会将其作为DataFrame对象读入,因此会抛出错误“DataFrame”对象没有属性“dtype”。我不确定如何解决此问题。非常感谢您的帮助:)但是,难道没有一种方法可以得到该数据帧的
ndarray
表达式吗?从文档中看,似乎
values
可以做到这一点。还有一种“as_matrix”方法。关于
ftypes
,我在文档中也看到了
dtypes
。数据帧可能包含
ndarray
,但它不是It如果
ndarray
np.hstack
能够强制类型,例如
np.hstack((X.A,xt))
工作,生成带有dtype对象的数组。
sparse.hstack
如果显式强制转换数组,也可以工作,例如
sparse.hstack((X.astype(object),xt))
OMFG我看到这个之前,我一直在拉扯我的头发和脑袋。谢谢!
TypeError: no supported conversion for types: (dtype('float64'), dtype('O'))