numpy 如何使用麻面压平?

zd287kbt  于 2023-08-05  发布在  其他
关注(0)|答案(2)|浏览(67)

有一个numpy数组的形式为(50 100 100)。请解释如何将flatten函数应用于最后两个维度,即将其转换为形式(50 10000)。
你可以用一个python列表生成器来做,但我想找到一个更聪明的解决方案。

igsr9ssn

igsr9ssn1#

可以使用reshape代替flatten。要使用它,您需要传递希望数组变成的形状。你知道你希望第一个维度是50,你可以传递-1作为第二个维度,这告诉numpy找出这个值应该是什么。

arr.reshape(50,-1)

字符串

ql3eal8s

ql3eal8s2#

要展平NumPy数组的最后两个维度,可以使用reshape函数。

import numpy as np

# Assuming you have a NumPy array of shape (50, 100, 100)
array = np.random.random((50, 100, 100))

# Flatten the last two dimensions
flattened_array = array.reshape((array.shape[0], -1))

# Print the shape of the flattened array
print(flattened_array.shape)

字符串
在上面的代码中,array是原始的NumPy数组,形状为(50,100,100)。通过使用reshape函数,我们将新形状指定为(array.shape[0],-1),其中-1表示NumPy应根据剩余维度自动计算展开维度的适当大小

相关问题