- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试加入两个 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
有趣的是,我尝试打印 X 的 dtype
并且效果很好:
X.dtype => float64
但是,尝试像这样打印 AllAlexaAndGoogleInfo
的 dtype:
print "AllAlexaAndGoogleInfo.dtype => " + str(AllAlexaAndGoogleInfo.dtype)
产生:
'DataFrame' object has no attribute 'dtype'
最佳答案
由于 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
没有dtype
,因为它是一个DataFrame
。要获得它的底层 numpy 数组,只需使用 AllAlexaAndGoogleInfo.values
。检查它的 dtype
。根据错误信息,它的 dtype
为 object
,这意味着它可能包含字符串等非数字元素。
这是重现这种情况的最小示例:
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
中是否有任何非数值并修复它们。
关于python - Numpy hstack - "ValueError: all the input arrays must have same number of dimensions"- 但他们这样做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22257836/
我想要 Text("111")具有与 VStack 相同的高度包含 2222... 和 333.... struct Test7: View { var body: some View { H
Desired output 寻找一种在不均匀元素中拆分 HStack 的方法,一个占据屏幕的 1/2,另外两个占据屏幕的 1/4(见附件)。 代码: struct MyCategoryRow:
我有这个 View 来显示从SwiftUI HStack with Wrap获得的多行文本标签,但是当我将其添加到VStack中时,这些标签会与下面放置的任何其他 View 重叠。 标签显示正确,但是
我创建了一个带有水平堆栈 View (标签、按钮、按钮)的简单列表。每个按钮都有自己的按钮操作,但是当我运行时,我可以看到点击一个按钮会打印两个操作。断点也出现在这两个 Action 中。她是我的代码
我一直在尝试制作具有 HStack 的 View 与 Image在其中,Image设置为可通过 aspectRatio 调整大小的 .fill .不知何故,它破坏了所有框架并在布局中引入了空间 例如,
我创建了一个带有水平堆栈 View (标签、按钮、按钮)的简单列表。每个按钮都有自己的按钮操作,但是当我运行时,我可以看到点击一个按钮会打印两个操作。断点也出现在两个 Action 中。她是我的密码
当我使用 CountVectorizer 等生成的一些稀疏矩阵的 scipy.sparse.hstack 时,我想合并它们以用于回归,但不知何故它们速度较慢: X1 有 10000 个来自 analy
我正在使用 HStack 在我的 View 层次结构中布置一些元素。我希望能够有条件地翻转元素的顺序。 HStack { Text("Hello") Text("World") } 我的想法是
下面的命令可以很好地堆叠两个具有左右 alpha channel 的 png 文件,输出 png 文件也将保留 alpha channel 。 ffmpeg -i a.png -i b.png -fi
我目前正在尝试水平堆叠多个视频文件并收到此错误 [libvorbis @ 000001bb38f23a80] Queue input is backward in timerate=N/A speed
我试图让键盘上的按钮在水平方向上彼此靠得更近。首先我尝试调整按钮框架的宽度。但是我发现,如果我减小框架宽度,一些像“W”这样的长宽字符将无法正确显示。 然后我尝试将 HStack 的间距设置为负数,就
hstack FFmpeg 命令的问题困扰着我。 input1 和 input2 都是垂直 360x640 视频。我将 input1 裁剪成一个正方形,将其与 input2 垂直合并,然后在生成的视频
我有一个 HStack: struct BottomList: View { var body: some View { HStack() { ForE
我正在尝试执行此代码: for i in Fil: for k in DatArr: a = np.zeros(0) for j in Bui:
我对 numpy.hstack() 函数有问题。我有三个相同的 numpy 数组,我想使用 hstack() 将它们连接起来,所以我从这些 numpy 数组创建元组并使用 numpy.hstack(t
我有两个 csr 稀疏矩阵。一个包含来自 sklearn.feature_extraction.text.TfidfVectorizer 的转换,另一个包含从 numpy 数组转换而来的转换。我试图对
这个问题在这里已经有了答案: How to extend an array in-place in Numpy? (4 个答案) 关闭 8 年前。 我是 Python 的新手,不确定为什么当我使用
我有以下矩阵: >>> X1 shape: (2399, 39999) type: scipy.sparse.csr.csr_matrix 和 >> X2 shape: (2399, 333534)
给定一个矩阵数组 matrices_w 我想在每个矩阵上应用 np.hstack 函数: matrices_w = np.asarray([[[1,2,3],[4,5,6]],[[9,8,7],[6,
我目前有一个 numpy 多维数组(float 类型)和一个 numpy 列数组(int 类型)。我想将两者组合成一个多维 numpy 数组。 import numpy >> dates.shape
我是一名优秀的程序员,十分优秀!