■ 타이타닉 데이터를 knn 으로 수행했을때
#1. 필요한 패키지를 import 한다.
import pandas as pd
import seaborn as sns
#1단계. csv ---> 데이터 프레임으로 변환
df = sns.load_dataset('titanic')
# 컬럼이 모두다 출력될 수 있도록 출력할 열의 개수 한도를 늘리기
pd.set_option('display.max_columns', 15 )
print (df.head() )
print ( df.info() )
print ( '\n' )
print ( df.isnull().sum( axis=0) )
rdf = df.drop(['deck', 'embark_town'] , axis= 1)
print ( rdf.columns.values )
# 나이의 누락 데이터의 행을 삭제해라 ~
rdf = rdf.dropna( subset=['age'], how='any', axis= 0 )
print ( len(rdf) )
print ('\n')
# 정박한 항구의 누락 데이터 2건을 최빈값으로 치환
most_freq = rdf['embarked'].value_counts(dropna=True).idxmax()
rdf['embarked'].fillna( most_freq, inplace=True )
print ( rdf.isnull().sum(axis=0) )
ndf = rdf[ ['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'embarked']]
print ( ndf.head() )
# 명목형 데이터를 숫자로 변환하기 위해 더미변수를 생성한다.
gender = pd.get_dummies( ndf['sex'] )
ndf = pd.concat( [ndf, gender], axis=1 )
# 명목형 데이터를 숫자로 변환하기 위해 더미변수를 생성한다.
onehot_embarked = pd.get_dummies( ndf['embarked'], prefix='town')
ndf = pd.concat([ ndf, onehot_embarked], axis=1)
ndf
# 명목형 컬럼 2개를 삭제한다.
ndf.drop( ['sex', 'embarked'], axis=1, inplace=True )
print ( ndf.head() )
# 훈련할 학습 데이터 X 와 정답이 있는 라벨 y 를 생성한다.
X = ndf[ [ 'pclass' ,'age', 'sibsp','parch', 'female', 'male', 'town_C', 'town_Q', 'town_S']]
y = ndf['survived'] # 종속변수
y # 0 이 생존자 1이 사망자
#4.2 독립변수들을 표준화 한다.
from sklearn import preprocessing
X = preprocessing.StandardScaler().fit(X).transform(X)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test =train_test_split( X, y, test_size=0.3,
random_state = 10 )
# 설명: test_size=0.3 에 의해서 7:3 비율로 훈련과 테스트를 나누고
# random_state=10 에 의해서 나중에 split 할 때도 항상 일정하게
# split 할 수 있게 한다.
print ( 'train data 의 갯수:' , X_train.shape )
print ( 'test data 의 갯수:' , X_test.shape )
# knn 머신러닝 모델로 학습 시킨다.
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier( n_neighbors=5 )
knn.fit ( X_train, y_train )
# 테스트 데이터 대한 사망자와 생존자를 예측한다.
y_hat = knn.predict( X_test )
# 모델 평가를 위해 이원 교차표를 그린다.
from sklearn import metrics
knn_matrix = metrics.confusion_matrix( y_test, y_hat )
print ( knn_matrix )
# 모델의 정확도를 확인한다.
from sklearn.metrics import accuracy_score
accuracy = accuracy_score( y_test, y_hat)
print(accuracy)
[[109 16]
[ 24 66]]
0.813953488372093
결과:
train data 의 갯수: (499, 9)
test data 의 갯수: (215, 9)
[[109 16]
[ 25 65]]
0.8093023255813954