DeseoDeSeo
[ Machine Learning ] Ex05_titanic 실습_part.03 본문
- Age에 따른 생존/ 사망 시각화
- 데이터의 분포를 확인할 때 여러가지 시각화 방법을 활용하는데, 그 중에 하나인 바이올린 플롯을 활용
plt.figure(figsize=(15,5)) # x축 : 15, y축 : 5
sns.violinplot(data=train, x='Sex', y='Age', hue='Survived', split =True)
# 중심을 기준으로 양쪽이 같기에, 한쪽면만 봄.
plt.show()
- 중앙의 선을 기준으로 왼쪽은 사망, 오른쪽은 생존자의 수
- 20~40대 사이에 사망 多
- 어린아이 중에서는 남자아이가 여자아이에 비해 많이 생존했음.
- fare(요금)에 따른 생존/사망 시각화 해보기.
plt.figure(figsize=(15,5)) # x축 : 15, y축 : 5
sns.violinplot(data=train, x='Sex', y='Fare', hue='Survived', split =True)
# 중심을 기준으로 양쪽이 같기에, 한쪽면만 봄.
# 0 ~ 300사이로 y 축 범위 제한.
plt.ylim(0,300)
plt.show()
- 요금이 저렴한 사람은 상대적으로 많이 사망함.
# Fare 기술 통계량 확인
train['Fare'].describe()
< 가족의 수 컬럼 생성 >
- 기존의 의미를 가지고 새로운 컬럼을 생성( 특성 공학의 분야 중 하나)
- 가족의 수 : Sibsp( 형제자매, 배우자) , Parch(부모, 자식) +1(자신)
- train, test 컬럼 모두 생성 진행
Sibsp + Parch +1 => Family_SIze 컬럼 추가
# train, test
train['Family_Size'] = train['SibSp'] + train['Parch'] + 1
train['Family_Size']
결과가 1이면 혼자 탑승한 것!.
test에 Family_Size 컬럼 생성
test['Family_Size'] = test['SibSp'] + test['Parch'] + 1
test['Family_Size']
가족의 수 컬럼을 이용해서 생존/ 사망 시각화
sns.countplot(data=train, x= 'Family_Size', hue='Survived')
plt.show()
- 1명 일때는사망 비율이 높고, 2~4명일 때는 생존 비율이 높고 5명이상이면 사망 비율이 더 높음.
- 사소한 관찰의 오류를 줄이기 위해서 범주를 줄여준다.(binning)
- 가족의 수가 1이면 ALONE, 2~4명일 때는 SMALL, 5명 이상이면 LARGE
- 연속적인수치값을범주화(카테고리 화) 사용하는 PANDAS 함수: PD.CUT ( )
- 범위( 구간 ) : bins 설정
- 범위에서 범위의 시작값은 포함되지 않는다.
user_bins= [0,1,4,11]
# 0 ~ 1이면 => 1이다.
# 1 ~ 4이면 => 1,2,3
user_labels=['Alone','Small','Large']
train['Family_Group'] = pd.cut(train['Family_Size'], bins = user_bins, labels=user_labels)
train['Family_Group']
test['Family_Group'] = pd.cut(test['Family_Size'], bins = user_bins, labels=user_labels)
test['Family_Group']
sns.countplot(data=train, x= 'Family_Group', hue='Survived')
plt.show()
< 불필요한 컬럼 삭제 >
- drop(), 컬럼은 옆으로 나열 되어있으니까 삭제할 이름이 있는 방향으로 axis=1로 설정.
- 전처리 대상에서 제외되거나 전처리 후 불필요한 컬럼 삭제
- Ticket, Name, Family_Size 삭제
- train, test 삭제
train = train.drop(columns=['Ticket','Name','Family_Size'],axis=1)
train.info()
test = test.drop(columns=['Ticket','Name','Family_Size'],axis=1) # inplace=True하면 됨.
test.info()
# 훈련문제. 훈련 답
x_train= train.drop('Survived', axis =1)
y_train= train ['Survived']
# 테스트 문제
x_test= test
범주형 -> 수치형으로 인코딩해야함. ( 원 핫 인코딩 )
# 인코딩 필요한 컬럼 찾기
# 데이터의 타입에 대한 질문으로 불리언 인덱싱 활용해보기
cat_filter = (x_train.dtypes !='int64') & (x_train.dtypes !='float64')
cat_choice = x_train.columns [cat_filter]
cat_choice
x_train[cat_choice]
원핫인코딩 함수 -> pd.get_dummies(대상)
x_train_ch_oh = pd.get_dummies(x_train[cat_choice])
x_train_ch_oh
x_test_ch_oh = pd.get_dummies(x_test[cat_choice])
x_test_ch_oh
x_train과 원핫인코딩 데이터 합치기(병합하기)
x_train = pd.concat([x_train, x_train_ch_oh], axis=1)
x_test = pd.concat([x_test, x_test_ch_oh], axis=1)
x_train
cat_choice 컬럼 삭제하기
x_train.drop(cat_choice, axis=1, inplace=True)
x_train
x_test.drop(cat_choice, axis=1, inplace=True)
x_test
x_train.shape, x_test.shape
< set() 자료형 >
- 집합
- 합집합. 차집합. 교집합
( 중복 x, 순서 x )
-> 중복을 허용하지 않는 set 특징은 자료형의 중복을 제거하기 위한 필터 역할로 종종 사용됨
-> 요소의 여부를 확인하기 위해서도 종종 사용 됨.
-> 인덱싱으로 데이터에 접근하기 위해서는 리스트나 튜플로 형변환해서 사용해야한다.
set(x_train.columns) - set(x_test.columns)
x_train에만 deck_t 가지고 있음.
인덱싱하려면 list로 해야함.
list(set(x_train.columns))
'Deck_T'에 0으로 채우겠다.
x_test['Deck_T'] = 0
x_test.shape
x_test 컬럼 순서를 x_train 컬럼 순서대로 맞추기
display(x_train.columns)
display(x_test.columns)
x_test = x_test[x_train.columns]
모델링
- 모델 선택 및 하이퍼 파라미터로 정의
- 모델 학습
- 모델 예측 및 평가
tree 분류
tree_model = DecisionTreeClassifier( )
-> 매개변수 random_state때문에 실행할 떄마다 모델의 학습 결과가 미묘하게 변경 될 수도 있음.
학습
#모델.fit(훈련문제, 훈련 답)
tree_model.fit(x_train,y_train)
예측 후, pred변수에 담기.
# pred = 모델.predict()
pred = tree_model.predict(x_test)
pred
정확도 점수 확인하기 위해서 kaggle제출
# 답안지 파일 불러오기
# index는 저장하지 않음.
sub =pd.read_csv('./data/titanic/gender_submission.csv')
sub['Survived'] =pred
sub.to_csv('123_submission01.csv',index=False)
sub
tree_model : 모델 깊이 조정( 하이퍼 파라미터 튜닝 과정 )
tree_model = DecisionTreeClassifier(max_depth= 5)
from sklearn.model_selection import cross_val_score
result = cross_val_score(tree_model, x_train, y_train, cv =5)
print(result.mean())
# 추후 max_depth, min_samples_split, max_leaf_nodes, min_samples_leaf
# 어떤 파라미터 값의 조합이 좋을지 찾아주는 방법을 연결해볼 수 있음.( => 그리드서치 )
# max_depth : 5라고 설정한 모델의 예측값 kaggle에 업로드하고 마무리!
tree_model.fit(x_train,y_train)
pred = tree_model.predict(x_test)
sub =pd.read_csv('./data/titanic/gender_submission.csv')
sub['Survived'] =pred
# index는 저장하지 않음.
sub.to_csv('xx12_submission02.csv',index=False)
'Python' 카테고리의 다른 글
[Machine learning] 앙상블 (0) | 2023.09.05 |
---|---|
[ Machine Learning ] ex06_타이타닉실습_앙상블모델 (0) | 2023.09.05 |
[Machine Learning] ex05_titanic 실습. part 02 (0) | 2023.09.01 |
[ Machine Learning ] ex05_titanic 분류실습 (0) | 2023.08.31 |
[ Machine Learning ] ex04_mushroom_part.02 (1) | 2023.08.31 |