작성
·
34
0
# 검증 데이터 분리
from sklearn.model_selection import train_test_split
X_tr,X_val,y_tr,y_val = train_test_split(
X_train, y_train, test_size = 0.2, random_state=0
)
X_tr.shape,X_val.shape,y_tr.shape,y_val.shape
# 라이브러리 불러오기
from sklearn.ensemble import RandomForestClassifier
# 랜덤포레스트
model = RandomForestClassifier(random_state=2022).fit(X_tr, y_tr)
pred = model.predict_proba(X_val)
이렇게 코딩는데 아래 에러가 났거든요
해결 못하겠느데 도움 부탁 드리겠습니다 ㅠㅠ
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-60-4020959764> in <cell line: 0>()
3
4 # 랜덤포레스트
----> 5 model = RandomForestClassifier(random_state=2022).fit(X_tr, y_tr)
6
7 pred = model.predict_proba(X_val)
6 frames
/usr/local/lib/python3.11/dist-packages/pandas/core/generic.py in __array__(self, dtype, copy)
2151 ) -> np.ndarray:
2152 values = self._values
-> 2153 arr = np.asarray(values, dtype=dtype)
2154 if (
2155 astype_is_view(values.dtype, arr.dtype)
ValueError: could not convert string to float: 'B'
답변 2
0
0
안녕하세요, 인프런 AI 인턴입니다.
최숙정님이 설명하신 문제에서 코드와 함께 발생한 ValueError: could not convert string to float: 'B'
오류는 학습 데이터에 범주형 데이터가 포함되어 있고, 이를 수치형으로 변환하지 않아 발생하는 오류입니다. RandomForestClassifier
는 문자열과 같은 고유 값이 있는 데이터를 처리할 수 없으므로, 이를 해결하기 위해 범주형 데이터를 수치형으로 변환해야 합니다.
RandomForestClassifier
는 수치형 데이터를 필요로 하기 때문에, 범주형 데이터를 수치형(보통 정수형)으로 변환해야 합니다. 오류 메시지에 있는 “could not convert string to float: ‘B’“는 ‘B’라는 문자열 값 때문에 발생했음을 나타냅니다. 이는 범주형 데이터가 수치형으로 변환되지 않아 발생한 문제입니다.
범주형 데이터를 처리하기 위해 LabelEncoder
또는 OneHotEncoder
를 사용할 수 있습니다. 가장 일반적으로 사용되는 방법은 LabelEncoder
를 사용하여 각 범주형 값을 정수로 변환하는 것입니다.
from sklearn.preprocessing import LabelEncoder
# X_train과 X_val의 범주형 열을 변환
label_encoders = {}
cols = X_train.select_dtypes(include='object').columns
for col in cols:
le = LabelEncoder()
X_train[col] = le.fit_transform(X_train[col])
X_val[col] = le.transform(X_val[col])
label_encoders[col] = le
이와 같이 LabelEncoder
를 사용하면 문자열로 되어 있는 범주형 데이터를 정수로 변환하여 모델에 전달할 수 있습니다.
유사한 문제에 대한 명확한 답변과 그에 대한 예제를 보시려면 아래의 링크를 참고하시면 좋습니다:
위의 링크에서는 범주형 데이터를 수치형으로 변환하는 구체적인 방법에 대해 설명하고 있습니다.
저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.