본문 바로가기
  • Hello_
Python/Error

[Python_Error] ValueError: The dimension of bins must be equal to the dimension of the sample x.

by LDwDL 2023. 1. 9.
728x90
반응형

본 포스팅은 업무 중 발생했던 오류들을 예시를 통해 어떻게 해결을 하는지 작성했다.

 

ValueError: The dimension of bins must be equal to the 
dimension of the  sample x.

위 에러메시지는 "np.histogram2d()" 모듈을 사용할 때 발생한 오류이다. 

 

import numpy as np

# Generate some random data
data_1 = np.random.randn(100, 2)

# Generate some random data
data_2 = np.random.randn(150, 2)

# Try to create a 2D histogram with one-dimensional bins
hist, _, _ = np.histogram2d(data_1.flatten(),data_2.flatten(), bins=(10,10))


"""
File ~/.conda/envs/soobumk/lib/python3.9/site-packages/numpy/lib/histograms.py:1031, in histogramdd(sample, bins, range, normed, weights, density)
   1029     M = len(bins)
   1030     if M != D:
-> 1031         raise ValueError(
   1032             'The dimension of bins must be equal to the dimension of the '
   1033             ' sample x.')
   1034 except TypeError:
   1035     # bins is an integer
   1036     bins = D*[bins]

ValueError: The dimension of bins must be equal to the dimension of the  sample x.
"""

 

 

해결법 

np.histogram2d에 대한 설명이다. 인자는 x, y, bins를 보통 받아서 사용이 되는데, 이 x와 y가 문제였다.

해당 인자들의 크기는 N으로 같은 길이를 가져야 한다.

 

np.histogram2d

 

 

위 코드에서 data_2의 길이는 150이 아닌 100으로 통일시켜 주면 문제없이 작동된다.

 

import numpy as np

# Generate some random data
data_1 = np.random.randn(100, 2)

# Generate some random data
data_2 = np.random.randn(100, 2)

# Try to create a 2D histogram with one-dimensional bins
hist, _, _ = np.histogram2d(data_1.flatten(),data_2.flatten(), bins=(10,10))

 

 

728x90
반응형

댓글