无法将 (N, 1) 数组转换为 (N,)

cannot convert (N, 1) array to (N,)

我有一个 (200, 1) 矩阵,我需要将它转换为 (200,)

y = np.matrix(np.append(np.zeros(200), np.ones(200))).T

y的形状是(200,1)

我尝试展平矩阵:

c = y.flatten() 

我的形状是 (1,200)

然后我尝试访问矩阵的第一个元素,

c[0].shape

而且我的身材还是 (1, 200)

如何将原始矩阵转换为(200,)

您正在使用 np.matrix 并根据 documentation

class numpy.matrix[source] Returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array that retains its 2-D nature through operations.

因此,调用matrix.flatten(). (Note that matrix.flatten()后,c的维数仍为2

return a copy of the matrix, flattened to a (1, N) matrix where N is the number of elements in the original matrix.

一个解决方案:在

中使用np.array
y = np.array(np.append(np.zeros(200), np.ones(200))).T

您可以使用y.A1

>>> y = np.matrix(np.identity(3))
>>> y
matrix([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])
>>> y.A1
array([1., 0., 0., 0., 1., 0., 0., 0., 1.])