본문 바로가기
카테고리 없음

EDA(Exploratory Data Analysis) 베이스라인

by pgh95319 2023. 5. 7.

https://www.kaggle.com/code/ash316/eda-to-prediction-dietanic

 

EDA To Prediction(DieTanic)

Explore and run machine learning code with Kaggle Notebooks | Using data from Titanic - Machine Learning from Disaster

www.kaggle.com

 

캐글의 EDA To Prediction (DieTanic) 글에서, ADP 실기 시험에서 EDA 파이프라인으로 사용할 내용을 정리하였습니다.


- 데이터 훑기

data.info()
data.describe()

data.isnull().sum() #checking for total null values
data.Age.isnull().any() # 결측치 데이터 채운 후, 결측치 확인, False 나오면 결측치 이상 없음.

 

 

- Target 데이터 범주별 시각화하기

f,ax=plt.subplots(1,3,figsize=(18,8)) # 파이 그래프
data['target'].value_counts().plot.pie(explode=[0,0.1],autopct='%1.1f%%',ax=ax[0],shadow=True)
ax[0].set_title('target')
ax[0].set_ylabel('')

sns.countplot('target',data=data,ax=ax[1]) # 빈도 그래프
ax[1].set_title('target')
plt.show()

sns.countplot('범주형 데이터',hue='범주형 데이터',data=data,ax=ax[2]) # 빈도 그래프 + hue : 한 그래프에 여러 범주별 빈도 표현
plt.show()

 

- Categorical Features (범주형 데이터) 분석

data.groupby(['범주형 데이터','target'])['target'].count() # 범주별 target별 target 데이터 수

f,ax=plt.subplots(1,2,figsize=(18,8)) # 막대 그래프
data[['범주형 데이터','target']].groupby(['범주형 데이터']).mean().plot.bar(ax=ax[0])
ax[0].set_title('target vs 범주형 데이터')

sns.countplot('범주형 데이터',hue='target',data=data,ax=ax[1]) # 빈도 그래프
ax[1].set_title('범주형 데이터:target 0 vs target 1')
plt.show()

 

- Ordinal Features (순서형 데이터) 분석

pd.crosstab(data['순서형 데이터'],data['target'], margins=True).style.background_gradient(cmap='summer_r')

f,ax=plt.subplots(1,2,figsize=(18,8)) # 막대 그래프
data['순서형 데이터'].value_counts().plot.bar(color=['순서형 데이터 범주 수 만큼'],ax=ax[0])
ax[0].set_title('Count By 순서형 데이터')
ax[0].set_ylabel('Count')
sns.countplot('순서형 데이터',hue='target',data=data,ax=ax[1])
ax[1].set_title('순서형 데이터:target 0 vs target 1')
plt.show()

# cross tab 히트맵
pd.crosstab([data['범주형 데이터'], data['target'], data['범주형 데이터'], margins=True).style.background_gradient(cmap='summer_r')   
pd.crosstab([data['범주형 데이터'],data['순서형 데이터']],[data['범주형 데이터']],data['target']]],margins=True).style.background_gradient(cmap='summer_r')

# factorplot -> 3개 차원의 그래프. hue는 한 그래프에 범주형 데이터별로 표현
sns.factorplot('순서형 데이터','target',hue='범주형 데이터',data=data)
plt.show()

# factorplot -> 3개 차원의 그래프.  col은 col 변수별로 여러 그래프가 형성됨. hue는 없음.
sns.factorplot('순서형 데이터','target',col='범주형 데이터',data=data)
plt.show()

# factorplot 4개 차원 그래프. col 변수별 여러 그래프 형성. 한 그래프에 hue 범주별 데이터 표현
sns.factorplot('순서형 데이터','target',hue='범주형 데이터',col='범주형 데이터',data=data)
plt.show()

 

- Continuous Features (연속형 데이터) 분석

# max, min, mean
data['연속형 데이터'].max(), data['연속형 데이터'].min(), data['연속형 데이터'].mean()

# 바이올린 플롯
f,ax=plt.subplots(1,2,figsize=(18,8))
sns.violinplot("순서형 데이터","연속형 데이터", hue="target", data=data,split=True,ax=ax[0])
ax[0].set_title('순서형 데이터 and 연속형 데이터 vs target')
ax[0].set_yticks(range(0,110,10))

sns.violinplot("범주형 데이터","연속형 데이터", hue="target", data=data,split=True,ax=ax[1])
ax[1].set_title('범주형 데이터 and 연속형 데이터 vs target')
ax[1].set_yticks(range(0,110,10))
plt.show()

# 히스토그램
f,ax=plt.subplots(1,2,figsize=(20,10))
data[data['target']==0].'연속형 데이터'.plot.hist(ax=ax[0],bins=20,edgecolor='black',color='red')
ax[0].set_title('target= 0')
x1=list(range(0,85,5))
ax[0].set_xticks(x1)

data[data['target']==1].'연속형 데이터'.plot.hist(ax=ax[1],color='green',bins=20,edgecolor='black')
ax[1].set_title('target= 1')
x2=list(range(0,85,5))
ax[1].set_xticks(x2)
plt.show()

# 히스토그램 + distplot 분포, 순서형 데이터 조건을 만족하는 연속형 데이터의 히스토그램 분포
sns.distplot(data[data['순서형 데이터']==1]['연속형 데이터'])
plt.show()

 

- 범주형데이터 히트맵 시각화

data.drop(['범주형 데이터 목록들'],axis=1,inplace=True)
sns.heatmap(data.corr(),annot=True,cmap='RdYlGn',linewidths=0.2) #data.corr()-->correlation matrix
fig=plt.gcf()
fig.set_size_inches(10,8)
plt.show()

 

- 분류 알고리즘

'''
1)Logistic Regression
2)Support Vector Machines(Linear and radial)
3)Random Forest
4)K-Nearest Neighbours
5)Gaussian Naive Bayes
6)Decision Tree
'''

# importing all the required ML packages
from sklearn.linear_model import LogisticRegression #logistic regression
from sklearn import svm #support vector Machine
from sklearn.ensemble import RandomForestClassifier #Random Forest
from sklearn.neighbors import KNeighborsClassifier #KNN
from sklearn.naive_bayes import GaussianNB #Naive bayes
from sklearn.tree import DecisionTreeClassifier #Decision Tree
from sklearn.model_selection import train_test_split #training and testing data split
from sklearn import metrics #accuracy measure
from sklearn.metrics import confusion_matrix #for confusion matrix

 

- Cross Validation

 

- Confusion Matrix

 

- Hyper-Parameters Tuning

 

- Voting Classifier, Bagging, Boosting