ValueError: Found input variables with inconsistent numbers of samples 해결하기(train_test_split)
2022. 11. 7. 13:20ㆍPython
데이터를 가지고 모델을 학습시키고 있는데 에러를 만나게 되었다.
복잡한 코드도 아니었기에 당황스러웠으나 일단 살펴보았는데
1.에러 내용
아래와 같은 매우 긴 에러글을 만나게되었다.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In [45], line 3
1 mlr=LinearRegression()
----> 3 mlr.fit(x_train, y_train)
File ~\anaconda3\envs\keyword\lib\site-packages\sklearn\linear_model\_base.py:684, in LinearRegression.fit(self, X, y, sample_weight)
680 n_jobs_ = self.n_jobs
682 accept_sparse = False if self.positive else ["csr", "csc", "coo"]
--> 684 X, y = self._validate_data(
685 X, y, accept_sparse=accept_sparse, y_numeric=True, multi_output=True
686 )
688 sample_weight = _check_sample_weight( 689 sample_weight, X, dtype=X.dtype, only_non_negative=True
690 )
692 X, y, X_offset, y_offset, X_scale = _preprocess_data(
693 X,
694 y, (...)
698 sample_weight=sample_weight,
699 )
File ~\anaconda3\envs\keyword\lib\site-packages\sklearn\base.py:596, in BaseEstimator._validate_data(self, X, y, reset, validate_separately, **check_params)
594 y = check_array(y, input_name="y", **check_y_params)
595 else:
--> 596 X, y = check_X_y(X, y, **check_params)
597 out = X, y
599 if not no_val_X and check_params.get("ensure_2d", True):
File ~\anaconda3\envs\keyword\lib\site-packages\sklearn\utils\validation.py:1092, in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator)
1074 X = check_array(
1075 X,
1076 accept_sparse=accept_sparse, (...)
1087 input_name="X",
1088 )
1090 y = _check_y(y, multi_output=multi_output, y_numeric=y_numeric, estimator=estimator)
-> 1092 check_consistent_length(X, y)
1094 return X, y
File ~\anaconda3\envs\keyword\lib\site-packages\sklearn\utils\validation.py:387, in check_consistent_length(*arrays)
385 uniques = np.unique(lengths)
386 if len(uniques) > 1:
--> 387 raise ValueError(
388 "Found input variables with inconsistent numbers of samples: %r"
389 % [int(l) for l in lengths]
390 )
ValueError: Found input variables with inconsistent numbers of samples: [716, 180]
말하고 있는 것은 한가지. 모델을 학습시킬 때 사용한 x와 y의 shape[0]가 맞지 않다는 것이었다.
2. 해결
이상해서 위로 올라가보니
train_test_split 을 사용할 때 아래와 같이 입력을 했었다
>>> x_train, y_train, x_test, y_test=train_test_split(x, y, train_size=0.8, test_size=0.2)
이를 아래와 같이 y_train과 x_test의 자리를 바꿔주니 에러가 해결되었음을 확인 할 수 있었다.
>>> x_train, x_test, y_train, y_test=train_test_split(x, y, train_size=0.8, test_size=0.2)
아무리 익숙한 작업이라 하더라도 다시 한 번 확인하고 넘어가자!