簡體   English   中英

合並兩個2D數組時出錯不能連接零維數組

[英]Error when merging two 2D arrays Zero-dimensional arrays cannot be concatenated

我正在執行二進制文本分類任務,並且已將矢量化器應用於數據,如下所示:

count_vect = CountVectorizer(tokenizer=tokens)
X_train_counts = count_vect.fit_transform(docs_train.data)
print X_train_counts.shape
(150, 370)

並且因為我只想從類'0'(在我的示例中為a)中隨機抽取一個樣本並將其分類為類'1',所以我做了以下工作:

x =  X_train_counts
y =  docs_train.target

a_x,a_y=x[y==0,:],y[y==0]   
b_x,b_y=x[y==1,:],y[y==1]

inds=np.random.choice(range(a_x.shape[0]),50)
random_x=a_x[inds,:]
random_y=a_y[inds]

x_merged=np.concatenate((random_x,b_x))
y_merged=np.concatenate((random_y,b_y))
X_train,y_train=shuffle(x_merged, y_merged, random_state=0)

但我總是收到以下錯誤:

x_merged=np.concatenate((random_x,b_x))
ValueError: zero-dimensional arrays cannot be concatenated

雖然當我打印形狀時它給了我:

print random_x.shape
print b_x.shape
(50, 370)
(50, 370)

知道如何解決嗎? 當然,在鏈接到標簽時會保留索引。

更新:這是執行以下命令時每個陣列的內容/類型的打印:

print random_x[:5,:].toarray()
print b_x[:5,:].toarray()
print (type(random_x))
print (type(b_x))

[[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [4 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]
[[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]
<class 'scipy.sparse.csr.csr_matrix'>
<class 'scipy.sparse.csr.csr_matrix'>

編輯:顯然Scipy有它自己的連接方法,包括處理稀疏矩陣的hstackvstack

問題確實是類型。 要解決該問題,只需將csr_matrix轉換為數組,然后串聯,然后再將其轉換為csr_matrix:

     import numpy as np
     import scipy.sparse as m
     a = np.zeros((50, 370))
     b = np.zeros((50, 370))

     am = m.csr_matrix(a).toarray()
     bm = m.csr_matrix(b).toarray()
     cm = m.csr_matrix(np.concatenate((am,bm)))
     print(am.shape,bm.shape,cm.shape)

結果是:

     (50, 370) (50, 370) (100, 370)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM