4 분 소요

자동차 구매 가격 예측

PROBLEM STATEMENT

다음과 같은 컬럼을 가지고 있는 데이터셋을 읽어서, 어떠한 고객이 있을때, 그 고객이 얼마정도의 차를 구매할 수 있을지를 예측하여, 그 사람에게 맞는 자동차를 보여주려 한다.

  • Customer Name
  • Customer e-mail
  • Country
  • Gender
  • Age
  • Annual Salary
  • Credit Card Debt
  • Net Worth (순자산)

예측하고자 하는 값 :

  • Car Purchase Amount

STEP #0: 라이브러리 임포트 및 코랩 환경 설정

구글 드라이브 파일 읽기 참고

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

csv 파일을 읽기 위해, 구글 드라이브 마운트 하시오

from google.colab import drive
drive.mount('/content/drive')
Mounted at /content/drive

working directory 를, 현재의 파일이 속한 폴더로 셋팅하시오.

import os
os.chdir('/content/drive/MyDrive/python/day14')

STEP #1: IMPORT DATASET

Car_Purchasing_Data.csv 파일을 사용한다. 코랩의 경우 구글드라이브의 전체경로를 복사하여 파일 읽는다.

인코딩은 다음처럼 한다. encoding=’ISO-8859-1’

pd.read_csv('Car_Purchasing_Data.csv', encoding='ISO-8859-1')
Customer Name Customer e-mail Country Gender Age Annual Salary Credit Card Debt Net Worth Car Purchase Amount
0 Martina Avila cubilia.Curae.Phasellus@quisaccumsanconvallis.edu Bulgaria 0 41.851720 62812.09301 11609.380910 238961.2505 35321.45877
1 Harlan Barnes eu.dolor@diam.co.uk Belize 0 40.870623 66646.89292 9572.957136 530973.9078 45115.52566
2 Naomi Rodriquez vulputate.mauris.sagittis@ametconsectetueradip... Algeria 1 43.152897 53798.55112 11160.355060 638467.1773 42925.70921
3 Jade Cunningham malesuada@dignissim.com Cook Islands 1 58.271369 79370.03798 14426.164850 548599.0524 67422.36313
4 Cedric Leach felis.ullamcorper.viverra@egetmollislectus.net Brazil 1 57.313749 59729.15130 5358.712177 560304.0671 55915.46248
... ... ... ... ... ... ... ... ... ...
495 Walter ligula@Cumsociis.ca Nepal 0 41.462515 71942.40291 6995.902524 541670.1016 48901.44342
496 Vanna Cum.sociis.natoque@Sedmolestie.edu Zimbabwe 1 37.642000 56039.49793 12301.456790 360419.0988 31491.41457
497 Pearl penatibus.et@massanonante.com Philippines 1 53.943497 68888.77805 10611.606860 764531.3203 64147.28888
498 Nell Quisque.varius@arcuVivamussit.net Botswana 1 59.160509 49811.99062 14013.034510 337826.6382 45442.15353
499 Marla Camaron.marla@hotmail.com marlal 1 46.731152 61370.67766 9391.341628 462946.4924 45107.22566

500 rows × 9 columns

car_df = pd.read_csv('Car_Purchasing_Data.csv', encoding='ISO-8859-1')

컬럼을 확인하고

기본 통계 데이터를 확인해 보자

car_df.isna().sum()
Customer Name          0
Customer e-mail        0
Country                0
Gender                 0
Age                    0
Annual Salary          0
Credit Card Debt       0
Net Worth              0
Car Purchase Amount    0
dtype: int64
car_df['Country'].describe()
count        500
unique       211
top       Israel
freq           6
Name: Country, dtype: object

연봉이 가장 높은 사람은 누구인가

car_df[car_df['Annual Salary'] == car_df['Annual Salary'].max() ].loc[:,'Customer Name']
28    Gemma Hendrix
Name: Customer Name, dtype: object

나이가 가장 어린 고객은, 연봉이 얼마인가

car_df[car_df['Age']==car_df['Age'].min()].loc[:,'Annual Salary']
444    70467.29492
Name: Annual Salary, dtype: float64

STEP #2: VISUALIZE DATASET

상관관계를 분석하기 위해, pairplot 을 그려보자.

sns.pairplot(data = car_df)
plt.show()

png

cc = car_df.corr()
cc
Gender Age Annual Salary Credit Card Debt Net Worth Car Purchase Amount
Gender 1.000000 -0.064481 -0.036499 0.024193 -0.008395 -0.066408
Age -0.064481 1.000000 0.000130 0.034721 0.020356 0.632865
Annual Salary -0.036499 0.000130 1.000000 0.049599 0.014767 0.617862
Credit Card Debt 0.024193 0.034721 0.049599 1.000000 -0.049378 0.028882
Net Worth -0.008395 0.020356 0.014767 -0.049378 1.000000 0.488580
Car Purchase Amount -0.066408 0.632865 0.617862 0.028882 0.488580 1.000000
sns.heatmap(data = cc,annot=True,vmin=-1,vmax=1,cmap='coolwarm',linewidths= 0.5 , square=True)
plt.show()

png

STEP #3: CREATE TESTING AND TRAINING DATASET/DATA CLEANING

NaN 값이 있으면, 이를 해결하시오.

car_df.isna().sum()
Customer Name          0
Customer e-mail        0
Country                0
Gender                 0
Age                    0
Annual Salary          0
Credit Card Debt       0
Net Worth              0
Car Purchase Amount    0
dtype: int64

학습을 위해 ‘Customer Name’, ‘Customer e-mail’, ‘Country’, ‘Car Purchase Amount’ 컬럼을 제외한 컬럼만, X로 만드시오.

X = car_df.loc[:,'Gender':'Net Worth']
X.shape
(500, 5)

y 값은 ‘Car Purchase Amount’ 컬럼으로 셋팅하시오.

y = car_df['Car Purchase Amount']

피처 스케일링 하겠습니다. 정규화(normalization)를 사용합니다. MinMaxScaler 를 이용하시오.

from sklearn.preprocessing import MinMaxScaler
scaler_X = MinMaxScaler()
X = scaler_X.fit_transform(X)

학습을 위해서, y 의 shape 을 변경하시오.

y= car_df.iloc[:,-1]
y = y.to_numpy().reshape(500,1)
y.shape
(500, 1)

y 도 피처 스케일링 하겠습니다. X 처럼 y도 노멀라이징 하시오.

scaler_y = MinMaxScaler()
y = scaler_y.fit_transform(y)

STEP#4: TRAINING THE MODEL

트레이닝셋과 테스트셋으로 분리하시오. (테스트 사이즈는 25%로 하며, 동일 결과를 위해 랜덤스테이트는 50 으로 셋팅하시오.)

from sklearn.model_selection import train_test_split
X_train , X_test, y_train, y_test = train_test_split(X,y,test_size = 0.25 ,random_state = 50)

1. RandomForest 나 XGBoost 를 이용하시오.

from sklearn.ensemble import RandomForestRegressor
regressor = RandomForestRegressor(50)
regressor.fit(X_train,y_train)
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:1: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().
  """Entry point for launching an IPython kernel.





RandomForestRegressor(n_estimators=50)
y_pred = regressor.predict(X_test)
# y_test 값이 , 피처 스케일링을 통해서 2차원으로 만들어져 있기 때문에 오차를 구하려면 이를 다시 1차원으로 변경시켜줘야한다.
y_test = y_test.reshape(125,)
error = y_test - y_pred
MSE = (error ** 2).mean()
MSE
0.001821193287592156
plt.plot(y_test)
plt.plot(y_pred)
plt.show()

png

# 유저가 앱을 통해서 데이터를 입력했습니다.
# 이 사람은 얼마 정도의 차를 구매할 수 있는지 예측하세요.

# 여자이고, 나이는 38살, 연봉은 78000달러 카드빚은 15000달러 이고 자산은 480,000 달러입니다.
# 이 사람은 얼마짜리 차를 구매할 여력이 될까요?
car_df.head()
Customer Name Customer e-mail Country Gender Age Annual Salary Credit Card Debt Net Worth Car Purchase Amount
0 Martina Avila cubilia.Curae.Phasellus@quisaccumsanconvallis.edu Bulgaria 0 41.851720 62812.09301 11609.380910 238961.2505 35321.45877
1 Harlan Barnes eu.dolor@diam.co.uk Belize 0 40.870623 66646.89292 9572.957136 530973.9078 45115.52566
2 Naomi Rodriquez vulputate.mauris.sagittis@ametconsectetueradip... Algeria 1 43.152897 53798.55112 11160.355060 638467.1773 42925.70921
3 Jade Cunningham malesuada@dignissim.com Cook Islands 1 58.271369 79370.03798 14426.164850 548599.0524 67422.36313
4 Cedric Leach felis.ullamcorper.viverra@egetmollislectus.net Brazil 1 57.313749 59729.15130 5358.712177 560304.0671 55915.46248
new_data = np.array([0,38,78000,15000,480000]).reshape(1,5)
new_data = scaler_X.transform(new_data)
/usr/local/lib/python3.7/dist-packages/sklearn/base.py:446: UserWarning: X does not have valid feature names, but MinMaxScaler was fitted with feature names
  "X does not have valid feature names, but"
# 피쳐 스케일링 해줘야 하는데.
# 학습할떄 사용한 스케일러가 이미 , 최대 최소값들을 가지고 있기 때문에
# 그 스케일러를 이용해서 변환해야한다.
y_pred = regressor.predict(new_data)
scaler_y.inverse_transform(y_pred.reshape(1,1))
array([[47448.7187924]])

댓글남기기