python - 为什么 np reshape 不适用于 np.matrix

标签 python numpy

我有稀疏矩阵,我正在尝试 reshape :

_train_data = model.pipeline.transform(train_data)
print(type(_train_data), _train_data.shape)
>>> <class 'scipy.sparse.csr.csr_matrix'> (18864, 3742)

我首先将其转换为密集的 numpy 数组:

 _train_data = _train_data.todense()
 print(type(_train_data), _train_data.shape)
 >>> <class 'numpy.matrix'> (18864, 3742)

然后尝试 reshape 它,目标是对其进行整形(18864, 3742, 1),以便我可以适应一些 keras 密集层,但 reshape 似乎不起作用:

a_new_df = _train_data.reshape((18864, 3742, -1))
print(type(a_new_df), a_new_df.shape)
>>> <class 'numpy.matrix'> (18864, 3742)

我也尝试过使用 np.reshape():

a_new_df = np.reshape(_train_data, (18864, 3742, -1))
print(type(a_new_df), a_new_df.shape)
>>> <class 'numpy.matrix'> (18864, 3742)

并使用不同的轴来 reshape :

a_new_df = np.reshape(_train_data, (18864, 3742, 1))
print(type(a_new_df), a_new_df.shape)
>>> <class 'numpy.matrix'> (18864, 3742)

a_new_df = np.reshape(_train_data, (1, 18864, 3742))
print(type(a_new_df), a_new_df.shape)
>>> <class 'numpy.matrix'> (18864, 3742)

但是这些都没有成功地 reshape 矩阵的形状。

最佳答案

来自矩阵文档字符串:

A matrix is a specialized 2-D array that retains its 2-D nature through operations.

如果你想 reshape 你需要一个数组。矩阵和稀疏对象具有返回数组的 .A 属性。

关于python - 为什么 np reshape 不适用于 np.matrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564309/

相关文章:

python - 同步本地和 Elastic Beanstalk 数据库?

python - 带有 Pandas Dataframe 的数据透视表(?)

python - Numpy,连接整数和 ndarrays 的简单公式

python - 如何在 pandas Dataframe 中查找 numpy 数组列的 boolean 值?

python - 更改 python 发行版

Apache 服务器上的 Python CGI

python - 根据某些列条件从 Pandas 数据框中获取所有行组合?

python - 获取文本标题

python - Cython:使用类型化内存 View 时,Cython 用户是否应该实现他们自己的 "vector"函数库?

python - Opencv python 相机校准 : objp matrix