강의

멘토링

로드맵

인프런 커뮤니티 질문&답변

dwj님의 프로필 이미지
dwj

작성한 질문수

머신러닝 로지스틱 회귀모델 랜덤서치 param_distribs 에러

작성

·

303

·

수정됨

0

안녕하세요!

머신러닝 학습 중 랜덤서치의 코드를 실행했을 때 에러가 발생하여 질문 드립니다.

학습 자료의 코드를 그대로 복사해서 실행해도 같은 에러가 발생하는데 어떤 이유인지 궁금하고 해결방안까지 알려주시면 감사하겠습니다🙏🏻

 

from scipy.stats import randint
param_distribs={'C': randint(low=0.001, high=100)}
from sklearn.model_selection import RandomizedSearchCV
random_search=RandomizedSearchCV(LogisticRegression(), param_distributions=param_distribs, n_iter=100, cv=5)random_search.fit(X_scaled_train, y_train)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[24], line 1
----> 1 random_search.fit(X_scaled_train, y_train)

File ~/anaconda3/lib/python3.11/site-packages/sklearn/base.py:1151, in _fit_context.<locals>.decorator.<locals>.wrapper(estimator, *args, **kwargs)
   1144     estimator._validate_params()
   1146 with config_context(
   1147     skip_parameter_validation=(
   1148         prefer_skip_nested_validation or global_skip_validation
   1149     )
   1150 ):
-> 1151     return fit_method(estimator, *args, **kwargs)

File ~/anaconda3/lib/python3.11/site-packages/sklearn/model_selection/_search.py:898, in BaseSearchCV.fit(self, X, y, groups, **fit_params)
    892     results = self._format_results(
    893         all_candidate_params, n_splits, all_out, all_more_results
    894     )
    896     return results
--> 898 self._run_search(evaluate_candidates)
    900 # multimetric is determined here because in the case of a callable
    901 # self.scoring the return type is only known after calling
    902 first_test_score = all_out[0]["test_scores"]

File ~/anaconda3/lib/python3.11/site-packages/sklearn/model_selection/_search.py:1806, in RandomizedSearchCV._run_search(self, evaluate_candidates)
   1804 def _run_search(self, evaluate_candidates):
   1805     """Search n_iter candidates from param_distributions"""
-> 1806     evaluate_candidates(
   1807         ParameterSampler(
   1808             self.param_distributions, self.n_iter, random_state=self.random_state
   1809         )
   1810     )

File ~/anaconda3/lib/python3.11/site-packages/sklearn/model_selection/_search.py:834, in BaseSearchCV.fit.<locals>.evaluate_candidates(candidate_params, cv, more_results)
    832 def evaluate_candidates(candidate_params, cv=None, more_results=None):
    833     cv = cv or cv_orig
--> 834     candidate_params = list(candidate_params)
    835     n_candidates = len(candidate_params)
    837     if self.verbose > 0:

File ~/anaconda3/lib/python3.11/site-packages/sklearn/model_selection/_search.py:325, in ParameterSampler.__iter__(self)
    323 for k, v in items:
    324     if hasattr(v, "rvs"):
--> 325         params[k] = v.rvs(random_state=rng)
    326     else:
    327         params[k] = v[rng.randint(len(v))]

File ~/anaconda3/lib/python3.11/site-packages/scipy/stats/_distn_infrastructure.py:468, in rv_frozen.rvs(self, size, random_state)
    466 kwds = self.kwds.copy()
    467 kwds.update({'size': size, 'random_state': random_state})
--> 468 return self.dist.rvs(*self.args, **kwds)

File ~/anaconda3/lib/python3.11/site-packages/scipy/stats/_distn_infrastructure.py:3357, in rv_discrete.rvs(self, *args, **kwargs)
   3328 """Random variates of given type.
   3329 
   3330 Parameters
   (...)
   3354 
   3355 """
   3356 kwargs['discrete'] = True
-> 3357 return super().rvs(*args, **kwargs)

File ~/anaconda3/lib/python3.11/site-packages/scipy/stats/_distn_infrastructure.py:1036, in rv_generic.rvs(self, *args, **kwds)
   1030 if not np.all(cond):
   1031     message = ("Domain error in arguments. The `scale` parameter must "
   1032                "be positive for all distributions, and many "
   1033                "distributions have restrictions on shape parameters. "
   1034                f"Please see the `scipy.stats.{self.name}` "
   1035                "documentation for details.")
-> 1036     raise ValueError(message)
   1038 if np.all(scale == 0):
   1039     return loc*ones(size, 'd')

ValueError: Domain error in arguments. The `scale` parameter must be positive for all distributions, and many distributions have restrictions on shape parameters. Please see the `scipy.stats.randint` documentation for details.

 

답변 1

1

안녕하세요, 인프런 AI 인턴이에요. 에러가 발생하셨군요.

해당 코드를 보면, 파라미터 분포를 정의하는 부분에서 문제가 발생한 것 같습니다. param_distribs 변수에는 ‘C’라는 파라미터의 분포를 정의하고 있는데, randint 함수를 이용하여 정수값 범위로 지정하셨네요.

그런데, LogisticRegression()의 ‘C’ 파라미터는 실수값 범위로 지정되어야 합니다. 그래서 randint 함수에서 생성되는 정수값을 실수로 변환해야 합니다.

아래와 같이 코드를 수정해보세요.
from scipy.stats import randint
param_distribs={‘C’: [float(x) for x in randint(low=1, high=100, size=100)]}

위 코드에서는 randint 함수로 생성된 정수값을 float() 함수를 이용하여 실수로 변환하고 있습니다. low와 high 매개변수도 적절한 값을 설정해주시기 바랍니다.

이렇게 수정하면 에러가 발생하지 않고 코드가 실행될 것입니다. 문제가 계속된다면, 해당 에러 메시지를 함께 알려주세요. 감사합니다.

dwj님의 프로필 이미지
dwj

작성한 질문수

질문하기