컴공생 누르지 마세요! 컴공생 울어요.
[ML] HA1 part1 (2) Logistic regression with Titanic dataset 본문
[ML] HA1 part1 (2) Logistic regression with Titanic dataset
당도최고치악산멜론 2022. 12. 19. 14:24📢 학교 수업에서 수행한 과제입니다.
이번 게시글에서는 titanic dataset에 대해 Logistic Regression model을 학습시킬 것이다.
구글 코랩을 이용하였으며, 전체 코드는 지난 게시글을 참고하라.
* 지난 게시글
[ML] HA1 part1 (1) Linear Regression with Startup dataset
https://kwonppo.tistory.com/34
[ML] HA1 part1 (1) Linear Regression with Startup dataset
HA1 part1은 Linear Regression, Logistice Regression, GDA를 이용한 practice이다. 이번 게시글에서는 startup dataset을 이용한 Linear Regression을 수행할 것이다. 0. 실행 환경 구글에서 제공하는 jupyter notebook인 구글
kwonppo.tistory.com
2. Logistic regression with Titanic dataset
우선 titanic.csv 데이터셋을 가져온다.
!wget wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=1Z-IGKwjJ2z-tzJUFa9pWmG3BdMULbTqm' -O titanic.csv
df2 = pd.read_csv('titanic.csv')
df2.head()

이때 'Survived'는 해당 passenger가 살았는지 죽었는지를 나타낸다.
이제 data preprocessing을 수행할 것이다. 'Pclass', 'Sex', 'Age'가 more important feature이기 때문에 다음과 같이 전처리를 수행한다.
# In Sex, string type used, convert this to 1 or 0
df2['Sex'] = df2['Sex'].map({'female':1,'male':0})
# In Age, there are missing values. Fill them with average values
df2['Age'].fillna(value=df2['Age'].mean(), inplace=True)
# For further simplicity, divide Pclass into "First class" and "Second class" to use boolean values
df2['FirstClass'] = df2['Pclass'].apply(lambda x: 1 if x == 1 else 0)
df2['SecondClass'] = df2['Pclass'].apply(lambda x: 1 if x == 2 else 0)
X = df2[['Sex', 'Age', 'FirstClass', 'SecondClass']]
y = df2['Survived']
# As LR provided by sklearn uses L2 norm as the penalty (by default), the predictor tends to depend on the inputted feature scale
# Also, the scaler helps better prediction when the data points are spread out
from sklearn.preprocessing import StandardScaler
def scaler_samples(train_X,test_X):
scaler = StandardScaler()
train_X = scaler.fit_transform(train_X)
test_X = scaler.transform(test_X)
return train_X, test_X
이제 본격적으로 training을 수행할 것이다. 주어진 feature에 대해 해당 passenger가 살 수 있을지 없을지를 predict하는 calssifier를 학습해보겠다.
우선 데이터셋을 train set과 test set으로 나눈다. 오버 피팅을 방지하기 위해 train set으로 모델을 학습하고, test set으로 모델을 평가한다.
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size= 0.25, random_state=0)
그 다음, StandardScaler를 이용하여 모든 data points가 mean = 0, std = 1이 되도록 매핑한다.
x_train, x_test = scaler_samples(x_train, x_test)
이제 train set을 이용하여 LR classifier를 학습한다.
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(random_state=0).fit(x_train, y_train)
test set으로 classifier를 테스트해보자.
# test a trained LR classifier using testing set
clf.predict(x_test)
# report the testing accuracy
print('testing accuracy:', clf.score(x_test, y_test))

위와 같은 accuracy가 나왔다.
이제 coefficients 값을 확인해보자.
# coefficients
print(clf.coef_)

coefficient의 절댓값이 클 수록 prediction에 더 많은 영향을 끼친다. 따라서 features 중에서 coeffiecients의 절댓값이 가장 큰 passengers' sex가 가장 중요함을 알 수 있다.
이제 재미 삼아서 내 프로필을 기반으로 prediction을 수행해보자.
ME = np.array([1.0, 23.0, 1.0, 0.0]) # my profile
clf.predict(ME.reshape(1, -1))
그 결과 0이 나왔다. 내가 만약 타이타닉호에 탔었다면 나는 바다에 수장되었을 것이다.
'STUDY > 기계학습' 카테고리의 다른 글
[ML] HA2 part1 (1) Decision trees with Breast cancer dataset (1) | 2022.12.19 |
---|---|
[ML] HA1 part2 Support vector machines with Iris dataset (0) | 2022.12.19 |
[ML] HA1 part1 (3) Gaussian discriminant analysis (Gaussian Naive Bayes) with iris dataset (0) | 2022.12.19 |
[ML] HA1 part1 (1) Linear Regression with Startup dataset (0) | 2022.12.19 |
[ML] Machine Learning Lab Practice Archiving (0) | 2022.12.19 |