Part1. Chapter 02 - 우리 애는 머리는 좋은데, 공부를 안해서 그래요

2023. 3. 7. 11:46Python/Kaggle

Step 1. 데이터셋 준비하기

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

Colab Notebook에 Kaggle API 세팅하기

import os

# os.environ을 이용하여 Kaggle API Username, Key 세팅하기
os.environ['KAGGLE_USERNAME'] = 'jhighllight'
os.environ['KAGGLE_KEY'] = 'xxxxxxxxxxxxxxxxxxxxxx'

데이터 다운로드 및 압축 해제하기

# Linux 명령어로 Kaggle API를 이용하여 데이터셋 다운로드하기 (!kaggle ~)
# Linux 명령어로 압축 해제하기
!kaggle datasets download -d aljarah/xAPI-Edu-Data
! unzip '*.zip'

xAPI-Edu-Data.zip: Skipping, found more recently modified local copy (use --force to force download) Archive: xAPI-Edu-Data.zip replace xAPI-Edu-Data.csv? [y] es, [n] o, [A] ll, [N] one, [r] ename:

 

Pandas 라이브러리로 csv파일 읽어 들이기

# pd.read_csv()로 csv파일 읽어들이기
df = pd.read_csv('/content/xAPI-Edu-Data.csv')

df

Step 2. EDA 및 데이터 기초 통계 분석

데이터프레임의 각 칼럼 분석하기

# DataFrame에서 제공하는 메소드를 이용하여 컬럼 분석하기 (head(), info(), describe())
df.head()

df.info()

 

df.describe()

df.columns

df['gender'].value_counts()

df['NationalITy'].value_counts()

df['PlaceofBirth'].value_counts()

수치형 데이터의 히스토그램 그리기

df.columns

# seaborn의 histplot, jointplot, pairplot을 이용해 히스토그램 그리기
sns.histplot(x='raisedhands', data=df, hue='Class', hue_order=['L', 'M', 'H'], kde=True)

<AxesSubplot:xlabel='raisedhands', ylabel='Count'>

sns.histplot(x='VisITedResources', data=df, hue='Class', hue_order=['L', 'M', 'H'], kde=True)

<AxesSubplot:xlabel='VisITedResources', ylabel='Count'>

sns.jointplot(x='VisITedResources', y='raisedhands', data=df, hue='Class', hue_order=['L', 'M', 'H'])

<seaborn.axisgrid.JointGrid at 0x7 f83 cf86 a220>

sns.histplot(x='AnnouncementsView', data=df, hue='Class', hue_order=['L', 'M', 'H'], kde=True)

<AxesSubplot:xlabel='AnnouncementsView', ylabel='Count'>

sns.histplot(x='Discussion', data=df, hue='Class', hue_order=['L', 'M', 'H'], kde=True)

<AxesSubplot:xlabel='Discussion', ylabel='Count'>

sns.pairplot(df, hue='Class', hue_order=['L', 'M', 'H'])

 

<seaborn.axisgrid.PairGrid at 0x7 f83 cf4 efc40>

Countplot을 이용하여 범주별 통계 확인하기

# seaborn의 countplot()을 사용
# Hint) x와 hue를 사용하여 범주별 Class 통계 확인
sns.countplot(x='Class', data=df, order=['L', 'M', 'H'])
 <AxesSubplot:xlabel='Class', ylabel='count'>

sns.countplot(x='gender', data=df, hue='Class', hue_order=['L', 'M', 'H'])

<AxesSubplot:xlabel='gender', ylabel='count'>

df.columns

sns.countplot(x='NationalITy', data=df, hue='Class', hue_order=['L', 'M', 'H'])
plt.xticks(rotation=90)
plt.show()

sns.countplot(x='ParentAnsweringSurvey', data=df, hue='Class', hue_order=['L', 'M', 'H'])

<AxesSubplot:xlabel='ParentAnsweringSurvey', ylabel='count'>

sns.countplot(x='ParentschoolSatisfaction', data=df, hue='Class', hue_order=['L', 'M', 'H'])

<AxesSubplot:xlabel='ParentschoolSatisfaction', ylabel='count'>

sns.countplot(x='Topic', data=df, hue='Class', hue_order=['L', 'M', 'H'])
plt.xticks(rotation=90)
plt.show()

범주형 대상 Class 칼럼을 수치로 바꾸어 표현하기

# L, M, H를 숫자로 바꾸어 표현하기 (eg. L: -1, M: 0, H:1)
# Hint) DataFrame의 map() 메소드를 사용

df['Class_value'] = df['Class'].map(dict(L=-1, M=0, H=1))
df.head()

# 숫자로 바꾼 Class_value 컬럼을 이용해 다양한 시각화 수행하기
gb = df.groupby('gender').mean()['Class_value']
plt.bar(gb.index, gb)

<BarContainer object of 2 artists>

gb = df.groupby('Topic').mean()['Class_value'].sort_values()
plt.barh(gb.index, gb)

<BarContainer object of 12 artists>

gb = df.groupby('StudentAbsenceDays').mean()['Class_value'].sort_values(ascending=False)
plt.bar(gb.index, gb)

<BarContainer object of 2 artists>

Step 3. 모델 학습을 위한 데이터 전처리

get_dummies()를 이용하여 범주형 데이터 전처리하기

df.columns

# pd.get_dummies()를 이용해 범주형 데이터를 one-hot 벡터로 변환하기
# Hint) Multicollinearity를 피하기 위해 drop_first=True로 설정
X = pd.get_dummies(df.drop(['ParentschoolSatisfaction', 'Class', 'Class_value'], axis=1),
                   columns=['gender', 'NationalITy', 'PlaceofBirth',
                            'StageID', 'GradeID','SectionID', 'Topic',
                            'Semester', 'Relation', 'ParentAnsweringSurvey',
                            'StudentAbsenceDays'],
                   drop_first=True)
y = df['Class']

학습데이터와 테스트데이터 분리하기

from sklearn.model_selection import train_test_split
# train_test_split() 함수로 학습 데이터와 테스트 데이터 분리하기
X_train, X_test, y_train, y_test =  train_test_split(X, y, test_size=0.3, random_state=1)

Step 4. Classification 모델 학습하기

Logistic Regression 모델 생성/학습하기

from sklearn.linear_model import LogisticRegression
# LogisticRegression 모델 생성/학습
model_lr = LogisticRegression(max_iter=10000)
model_lr.fit(X_train, y_train)

모델 학습 결과 평가하기

from sklearn.metrics import classification_report
# Predict를 수행하고 classification_report() 결과 출력하기
pred = model_lr.predict(X_test)
print(classification_report(y_test, pred))

Step5 모델 학습 결과 심화 분석하기

Logistic Regression 모델 계수로 상관성 파악하기

model_lr.classes_

model_lr.coef_.shape

# Logistic Regression 모델의 coef_ 속성을 plot하기
fig = plt.figure(figsize=(15, 8))
plt.bar(X.columns, model_lr.coef_[0, :])
plt.xticks(rotation=90)
plt.show()

# Logistic Regression 모델의 coef_ 속성을 plot하기
fig = plt.figure(figsize=(15, 8))
plt.bar(X.columns, model_lr.coef_[1, :])
plt.xticks(rotation=90)
plt.show()

XGBoost 모델로 특징의 중요도 확인하기

# XGBoost 모델의 feature_importances_ 속성을 plot하기
fig = plt.figure(figsize=(15, 8))
plt.bar(X.columns, model_xgb.feature_importances_)
plt.xticks(rotation=90)
plt.show()