빅데이터분석기사/작업형2

[작업형2] 자동차 시장 세분화(분류)

seo0seok 2023. 6. 24. 03:17

// 퇴근후딴짓 님의 강의를 참고하였습니다. //

 

Dataset :

test.csv
0.11MB
train.csv
0.35MB

 

문제) 신규 고객이 어떤 분류에 속할지 예측하여 다음과 같은 형식으로 제출하시오.

  • 자동차 회사는 새로운 전략을 수립하기 위해 4개의 시장으로 세분화했습니다.
  • 기존 고객 분류 자료를 바탕으로 신규 고객이 어떤 분류에 속할지 예측해주세요!
  • 예측할 값(y): "Segmentation" (1,2,3,4)
  • 평가: Macro f1-score
  • data: train.csv, test.csv

 

문제1-1) 수치형 변수만 사용 (초급자)

 

1. EDA

# 라이브러리 불러오기
import pandas as pd
train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")
print(train.shape, test.shape)
train.head()

실행 결과 : 
(6665, 11) (2154, 10)

→ 11개의 컬럼으로 이루어져있다. 'Segmentation' 컬럼은 Target 컬럼이다.

 

train.info()
train.nunique()

실행 결과 :
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6665 entries, 0 to 6664
Data columns (total 11 columns):
 #   Column           Non-Null Count  Dtype  
---  ------           --------------  -----  
 0   ID               6665 non-null   int64  
 1   Gender           6665 non-null   object 
 2   Ever_Married     6665 non-null   object 
 3   Age              6665 non-null   int64  
 4   Graduated        6665 non-null   object 
 5   Profession       6665 non-null   object 
 6   Work_Experience  6665 non-null   float64
 7   Spending_Score   6665 non-null   object 
 8   Family_Size      6665 non-null   float64
 9   Var_1            6665 non-null   object 
 10  Segmentation     6665 non-null   int64  
dtypes: float64(2), int64(3), object(6)

ID                 6665
Gender                2
Ever_Married          2
Age                  67
Graduated             2
Profession            9
Work_Experience      15
Spending_Score        3
Family_Size           9
Var_1                 7
Segmentation          4
dtype: int64

→ 수치형 컬럼은 5개가 있다.

 

train.isnull().sum()

실행 결과 :
ID                 0
Gender             0
Ever_Married       0
Age                0
Graduated          0
Profession         0
Work_Experience    0
Spending_Score     0
Family_Size        0
Var_1              0
Segmentation       0
dtype: int64
test.isnull().sum()

실행 결과 : 
ID                 0
Gender             0
Ever_Married       0
Age                0
Graduated          0
Profession         0
Work_Experience    0
Spending_Score     0
Family_Size        0
Var_1              0
dtype: int64

→ train, test 데이터 모두 결측치는 없다.

 

2. 전처리

# target(y, label) 값 복사
target = train.pop('Segmentation')
target

실행 결과 :
0       4
1       2
2       2
3       3
4       3
       ..
6660    2
6661    4
6662    4
6663    2
6664    2
Name: Segmentation, Length: 6665, dtype: int64

→ Target으로 사용할 'Segmentation' 컬럼은 train 데이터에서 pop() 함수를 사용해 따로 뽑아두고 데이터에서는 삭제한다.

 

# test데이터 ID 복사
test_ID = test.pop('ID')

→ 제출용 데이터프레임에 사용할 'ID' 컬럼을 'test_ID' 변수에 담아 두고 데이터에서는 삭제한다.

 

# 수치형 컬럼(train)
# ['ID', 'Age', 'Work_Experience', 'Family_Size', 'Segmentation']
num_cols = ['Age', 'Work_Experience', 'Family_Size']
train = train[num_cols]

→ 수치형 컬럼 5개 중 'ID' 컬럼은 사용하지 않아 미포함시키고, 'Segmentation' 컬럼은 Target으로 미포함시킨다.

 

3. model 학습 및 예측

# 모델 선택 및 학습
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(random_state=0)
rf.fit(train, target)
pred = rf.predict(test)
pred

실행 결과 : 
array([2, 3, 3, ..., 4, 3, 1])

→ 랜덤포레스트 모델로 train 데이터와 target을 학습 시키고 test 데이터를 예측하면 1~4로 분류된다.

 

4. csv파일 제출

pd.DataFrame({'ID': test_ID, 'Segmentation': pred}).to_csv('수험번호.csv', index=False)

→ 문제에서 제시한 형식대로 'ID'와 'Segmentation' 컬럼에 test_ID와 pred값을 넣어 데이터프레임으로 만든 후 제출

 

 

 

문제1-2) 범주형(카테고리) 활용 (중급자)

 

1. EDA

# 라이브러리 불러오기
import pandas as pd
train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")
train.info()

실행 결과 : 
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6665 entries, 0 to 6664
Data columns (total 11 columns):
 #   Column           Non-Null Count  Dtype  
---  ------           --------------  -----  
 0   ID               6665 non-null   int64  
 1   Gender           6665 non-null   object 
 2   Ever_Married     6665 non-null   object 
 3   Age              6665 non-null   int64  
 4   Graduated        6665 non-null   object 
 5   Profession       6665 non-null   object 
 6   Work_Experience  6665 non-null   float64
 7   Spending_Score   6665 non-null   object 
 8   Family_Size      6665 non-null   float64
 9   Var_1            6665 non-null   object 
 10  Segmentation     6665 non-null   int64  
dtypes: float64(2), int64(3), object(6)

→ 6개의 object형 컬럼이 있다.

 

2. 전처리

# 원핫 인코딩
train = pd.get_dummies(train)
test = pd.get_dummies(test)

→ train, test 데이터를 get_dummies() 함수를 사용해 원핫 인코딩을 진행한다.

 

# target(y, label) 값 복사
target = train.pop('Segmentation')
target

→ Target으로 사용할 'Segmentation' 컬럼은 train 데이터에서 pop() 함수를 사용해 따로 뽑아두고 데이터에서는 삭제한다.

 

train = train.drop("ID", axis=1)
test_ID = test.pop('ID')

→ train 데이터에서 사용하지 않는 'ID' 컬럼을 삭제한다.

→ 제출용 데이터프레임에 사용할 'ID' 컬럼을 'test_ID' 변수에 담아 두고 데이터에서는 삭제한다.

 

3. model 학습 및 예측

# 모델 선택 및 학습
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(random_state=0)
rf.fit(train, target)
pred = rf.predict(test)
pred

실행 결과 :
array([1, 3, 3, ..., 2, 3, 4])

→ 랜덤포레스트 모델로 train 데이터와 target을 학습 시키고 test 데이터를 예측하면 1~4로 분류된다.

 

4. csv파일 제출

pd.DataFrame({'ID': test_ID, 'Segmentation': pred}).to_csv('수험번호.csv', index=False)

→ 문제에서 제시한 형식대로 'ID'와 'Segmentation' 컬럼에 test_ID와 pred값을 넣어 데이터프레임으로 만든 후 제출