• 카테고리

    질문 & 답변
  • 세부 분야

    딥러닝 · 머신러닝

  • 해결 여부

    미해결

Bayesian Optimization에서 optimizer.maximize()함수를 더이상 지원 안한다고 합니다.

24.02.02 11:09 작성 24.02.02 11:14 수정 조회수 216

0

- 본 강의 영상 학습 관련 문의에 대해 답변을 드립니다. (어떤 챕터 몇분 몇초를 꼭 기재부탁드립니다)
- 이외의 문의등은 평생강의이므로 양해를 부탁드립니다
- 현업과 병행하는 관계로 주말/휴가 제외 최대한 3일내로 답변을 드리려 노력하고 있습니다
- 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.

 

import numpy as np
from xgboost import XGBClassifier
from bayes_opt import BayesianOptimization
from sklearn.model_selection import cross_val_score

pbounds = {  
    'learning_rate': (0.01, 0.5),  
    'n_estimators': (100, 1000), 
    'max_depth': (3, 10),
    'min_child_weight': (0, 10),    
    'subsample': (0.5, 1.0),
    'colsample_bytree': (0.5, 1.0)
    # 'reg_lambda': (0, 1000),
    # 'reg_alpha': (0, 1.0)
}

def lgbm_hyper_param(learning_rate, n_estimators, max_depth, min_child_weight, subsample, colsample_bytree):
    max_depth = int(max_depth)
    n_estimators = int(n_estimators)
    clf = LGBMClassifier(
        max_depth=max_depth,
        min_child_weight=min_child_weight,
        learning_rate=learning_rate, 
        n_estimators=n_estimators, 
        subsample=subsample, 
        colsample_bytree=colsample_bytree,
        random_state=1
        # reg_lambda=reg_lambda,        
        # reg_alpha=reg_alpha
    )
    return np.mean(cross_val_score(clf, train_importance, train_answer, cv=5, scoring='accuracy'))   # cv 도 숫자로 작성하여, 내부적으로 (Stratified)KFold 사용함

optimizer = BayesianOptimization( f=lgbm_hyper_param, pbounds=pbounds, verbose=1, random_state=1)
optimizer.maximize(init_points=10, n_iter=100, acq='ei', xi=0.01)

위 코드를 실행하면 아래와 같은 에러가 발생합니다.

---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
Cell In[44], line 34
     31     return np.mean(cross_val_score(clf, train_importance, train_answer, cv=5, scoring='accuracy'))   # cv 도 숫자로 작성하여, 내부적으로 (Stratified)KFold 사용함
     33 optimizer = BayesianOptimization( f=lgbm_hyper_param, pbounds=pbounds, verbose=1, random_state=1)
---> 34 optimizer.maximize(init_points=10, n_iter=100, acq='ei', xi=0.01)

File ~\miniconda3\Lib\site-packages\bayes_opt\bayesian_optimization.py:288, in BayesianOptimization.maximize(self, init_points, n_iter, acquisition_function, acq, kappa, kappa_decay, kappa_decay_delay, xi, **gp_params)
    286 old_params_used = any([param is not None for param in [acq, kappa, kappa_decay, kappa_decay_delay, xi]])
    287 if old_params_used or gp_params:
--> 288     raise Exception('\nPassing acquisition function parameters or gaussian process parameters to maximize'
    289                              '\nis no longer supported. Instead,please use the "set_gp_params" method to set'
    290                              '\n the gp params, and pass an instance of bayes_opt.util.UtilityFunction'
    291                              '\n using the acquisition_function argument\n')
    293 if acquisition_function is None:
    294     util = UtilityFunction(kind='ucb',
    295                            kappa=2.576,
    296                            xi=0.0,
    297                            kappa_decay=1,
    298                            kappa_decay_delay=0)

Exception: 
Passing acquisition function parameters or gaussian process parameters to maximize
is no longer supported. Instead,please use the "set_gp_params" method to set
 the gp params, and pass an instance of bayes_opt.util.UtilityFunction
 using the acquisition_function argument

 

 

"set_gp_params" method을 사용하라고 하는데

gpt에 물어봐도 제대로 된 코드를 주지 않아서 어려움이 있습니다.

 

제가 설치한 라이브러리는 아래 목록과 같습니다..

Package                      Version
---------------------------- ------------
absl-py                      2.1.0
anyio                        3.5.0
archspec                     0.2.1
argon2-cffi                  21.3.0
argon2-cffi-bindings         21.2.0
asttokens                    2.0.5
astunparse                   1.6.3
async-lru                    2.0.4
attrs                        23.1.0
Babel                        2.11.0
bayesian-optimization        1.4.3
beautifulsoup4               4.12.2
bleach                       4.1.0
boltons                      23.0.0
Brotli                       1.0.9
cachetools                   5.3.2
certifi                      2023.11.17
cffi                         1.16.0
charset-normalizer           2.0.4
colorama                     0.4.6
comm                         0.1.2
conda                        23.11.0
conda-content-trust          0.2.0
conda-libmamba-solver        23.12.0
conda-package-handling       2.2.0
conda_package_streaming      0.9.0
contourpy                    1.2.0
cryptography                 41.0.7
cv                           1.0.0
cycler                       0.12.1
debugpy                      1.6.7
Note: you may need to restart the kernel to use updated packages.
decorator                    5.1.1
defusedxml                   0.7.1
distro                       1.8.0
executing                    0.8.3
fastjsonschema               2.16.2
flatbuffers                  23.5.26
fonttools                    4.47.2
gast                         0.5.4
google-auth                  2.26.2
google-auth-oauthlib         1.2.0
google-pasta                 0.2.0
grpcio                       1.60.0
h5py                         3.10.0
idna                         3.4
ipykernel                    6.25.0
ipython                      8.20.0
ipywidgets                   8.0.4
jedi                         0.18.1
Jinja2                       3.1.2
joblib                       1.3.2
json5                        0.9.6
jsonpatch                    1.32
jsonpointer                  2.1
jsonschema                   4.19.2
jsonschema-specifications    2023.7.1
jupyter                      1.0.0
jupyter_client               8.6.0
jupyter-console              6.6.3
jupyter_core                 5.5.0
jupyter-events               0.8.0
jupyter-lsp                  2.2.0
jupyter_server               2.10.0
jupyter_server_terminals     0.4.4
jupyterlab                   4.0.8
jupyterlab-pygments          0.1.2
jupyterlab_server            2.25.1
jupyterlab-widgets           3.0.9
keras                        2.15.0
kiwisolver                   1.4.5
libclang                     16.0.6
libmambapy                   1.5.3
lightgbm                     4.3.0
Markdown                     3.5.2
MarkupSafe                   2.1.3
matplotlib                   3.8.2
matplotlib-inline            0.1.6
menuinst                     2.0.1
mistune                      2.0.4
ml-dtypes                    0.2.0
nbclient                     0.8.0
nbconvert                    7.10.0
nbformat                     5.9.2
nest-asyncio                 1.5.6
notebook                     7.0.6
notebook_shim                0.2.3
numpy                        1.26.3
oauthlib                     3.2.2
opencv-python                4.9.0.80
opt-einsum                   3.3.0
overrides                    7.4.0
packaging                    23.1
pandas                       2.2.0
pandocfilters                1.5.0
parso                        0.8.3
pillow                       10.2.0
pip                          23.3.2
platformdirs                 3.10.0
pluggy                       1.0.0
ply                          3.11
prometheus-client            0.14.1
prompt-toolkit               3.0.43
protobuf                     4.23.4
psutil                       5.9.0
pure-eval                    0.2.2
pyasn1                       0.5.1
pyasn1-modules               0.3.0
pycosat                      0.6.6
pycparser                    2.21
Pygments                     2.15.1
pyOpenSSL                    23.2.0
pyparsing                    3.1.1
PyQt5                        5.15.10
PyQt5-sip                    12.13.0
PySocks                      1.7.1
python-dateutil              2.8.2
python-json-logger           2.0.7
pytz                         2023.3.post1
pywin32                      305.1
pywinpty                     2.0.10
PyYAML                       6.0.1
pyzmq                        25.1.0
qtconsole                    5.5.0
QtPy                         2.4.1
referencing                  0.30.2
requests                     2.31.0
requests-oauthlib            1.3.1
rfc3339-validator            0.1.4
rfc3986-validator            0.1.1
rpds-py                      0.10.6
rsa                          4.9
ruamel.yaml                  0.17.21
scikit-learn                 1.4.0
scipy                        1.12.0
Send2Trash                   1.8.2
setuptools                   68.2.2
sip                          6.7.12
six                          1.16.0
sniffio                      1.3.0
soupsieve                    2.5
stack-data                   0.2.0
tensorboard                  2.15.1
tensorboard-data-server      0.7.2
tensorflow                   2.15.0
tensorflow-estimator         2.15.0
tensorflow-intel             2.15.0
tensorflow-io-gcs-filesystem 0.31.0
termcolor                    2.4.0
terminado                    0.17.1
threadpoolctl                3.2.0
tinycss2                     1.2.1
tornado                      6.3.3
tqdm                         4.65.0
traitlets                    5.7.1
truststore                   0.8.0
typing_extensions            4.7.1
tzdata                       2023.4
urllib3                      1.26.18
wcwidth                      0.2.5
webencodings                 0.5.1
websocket-client             0.58.0
Werkzeug                     3.0.1
wheel                        0.41.2
widgetsnbextension           4.0.5
win-inet-pton                1.1.0
wrapt                        1.14.1
xgboost                      2.0.3
zstandard                    0.19.0

 

 

 

궁극적인 질문은

앞으로 파이썬은 계속 업데이트가 될텐데 그때마다

어디를 찾아봐야하는지 어떻게 검색해야하는지에 관해서도 알려주시면 감사하겠습니다..

 

 

 

 

답변 2

·

답변을 작성해보세요.

0

안녕하세요. 답변도우미입니다.

해당 에러는 다음과 같이 라이브러리의 업데이트로인한 충돌 사항으로 보여집니다. 관련 부분은 제공해드린 코드 자료에 업데이트하였습니다.

 

# 202402 업데이트: Bayesian Optimization 라이브러리에서는 maximize 메소드의 사용법이 변경되어

# maximize() 메서드에서 acq 와 xi 를 직접 설정시 에러가 납니다. 따라서 해당 코드를 삭제하였습니다.

# 기존 코드: optimizer.maximize(init_points=10, n_iter=100, acq='ei', xi=0.01)

# maximize 메소드 호출

optimizer.maximize(init_points=10, n_iter=100)

 

pandas, scikit-learn 는 대형 라이브러리라서, 해당 라이브러리 사용시 해당 라이브러리가 내부적으로 사용하는 다른 라이브러리와의 버전 매칭에 따라서, 다양한 에러가 날 수 있습니다. 가장 확실한 것은 내부적으로 사용하는 라이브러리의 버전까지 정확히 맞추는 것인데요. 그럼에도 각각의 버전별 사용법이 다르거나, 심지어 버그가 있는 경우도 있어요. 그래서 주요 기능이 아니라 이와 같이 edge 에 가까운 기능을 사용하다보면, 완벽히 모든 기능이 동작하지 않을 수는 있습니다.

 

저희 같은 경우에는 주요 기능이 아니라면, 어느 정도는 그럴 수 있다는 점을 감안하고 사용을 합니다. 관련 부분이 이슈가 있는지등은 gpt 뿐만 아니라, 구글로 에러 메세지등을 검색하여 찾아내는 것이 일반적입니다. 그래서 gpt + 구글 검색을 둘다 사용하시는 것을 추천드립니다.

감사합니다.

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2024.02.04

안녕하세요, 인프런 AI 인턴입니다.
startup_edu2님의 질문에 답변드리겠습니다.

Bayesian Optimization 라이브러리에서 maximize 메서드는 기존의 파라미터 입력 방식이 아닌 UtilityFunction 클래스를 이용하여 입력을 받도록 변경되었습니다. 따라서 간단히 코드를 수정하여 optimizer.maximize를 수행할 수 있도록 하겠습니다.

from bayes_opt import BayesianOptimization, UtilityFunction

# 기존 코드의 나머지 부분은 동일하게 유지합니다.

# UtilityFunction 인스턴스를 생성합니다.
utility = UtilityFunction(kind="ei", xi=0.01, kappa=None)

# optimizer.maximize 호출 시, instantiation 파라미터에 utility 인스턴스를 넘깁니다.
optimizer.maximize(init_points=10, n_iter=100, acq=utility)

이렇게 수정하시면 기존의 maximize 메서드 사용에 대한 문제를 해결할 수 있습니다.

파이썬이나 라이브러리의 업데이트에 따른 변경사항을 확인하는 방법으로는 다음과 같은 접근 방법을 추천드립니다:

  1. 라이브러리 공식 문서 확인: 라이브러리의 공식 문서는 가장 신뢰성 있는 정보를 제공합니다. 업데이트 내역, 변경 사항, 사용 방법 등이 자세히 기술되어 있습니다.
  2. 릴리스 노트/체인지로그 참고: GitHub 등의 저장소에서 제공되는 릴리스 노트나 체인지로그를 통해 해당 버전에서 바뀐 사항들을 파악할 수 있습니다.
  3. 커뮤니티 활용: Stack Overflow, Reddit, 라이브러리 관련 포럼 등에서 해당 라이브러리의 업데이트에 대한 토론을 찾아볼 수 있습니다.
  4. 관련 블로그나 기사 검색: 때때로 기술 블로그나 기사에서 라이브러리 업데이트에 대한 설명을 쉽게 풀어쓴 글을 찾을 수 있습니다.

각 라이브러리나 프레임워크의 변화를 빠르게 파악하고, 중요한 업데이트 내용을 적용하는 것은 개발자로서의 중요한 능력 중 하나입니다. 지속적으로 학습하면서 경험을 쌓아나가시길 바랍니다.