0

I am trying to reshape an (N, 1) array d to an (N,) vector. According to this solution and my own experience with numpy, the following code should convert it to a vector:

from sklearn.neighbors import kneighbors_graph
from sklearn.datasets import make_circles
X, labels = make_circles(n_samples=150, noise=0.1, factor=0.2)
A = kneighbors_graph(X, n_neighbors=5)
d = np.sum(A, axis=1)
d = d.reshape(-1)

However, d.shape gives (1, 150)

The same happens when I exactly replicate the code for the linked solution. Why is the numpy array not reshaping?

Community
  • 1
  • 1
Jacob Stern
  • 3,758
  • 3
  • 32
  • 54

1 Answers1

0

The issue is that the sklearn functions returned the nearest neighbor graph as a sparse.csr.csr_matrix. Applying np.sum returned a numpy.matrix, a data type that (in my opinion) should no longer exist. numpy.matrixs are incompatible with just about everything, and numpy operations on them return unexpected results.

The solution was casting the numpy.csr.csr_matrix to a numpy.array:

A = kneighbors_graph(X, n_neighbors=5)
A = A.toarray()
d = np.sum(A, axis=1)
d = d.reshape(-1)

Now we have d.shape = (150,)

Jacob Stern
  • 3,758
  • 3
  • 32
  • 54