Programing

numpy 배열의 일부 차원 만 평면화하는 방법

lottogame 2020. 8. 26. 08:18
반응형

numpy 배열의 일부 차원 만 평면화하는 방법


numpy 배열의 첫 번째 차원 중 일부만 "하위 평면화"하거나 평면화하는 빠른 방법이 있습니까?

예를 들어, 차원의 배열이 많으면 (50,100,25)결과 차원은 다음과 같습니다.(5000,25)


numpy.reshape를 살펴 보십시오 .

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)

Alexander의 대답에 대한 약간의 일반화-np.reshape는 -1을 인수로 사용할 수 있습니다. 이는 "전체 배열 크기를 다른 모든 차원의 곱으로 나눈 값"을 의미합니다.

예를 들어 마지막 치수를 제외한 모든 것을 평평하게하려면 :

>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)

Peter의 대답에 대한 약간의 일반화-3 차원 배열을 넘어서고 싶다면 원래 배열의 모양에 대한 범위를 지정할 수 있습니다.

예를 들어 마지막 치수를 제외한 모든 치수 를 평면화 합니다.

arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)

편집 : 이전 답변에 대한 약간의 일반화-물론 모양 변경 시작 부분에도 범위를 지정할 수 있습니다.

arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)

다른 방법은 다음과 같이 사용 numpy.resize()하는 것입니다.

In [37]: shp = (50,100,25)
In [38]: arr = np.random.random_sample(shp)
In [45]: resized_arr = np.resize(arr, (np.prod(shp[:2]), shp[-1]))
In [46]: resized_arr.shape
Out[46]: (5000, 25)

# sanity check with other solutions
In [47]: resized = np.reshape(arr, (-1, shp[-1]))
In [48]: np.allclose(resized_arr, resized)
Out[48]: True

참고 URL : https://stackoverflow.com/questions/18757742/how-to-flatten-only-some-dimensions-of-a-numpy-array

반응형