해결된 질문
작성
·
53
0
# 라이브러리 불러오기
import pandas as pd
# 데이터 불러오기
train = pd.read_csv("https://raw.githubusercontent.com/lovedlim/inf/refs/heads/main/p4/4_2/train.csv")
test = pd.read_csv("https://raw.githubusercontent.com/lovedlim/inf/refs/heads/main/p4/4_2/test.csv")
#preprocessing
print('변경전:',train.shape, test.shape)
train = train.drop('ID', axis =1 )
target = train.pop("Segmentation")
test_id = test.pop('ID')
print('변경후:',train.shape, test.shape)
data = pd.concat([train, test], axis = 0)
cols = data.select_dtypes(include = "object").columns
#encoding
from sklearn.preprocessing import LabelEncoder
for col in cols:
la = LabelEncoder()
data[col] = la.fit_transform(data[col])
train = data[:len(train)].copy()
test = data[len(train):].copy()
print(train.shape, test.shape)
print(train.head(3))
#분할
from sklearn.model_selection import train_test_split
X_tr, X_val, y_tr, y_val = train_test_split(train, target, test_size = 0.2, random_state = 0)
print(X_tr.shape, X_val.shape, y_tr.shape, y_val.shape)
#랜포
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(random_state = 1006 , max_depth=7, n_estimators = 1000)
rf.fit(X_tr, y_tr)
pred = rf.predict(X_val)
len(pred)
from sklearn.metrics import accuracy_score, f1_score
#점수측정
f1 = f1_score(y_val, pred, average='macro')
acccuracy = accuracy_score(y_val, pred)
print('f1:',f1)
print('acccuracy:', acccuracy)
#rf 기본 0.4946975843769027
# rf : max_depth=7, n_estimators = 1000
# f1: 0.5406747794301512
# acccuracy: 0.5566391597899475
# lgb
# f1: 0.5227625161214081
# acccuracy: 0.536384096024006
pred = rf.predict(test)#실제예측
pd.DataFrame({'ID':test_id,'Segmentation':pred}).to_csv("00000.csv", index = False)
pd.read_csv("00000.csv")
하이퍼파라미터 여러가지 넣으면서 f1스코어 테스트하면서 해봤는데 적절히 풀었는지 궁금합니다
답변 2
0
0
안녕하세요, 인프런 AI 인턴입니다. dnrwls9115님.
질문해주신 코드 분석을 통해, 작업형 2 문제 해결 방법에 대해 몇 가지 피드백을 드리겠습니다.
데이터 전처리:
LabelEncoder
를 사용하여 카테고리 변수를 숫자로 변환하신 것은 옳습니다. 이는 클러스터링에 필요한 전처리 과정입니다.train
과 test
로 적절히 분리하고, train_test_split
함수를 사용하여 추가적인 검증 셋을 만드신 부분도 잘 하셨습니다.모델링:
RandomForestClassifier
을 사용하여 예측하는 것은 매우 직관적입니다. 랜덤 포레스트는 복잡한 데이터에서도 강력한 성능을 발휘하기 때문에 적절한 선택입니다.max_depth=7
, n_estimators=1000
)을 통해 모델 성능을 높이려는 시도 역시 적극적입니다.성능 평가:
f1_score
와 accuracy_score
로 모델 성능 측정을 하셨습니다. 이때 f1_score
는 데이터의 클래스 불균형을 다루기 위한 좋은 지표입니다.실제 예측 및 저장:
추가적으로, 각 모델 학습이 끝난 후 성능을 평가하여 적절한 하이퍼파라미터를 찾는 과정이 향후 더 복잡한 데이터셋에서도 유용할 것입니다.
해당 코드를 바탕으로, 다른 사용자님들의 유사한 경험을 공유할 수 있는 사례를 추천드리겠습니다:
저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.