Python 4

[Python] XGBoost 사용 시 ValueError: DataFrame.dtypes for data must be int, float,

아래와 같이 XGBClassifier나 XGBRegressor를 사용할 때, 범주형 변수에 대한 고려 없이 데이터가 그대로 들어갈 경우 제목과 같은 ValueError가 발생할 수 있다. ### anti-pattern ### import xgboost as xgb # 데이터셋은 준비되어 있다고 가정 clf = xgb.XGBClassifier(random_state=42, verbosity=1) clf.fit(X_train, y_train) 이를 해결하기 위해 보통 범주형 변수를 인코딩하는데, 그렇게 하지 않고도 바로 XGBoost를 training할 수 있는 방법이 에러 메시지 두 번째 문장에 나온다. ValueError: DataFrame.dtypes for data must be int, float,..

Development/Python 2023.08.23

[Python] TypeError: {함수명} missing 1 required positional argument: {함수 인자명}

쉬운 케이스와 어려운 케이스가 있다. 1. 쉬운 케이스 ### anti-pattern ### def sum(a, b, c): return a + b + c sum(a, b) ## TypeError: sum() missing 1 required positional argument: 'c' sum()이라는 함수의 인자를 세 개 정의했는데, 실제 사용 시 세 개 미만으로 입력 시 발생한다. 이런 경우는 함수 정의를 다시 살피고 정의한 인자 개수만큼 넣어주면 해결할 수 있다. 2. 어려운 케이스 ### anti-pattern ### class Recommender: def __init__(self, df): self.df = df def sum(self, a, b, c): return a + b + c Reco..

Development/Python 2023.06.17

[Python] 판다스(pandas) read_csv() 함수로 파일 읽을 때 'Unnamed: 0' 제거하기

pandas의 read_csv() 함수로 파일을 읽어올 때 아래와 같이 그냥 파일 경로만 넣으면 'Unnamed:0'과 같은 달갑지 않은 컬럼이 붙어서 읽혀질 때가 있다. ### anti-pattern ### import pandas as pd sample_txt = pd.read_csv('file_dir') read_csv() 함수 인자 중 index_col이 따로 특정되지 않아서 발생하는 문제이다(default setting은 index_col=None). index_col을 아래와 같이 원하는 컬럼으로 지정해주면 해결된다. ### best-practice ### import pandas as pd sample_txt = pd.read_csv('file_dir', index_col=0) Enjoy y..

Development/Python 2023.06.14

[Python] Keras import 시 발생할 수 있는 에러들(ImportError: cannot import name 'get_config' 등)

Keras가 확실히 날것의 TensorFlow를 사용하는 것보다 편하긴 한데, import할 때 아래와 같은 두 가지 에러가 연달아 발생할 수 있다. 유명한 에러지만 이 둘을 연달아 정리한 글은 많지 않은 것 같다. 1. ImportError: cannot import name 'get_config' TensorFlow와 Keras의 버전이 맞지 않을 때 발생하는 에러이다. 아래와 같이 각각 import를 하면 발생할 수 있다. ### anti-pattern ### import tensorflow as tf import keras from keras.models import Sequential from keras.layers.core import Dense Line 2처럼 TensorFlow로부터 Ker..

Development/Python 2023.06.14