본문 바로가기
AI

타이타닉 데이터셋

by 코낄2 2023. 12. 26.

1. 타이타닉 데이터셋

타이타닉 데이터셋은 역사적인 타이타닉호의 승객 정보에 관한 데이터입니다. 이 데이터셋은 기계 학습 및 데이터 분석을 연습하기 위한 대표적인 예제로 많이 사용됩니다. 주로 생존 여부와 관련된 문제로 사용되며, 승객의 여러 특성에 대한 정보를 포함하고 있습니다.

  1. Survived (생존 여부): 0이면 사망, 1이면 생존.
  2. Pclass (티켓 등급): 1, 2, 3 등급이 있음.
  3. Name (이름): 승객의 이름.
  4. Sex (성별): 남성 또는 여성.
  5. Age (나이): 승객의 나이.
  6. SibSp (형제자매 또는 배우자 수): 함께 탑승한 형제자매 또는 배우자의 수.
  7. Parch (부모 또는 자녀 수): 함께 탑승한 부모 또는 자녀의 수.
  8. Ticket (티켓 번호): 승객의 티켓 번호.
  9. Fare (운임 요금): 지불한 운임 요금.
  10. Cabin (객실 번호): 승객의 객실 번호.
  11. Embarked (탑승 항구): C, Q, S 중 하나로 표시되며, 각각 Cherbourg, Queenstown, Southampton을 나타냄.

https://bit.ly/fc-ml-titanic

import numpy as np
import pandas as pd

df = pd.read_csv('https://bit.ly/fc-ml-titanic')

 

2. 데이터 전처리

데이터 정제 작업을 뜻합니다. 필요없는 데이터를 삭제하고, null 값이 있는 행, 이상치들을 처리하고, 정규화/표준화 등의 많은 작업을 포함하고 있습니다. 머신러닝, 딥러닝 실무에서 전처리가 50% 이상의 중요도를 차지합니다. 이러한 데이터 전처리 작업은 모델의 성능뿐만 아니라 모델의 해석성과 안정성에도 영향을 미칩니다. 따라서 데이터 전처리 단계를 신중하게 수행하고, 여러 실험을 통해 최적의 전처리 방법을 찾는 것이 중요합니다.

✔️ 독립변수와 종속변수 나누기

feature = ['Pclass', 'Sex', 'Age', 'Fare'] # 독립변수
label = ['Survived'] # 종속변수

df[feature].head()

df[label].value_counts()

Survived
0           549
1           342
dtype: int64

✔️ 결측치 처리

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   PassengerId  891 non-null    int64  
 1   Survived     891 non-null    int64  
 2   Pclass       891 non-null    int64  
 3   Name         891 non-null    object 
 4   Sex          891 non-null    object 
 5   Age          714 non-null    float64
 6   SibSp        891 non-null    int64  
 7   Parch        891 non-null    int64  
 8   Ticket       891 non-null    object 
 9   Fare         891 non-null    float64
 10  Cabin        204 non-null    object 
 11  Embarked     889 non-null    object 
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KB

# 결측치 갯수 보기
df.isnull().sum()

PassengerId      0
Survived         0
Pclass           0
Name             0
Sex              0
Age            177
SibSp            0
Parch            0
Ticket           0
Fare             0
Cabin          687
Embarked         2
dtype: int64

# 결측치 비율 보기
df.isnull().mean()

PassengerId    0.000000
Survived       0.000000
Pclass         0.000000
Name           0.000000
Sex            0.000000
Age            0.198653
SibSp          0.000000
Parch          0.000000
Ticket         0.000000
Fare           0.000000
Cabin          0.771044
Embarked       0.002245
dtype: float64

 

- 평균 나이로 'age' NaN을 채움

df['Age']= df['Age'].fillna(df['Age'].mean())

df['Age']
0      22.000000
1      38.000000
2      26.000000
3      35.000000
4      35.000000
         ...    
886    27.000000
887    19.000000
888    29.699118
889    26.000000
890    32.000000
Name: Age, Length: 891, dtype: float64

✔️ 라벨 인코딩(Label Encoding)

- 문자(Categorical)를 수치(Numerical)로 변환함

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   PassengerId  891 non-null    int64  
 1   Survived     891 non-null    int64  
 2   Pclass       891 non-null    int64  
 3   Name         891 non-null    object 
 4   Sex          891 non-null    object 
 5   Age          891 non-null    float64
 6   SibSp        891 non-null    int64  
 7   Parch        891 non-null    int64  
 8   Ticket       891 non-null    object 
 9   Fare         891 non-null    float64
 10  Cabin        204 non-null    object 
 11  Embarked     889 non-null    object 
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KB

- object인 값이 몇가지의 대표값으로 나뉘어져있는지 .value_counts()를 해봐야한다.

df['Sex'].value_counts()

male      577
female    314
Name: Sex, dtype: int64

- 남자는 1, 여자는 0으로 라벨인코딩

sex_map = {'male': 1, 'female': 0}
df['Sex_code'] = df['Sex'].map(sex_map)

df['Sex_code']
0      1
1      0
2      0
3      0
4      1
      ..
886    1
887    0
888    0
889    1
890    1
Name: Sex_code, Length: 891, dtype: int64
def convert_sex(data):
    if data == 'male':
        return 1
    elif data == 'female':
        return 0
        
df['Sex'] = df['Sex'].apply(convert_sex)
df.head()

from sklearn.preprocessing import LabelEncoder

le = LabelEncoder()

LabelEncoder는 범주형 데이터를 정수형으로 변환하는 데 사용됩니다.

df['Embarked'].value_counts()

S    644
C    168
Q     77
Name: Embarked, dtype: int64
embarked = le.fit_transform(df['Embarked'])
embarked

array([2, 0, 2, 2, 2, 1, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 1, 2, 2, 0, 2, 2,
       1, 2, 2, 2, 0, 2, 1, 2, 0, 0, 1, 2, 0, 2, 0, 2, 2, 0, 2, 2, 0, 0,
       1, 2, 1, 1, 0, 2, 2, 2, 0, 2, 0, 2, 2, 0, 2, 2, 0, 3, 2, 2, 0, 0,
       2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
       2, 0, 2, 2, 0, 2, 1, 2, 0, 2, 2, 2, 0, 2, 2, 0, 1, 2, 0, 2, 0, 2,
       2, 2, 2, 0, 2, 2, 2, 0, 0, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 0, 2,
       2,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, 2, 2, 0, 2, 2, 2, 2, 2,
       0, 0, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 0,
       2, 2, 2, 2, 2, 1, 2, 2, 2, 0, 1])
le.classes_

array(['C', 'Q', 'S', nan], dtype=object)

le.classes_LabelEncoder 객체가 fit_transform 메서드를 통해 학습한 클래스들의 리스트를 나타냅니다.

✔️ 원 핫 인코딩(One Hot Encoding)

독립적인 데이터는 별도의 컬럼으로 분리하고 각각 컬럼에 해당 값에만 1, 나머지는 0값으로 갖게 하는 방법입니다.

# 라벨 인코딩
df['Embarked_num'] = LabelEncoder().fit_transform(df['Embarked'])
df.head()

# 원 핫 인코딩 수행
df = pd.get_dummies(df, columns=['Embarked'])


 

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df[feature],df[label],test_size= 0.2, random_state= 2023)
X_train.shape, y_train.shape
// ((712, 4), (712, 1))

X_test.shape, y_test.shape
// ((179, 4), (179, 1))
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

svc = SVC()
svc.fit(X_train, y_train)

y_pred = svc.predict(X_test)
print(accuracy_score(y_test, y_pred))
// 0.6480446927374302

정답률 : 64%

'AI' 카테고리의 다른 글

로지스틱 회귀  (0) 2023.12.27
의사 결정 나무(자전거 대여 예제)  (0) 2023.12.26
선형 회귀(랜트비 예측)  (1) 2023.12.26
사이킷런/아이리스 데이터셋 예제  (0) 2023.12.24
머신러닝과 딥러닝  (0) 2023.12.14