我有稀疏矩阵,我正在尝试 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/