Home 빅분기 실기 대비 이기적 1주차 예상 문제 풀이 1
Post
Cancel

빅분기 실기 대비 이기적 1주차 예상 문제 풀이 1

csv파일을 주소로 알고 있다면 pandas csv_read에서 바로 주소를 넣으면 읽을 수 있을 겁니다.

작업형 1유형

데이터 출처 https://data.kma.go.kr/cmmn/static/staticPage.do?page=intro

데이터 설명 : 2020년도 이화동(서울) , 수영동(부산)의 시간단위의 기온과 강수량

데이터 url : https://raw.githubusercontent.com/Datamanim/datarepo/main/weather/weather2.csv

데이터 상위 5개 컬럼

img1 daumcdn

1
2
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/Datamanim/datarepo/main/weather/weather2.csv")

Q1. 여름철(6월,7월,8월) 이화동이 수영동보다 높은 기온을 가진 시간대는 몇개인가? 1415개

1
2
3
4
5
6
df.time = pd.to_datetime(df.time)
#time열을 datetime으로 형변환
summer = df.loc[df.time.dt.month.isin([6,7,8]).reset_index(drop=True)]
#isin을 통해서 month가 6,7,8월달인 값만 추출, 인덱스 재설정
len(summer.loc[summer['이화동기온'] > summer['수영동기온']])
#조건문을 통해서 해당 조건에 속하는 값만 가져오고 len은 행의 길이를 반환

Q2. 이화동과 수영동의 최대강수량의 시간대를 각각 구하여라

1
2
print(df.loc[df['이화동강수']==df['이화동강수'].max()].time.values)
print(df.loc[df['수영동강수']==df['수영동강수'].max()].time.values)

어떤 조건을 구할때는 .loc를 기억하시면 됩니다.

Pandas loc와 iloc차이

1
DataFrame.max(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)

max면 max지 왜 괄호가 들어갈까 생각이 들수도 있습니다. 다만 이번에는 열이 하나여서 그렇지 명시적으로 어떤 축인지 정해줘야할때도 있으며 보다 다양한 매개변수가 들어갈 때도 있습니다.

DataFrame.sum Return the sum over the requested axis.

DataFrame.min Return the minimum over the requested axis.

DataFrame.max Return the maximum over the requested axis.

DataFrame.idxmin Return the index of the minimum over the requested axis.

DataFrame.idxmax Return the index of the maximum over the requested axis.

max이외에도 sum, min 여러 종류가 있으며 dixmin의 경우 해당 최대 또는 최소 인덱스 값을 반환합니다. time이 고유한 인덱스 역할을 했다면 dixmin을 사용 했을 수도 있습니다.


작업형 2유형

데이터 출처 : https://www.kaggle.com/shubh0799/churn-modelling 에서 변형

데이터 설명 : 고객의 신상정보 데이터를 통한 회사 서비스 이탈 예측 (종속변수 : Exited)

문제타입 : 분류유형

평가지표 : f1-score

trainData url : https://raw.githubusercontent.com/Datamanim/datarepo/main/churn/train.csv

testData url : https://raw.githubusercontent.com/Datamanim/datarepo/main/churn/test.csv

subData url : https://raw.githubusercontent.com/Datamanim/datarepo/main/churn/submission.csv

*이번 데이터는 결측값이 없습니다.

데이터 상위 5개 컬럼

data view

1
2
3
4
5
6
7
8
9
10
11
trainData  = 'https://raw.githubusercontent.com/Datamanim/datarepo/main/churn/train.csv'
testData  = 'https://raw.githubusercontent.com/Datamanim/datarepo/main/churn/test.csv'
subData  = 'https://raw.githubusercontent.com/Datamanim/datarepo/main/churn/submission.csv'


#데이터로드
import pandas as pd

train = pd.read_csv(trainData)
test = pd.read_csv(testData)
submission = pd.read_csv(subData,index_col=0)

데이터 부터 살펴봅시다. 일단 먼저 RowNumber, CustomerId, Surname등 예측과는 큰 상관이 없는 변수들이 보입니다. 이들을 모두 드랍하고 시작을 합시다.

1
2
3
drop_feature = ['RowNumber','CustomerId','Surname']
train.drop(columns=drop_feature, inplace=True)
test.drop(columns=drop_feature, inplace=True)

train데이터와 test데이터도 똑같이 드랍을 해줍시다. inplace에 True를 하면 바로 반영이되고 False는 반영을 하지 않습니다.

1
y = train.pop('Exited')

하는김에 y데이터도 분리를 해줍시다.

1
2
3
4
5
6
7
8
Stand_feature = ['CreditScore','Age','Balance','EstimatedSalary']
from sklearn.preprocessing import StandardScaler
Scaler = StandardScaler()
Scaler.fit(train[Stand_feature])
train[Stand_feature] = Scaler.transform(train[Stand_feature])
test[Stand_feature] = Scaler.transform(test[Stand_feature])
train = pd.get_dummies(train)
test = pd.get_dummies(test)

육안으로 보았을때 범위의 크기가 작은 값을 제외하고 나머지 이산값의 열을 꺼내와서 표준화를 처리 했습니다. 그리고 범주형은 원핫인코딩을 합니다. 여기서 주의하실 것은 표준화 처리를 할때 train데이터를 기준으로 fit를 했으면 test는 새로 fit하는 것이 아닌 trian기준으로 transform을 그대로 진행해야 합니다.

1
2
3
4
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.fit(X_train,y)
model.score(X_train,y)

이탈하는가 아닌가 0,1 두가지로 분류하는 문제입니다. 랜덤포레스트분류로 하겠습니다.

훈련데이터에서 성능은 100%가 나오는군요, 그런데 데이터를 분리해서 살펴보면 56%로 추락하기때문에 오버피팅이 심각한 수준입니다. 하지만 여기서는 일단 해본다는 느낌으로 진행할 것이기 때문에 하이퍼라라미터튜닝이나 배깅은 생략하고 넘어가겠습니다.

1
2
3
4
5
pred_test=model.predict(X_test)
test = pd.read_csv(trainData)
summit['CustomerId'] = test['CustomerId']
summit['Exited'] = pred_test
summit.to_csv('Pre_Exited.csv', index=False)

csv파일로 저장하는것 까지 해보았습니다. test데이터를 다시 불러온 이유는 앞에서 전처리를 하면서 CustomerId를 날려버렸기 때문인데 처음에 하셔도되고 햇갈린다 싶으시면 나중에 하셔도 됩니다. 따로 성능 측정은 하지 않겠습니다.

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.

빅분기 실기 훈련데이터 추출 후 표준편차 구하기

빅분기 실기 대비 이기적 1주차 예상 문제 풀이 2