자격증/빅데이터분석기사

[빅분기] 실기 시험까지 D-1, 시험환경은 뭔가 어렵다.

mabb 2021. 12. 3. 02:22
반응형

 안녕하세요. 삶의질을 높이기 위해 노력하는 영차영차입니다.
빅데이터분석기사 실기 시험을 위한 본인의 메모 및 공부 목적 포스팅입니다.

시험환경에서 중요한 것.
print로 corr ,discribe, groupby등을 확인하여 특성치를 분석할 때
쥬피터컴퓨터처럼 데이터프레임 형태로 보여주지 않아 가독성이 떨어짐.
그리고 값이 칸을 넘어갈 경우 ...으로 생략이 됨.

pd.set_option('display.max_columns',None)  이 필수.

피디.셋_옵션('디스플레이.맥스_칼럼'.논)

이건 help나 dir로 못보니 그냥 외워야할듯...

 

 

# 출력을 원하실 경우 print() 함수 활용
# 예시) print(df.head())

# getcwd(), chdir() 등 작업 폴더 설정 불필요
# 파일 경로 상 내부 드라이브 경로(C: 등) 접근 불가

# 데이터 파일 읽기 예제
import pandas as pd
X_test = pd.read_csv("data/X_test.csv")
X_train = pd.read_csv("data/X_train.csv")
y_train = pd.read_csv("data/y_train.csv")

pd.set_option('display.max_columns',None)
pd.options.display.float_format = '{:.2f}'.format



#결측치 및 이상값 존재/ 결측치부터 처리, 환불금액의 결측값은 환불이 없는 것으로 간주하여 0으로 변경
X_train['환불금액'] = X_train['환불금액'].fillna(0)
X_test['환불금액'] = X_test['환불금액'].fillna(0)

#이상값 처리/ iqr넘는 값은 iqr 경계값으로 대체
#구매액이 -인 값 0으로 대체

#print(X_train[X_train['총구매액'] < 0].index) # 1659,3174,3488
X_train.loc[1659,'총구매액'] = 0
X_train.loc[3174,'총구매액'] = 0
X_train.loc[3488,'총구매액'] = 0

#print(X_train[X_train['최대구매액'] < 0].index) # 1659
X_train.loc[1659,'최대구매액'] = 0

#print(X_test[X_test['최대구매액'] < 0].index) # 579,1177 / 579,1177
X_test.loc[579,'총구매액'] = 0
X_test.loc[1177,'총구매액'] = 0
X_test.loc[579,'최대구매액'] = 0
X_test.loc[1177,'최대구매액'] = 0

#환불금액은 환불여부로 변경해볼까
a = X_train['환불금액'] > 0
X_train.loc[a,'환불금액'] = 1

a = X_test['환불금액'] > 0
X_test.loc[a,'환불금액'] = 1

#print(X_test['환불금액'])

# test셋 custid 저장
X_test_custid = X_test[['cust_id']]

#특성치 분석

data = pd.concat((X_train,y_train),axis = 1)
#print(data.groupby(['최대구매액'])['gender'].mean())
#print(data[['최대구매액','총구매액']].corr()) # 다중공선성 제거

#cust_id 제거

X_train = X_train.drop(columns = ['cust_id'])
X_test = X_test.drop(columns = ['cust_id'])
y_train = y_train.drop(columns = ['cust_id'])

#print(X_train.head())

#LabelEncoder
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()

X_train['주구매상품'] = encoder.fit_transform(X_train['주구매상품'])
X_train['주구매지점'] = encoder.fit_transform(X_train['주구매지점'])

X_test['주구매상품'] = encoder.fit_transform(X_test['주구매상품'])
X_test['주구매지점'] = encoder.fit_transform(X_test['주구매지점'])


#print(X_train['주구매상품'].nunique())  # 42 항목
#print(X_test['주구매상품'].nunique())  # 41 항목

'''
data2 = pd.concat((X_train,X_test),axis = 0).reset_index(drop=True)
data2['주구매상품'] = encoder.fit_transform(data2['주구매상품'])
X_train['주구매상품'] = data2.loc[:3499,'주구매상품']
X_test['주구매상품'] = data2.loc[3500:,'주구매상품']

data2['주구매지점'] = encoder.fit_transform(data2['주구매지점'])
X_train['주구매지점'] = data2.loc[:3499,'주구매지점']
X_test['주구매지점'] = data2.loc[3500:,'주구매지점']
#print(X_train.head())
'''

#수치형 변수끼리의 통계수치 차이가 크므로 정규화해준다.

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)


#데이터 세트 나누기

from sklearn.model_selection import train_test_split
X_TRAIN,X_TEST,Y_TRAIN,Y_TEST = train_test_split(X_train_scaled,y_train,test_size = 0.2,stratify = y_train,
 random_state = 36)

# 모델 적용하기 / 로지스틱회귀와 랜덤포레스트 이용하기
'''
from sklearn.linear_model import LogisticRegression
model_lr = LogisticRegression()
model_lr.fit(X_TRAIN,Y_TRAIN)
print(model_lr.score(X_TRAIN,Y_TRAIN))
print(model_lr.score(X_TEST,Y_TEST))
'''

from sklearn.ensemble import RandomForestClassifier
model_rfc = RandomForestClassifier(random_state = 36)
model_rfc.fit(X_TRAIN,Y_TRAIN)
print(model_rfc.score(X_TRAIN,Y_TRAIN))
print(model_rfc.score(X_TEST,Y_TEST))

X_test_proba = pd.DataFrame(model_rfc.predict_proba(X_test))

#파일 제출하기
ans = pd.concat((X_test_custid,X_test_proba[1]),axis =1)
ans.rename(columns = {'cust_id':'custid',1:'gender'},inplace = True)

ans.to_csv('910306.csv',index=False)



#범주형 변수 / 주구매상품, 주구매지점



# 사용자 코딩














# 답안 제출 참고
# 아래 코드 예측변수와 수험번호를 개인별로 변경하여 활용
# pd.DataFrame({'cust_id': X_test.cust_id, 'gender': pred}).to_csv('003000000.csv', index=False)

반응형