简体   繁体   中英

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

I am working on a binary text classification task and I've applied the vectorizer on my data as follows:

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

and because I want to take only a random sample from class '0' (a in my example)and classify it with class '1', I did the following:

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)

but I always getting the following error:

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

although when I print the shape it gaves me:

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

any idea how to fix it ? with of course preserving the indexes as it links to the labels.

Update: This is a print of the content/type of each arrays when the following commands executed:

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

EDIT: Apparently Scipy has it's own concatenate methods including hstack and vstack which deal with sparse matrices.

The problem is indeed the type. To solve it just convert your csr_matrix into an array, concatenate, and than convert it again to a 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)

The result is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM