IT/Scikit-learn(sklearn)

linear model 에러 정리(inconsistent numbers of samples, expected 2d got 1d)

이녀기 2023. 6. 23. 17:40

Found input variables with inconsistent numbers of samples: [4, 5]

x = X[: 2 + target_idx]
y = X[: 2 + target_idx + 1]

- 원인: X와 Y의 차원이 달라서 그렇다.

- 해결: numpy.array인 X의 인덱싱 과정에서 ,를 빼먹어서 슬라이싱된 상황이었다. ,를 작성해서 해결.

 

x = X[:, 2 + target_idx]
y = X[:, 2 + target_idx + 1]​

Expected 2D array, got 1D array instead:

from sklearn import linear_model
regr = linear_model.LinearRegression()
regr.fit(x, y)

- 원인: linear_model.LinearRegression()은 x로 2d array를 받는다. 그 이유는 LinearRegression()에서 다변수 선형회귀를 지원하기 때문이다.

- 해결: reshape(-1, 1)을 하는 것으로 X값들을 리스트 안에 집어넣어서 2d array로 만들면 된다.

from sklearn import linear_model
regr = linear_model.LinearRegression()
regr.fit(x.values.reshape(-1, 1), y) # if X is DataFrame
regr.fit(x.reshape(-1, 1), y) # if X is not DataFrame(such as numpy.array)