랜덤포레스트를 통한 보험사기 추측해보기
Insurance Fraud Detection using Random Forest
랜덤 포레스트를 이용한 보험 사기 탐지
Introduction
인공지능은 프로세스를 자동화하고, 비즈니스에 대한 통찰력을 모으고, 프로세스 속도를 높이기 위해 다양한 산업에서 사용되고 있습니다. 인공지능이 실제로 산업에 어떤 영향을 미치는지 실제 시나리오에서 인공지능의 사용을 연구하기 위해 Python을 사용할 것입니다.
보험 사기는 매우 크고 중요한 문제입니다. 다양한 사기가 계속 발생하고 있으며, 일부 수법은 일반화 되어있습니다. 따라서 미리 예측하면 많은 피해를 막을 수 있으며, 비용을 절약할 수 있습니다. 이러한 문제에 대하여 AI는 우리를 도울 수 있습니다.
이 노트북에서는 랜덤 포레스트를 사용한 보험 사기 탐지에 중점을 둘 것입니다.
Context
우리는 [Kaggle]에서 얻은 자동차 보험 청구 데이터로 실습할 것입니다. Kaggle은 데이터 전문가들이 모여 지식을 공유하고 서로 경쟁하여 보상을 받을 수 있는 데이터 공유 플랫폼입니다. 정리된 데이터가 Insurance.csv에 포함되어 있습니다.
Side note: Random Forest란 무엇인가?
랜덤 포레스트는 많은 의사 결정 트리의 결정을 결합하여 데이터 포인트의 클래스를 결정하는 분류 알고리즘입니다. 우리는 다양한 트리를 기반으로 결정을 내리고 과반수 투표를 수행하고 최종 클래스를 결정합니다. 다음 다이어그램을 보면 좀 더 명확하게 이해할 수 있을 것입니다.

Use Python to open csv files
scikit-learn과 pandas를 사용하여 데이터 세트를 작업합니다. Scikit-learn은 예측 데이터 분석을 위한 효율적인 도구를 제공하는 매우 유용한 기계 학습 라이브러리입니다. Pandas는 데이터 과학을 위한 인기 있는 Python 라이브러리입니다. 강력하고 유연한 데이터 구조를 제공하여 데이터 조작 및 분석을 더 쉽게 만듭니다.
Import Libraries
import numpy as np
import pandas as pd
import datetime as dt
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
TASK1. [Dataset]Module11(Insurance).csv 파일을 df 변수로 읽어 오세요.
df = pd.read_csv("./[Dataset]_Module11_(Insurance).csv")# your code here
df.head(5)# your code here
| Unnamed: 0 | capital-gains | capital-loss | incident_hour_of_the_day | number_of_vehicles_involved | witnesses | total_claim_amount | fraud_reported | insured_sex_FEMALE | insured_sex_MALE | ... | months_as_customer_groups_301-350 | months_as_customer_groups_351-400 | months_as_customer_groups_401-450 | months_as_customer_groups_451-500 | months_as_customer_groups_51-100 | policy_annual_premium_groups_high | policy_annual_premium_groups_low | policy_annual_premium_groups_medium | policy_annual_premium_groups_very high | policy_annual_premium_groups_very low | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 53300 | 0 | 5 | 1 | 2 | 71610 | 1 | 0 | 1 | ... | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 1 | 1 | 0 | 0 | 8 | 1 | 0 | 5070 | 1 | 0 | 1 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 2 | 2 | 35100 | 0 | 7 | 3 | 3 | 34650 | 0 | 1 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 3 | 3 | 48900 | -62400 | 5 | 1 | 2 | 63400 | 1 | 1 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| 4 | 4 | 66000 | -46000 | 20 | 1 | 1 | 6500 | 0 | 0 | 1 | ... | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |
5 rows × 69 columns
# Shape of dataframe
# your code here
df.shape
(1000, 69)
# df의 컬럼 값을 확인하세요.
# your code here
df.columns
Index(['Unnamed: 0', 'capital-gains', 'capital-loss',
'incident_hour_of_the_day', 'number_of_vehicles_involved', 'witnesses',
'total_claim_amount', 'fraud_reported', 'insured_sex_FEMALE',
'insured_sex_MALE', 'insured_occupation_adm-clerical',
'insured_occupation_armed-forces', 'insured_occupation_craft-repair',
'insured_occupation_exec-managerial',
'insured_occupation_farming-fishing',
'insured_occupation_handlers-cleaners',
'insured_occupation_machine-op-inspct',
'insured_occupation_other-service',
'insured_occupation_priv-house-serv',
'insured_occupation_prof-specialty',
'insured_occupation_protective-serv', 'insured_occupation_sales',
'insured_occupation_tech-support',
'insured_occupation_transport-moving', 'insured_hobbies_chess',
'insured_hobbies_cross-fit', 'insured_hobbies_other',
'incident_type_Multi-vehicle Collision', 'incident_type_Parked Car',
'incident_type_Single Vehicle Collision', 'incident_type_Vehicle Theft',
'collision_type_?', 'collision_type_Front Collision',
'collision_type_Rear Collision', 'collision_type_Side Collision',
'incident_severity_Major Damage', 'incident_severity_Minor Damage',
'incident_severity_Total Loss', 'incident_severity_Trivial Damage',
'authorities_contacted_Ambulance', 'authorities_contacted_Fire',
'authorities_contacted_None', 'authorities_contacted_Other',
'authorities_contacted_Police', 'age_group_15-20', 'age_group_21-25',
'age_group_26-30', 'age_group_31-35', 'age_group_36-40',
'age_group_41-45', 'age_group_46-50', 'age_group_51-55',
'age_group_56-60', 'age_group_61-65', 'months_as_customer_groups_0-50',
'months_as_customer_groups_101-150',
'months_as_customer_groups_151-200',
'months_as_customer_groups_201-250',
'months_as_customer_groups_251-300',
'months_as_customer_groups_301-350',
'months_as_customer_groups_351-400',
'months_as_customer_groups_401-450',
'months_as_customer_groups_451-500', 'months_as_customer_groups_51-100',
'policy_annual_premium_groups_high', 'policy_annual_premium_groups_low',
'policy_annual_premium_groups_medium',
'policy_annual_premium_groups_very high',
'policy_annual_premium_groups_very low'],
dtype='object')
# 다양한 Feature에 대하여 null 값의 수를 확인합니다.
# your code here
df.isna().sum()
Unnamed: 0 0
capital-gains 0
capital-loss 0
incident_hour_of_the_day 0
number_of_vehicles_involved 0
..
policy_annual_premium_groups_high 0
policy_annual_premium_groups_low 0
policy_annual_premium_groups_medium 0
policy_annual_premium_groups_very high 0
policy_annual_premium_groups_very low 0
Length: 69, dtype: int64
# Dataset에 대한 추가 정보를 확인합니다.
# your code here
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 1000 entries, 0 to 999 Data columns (total 69 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Unnamed: 0 1000 non-null int64 1 capital-gains 1000 non-null int64 2 capital-loss 1000 non-null int64 3 incident_hour_of_the_day 1000 non-null int64 4 number_of_vehicles_involved 1000 non-null int64 5 witnesses 1000 non-null int64 6 total_claim_amount 1000 non-null int64 7 fraud_reported 1000 non-null int64 8 insured_sex_FEMALE 1000 non-null int64 9 insured_sex_MALE 1000 non-null int64 10 insured_occupation_adm-clerical 1000 non-null int64 11 insured_occupation_armed-forces 1000 non-null int64 12 insured_occupation_craft-repair 1000 non-null int64 13 insured_occupation_exec-managerial 1000 non-null int64 14 insured_occupation_farming-fishing 1000 non-null int64 15 insured_occupation_handlers-cleaners 1000 non-null int64 16 insured_occupation_machine-op-inspct 1000 non-null int64 17 insured_occupation_other-service 1000 non-null int64 18 insured_occupation_priv-house-serv 1000 non-null int64 19 insured_occupation_prof-specialty 1000 non-null int64 20 insured_occupation_protective-serv 1000 non-null int64 21 insured_occupation_sales 1000 non-null int64 22 insured_occupation_tech-support 1000 non-null int64 23 insured_occupation_transport-moving 1000 non-null int64 24 insured_hobbies_chess 1000 non-null int64 25 insured_hobbies_cross-fit 1000 non-null int64 26 insured_hobbies_other 1000 non-null int64 27 incident_type_Multi-vehicle Collision 1000 non-null int64 28 incident_type_Parked Car 1000 non-null int64 29 incident_type_Single Vehicle Collision 1000 non-null int64 30 incident_type_Vehicle Theft 1000 non-null int64 31 collision_type_? 1000 non-null int64 32 collision_type_Front Collision 1000 non-null int64 33 collision_type_Rear Collision 1000 non-null int64 34 collision_type_Side Collision 1000 non-null int64 35 incident_severity_Major Damage 1000 non-null int64 36 incident_severity_Minor Damage 1000 non-null int64 37 incident_severity_Total Loss 1000 non-null int64 38 incident_severity_Trivial Damage 1000 non-null int64 39 authorities_contacted_Ambulance 1000 non-null int64 40 authorities_contacted_Fire 1000 non-null int64 41 authorities_contacted_None 1000 non-null int64 42 authorities_contacted_Other 1000 non-null int64 43 authorities_contacted_Police 1000 non-null int64 44 age_group_15-20 1000 non-null int64 45 age_group_21-25 1000 non-null int64 46 age_group_26-30 1000 non-null int64 47 age_group_31-35 1000 non-null int64 48 age_group_36-40 1000 non-null int64 49 age_group_41-45 1000 non-null int64 50 age_group_46-50 1000 non-null int64 51 age_group_51-55 1000 non-null int64 52 age_group_56-60 1000 non-null int64 53 age_group_61-65 1000 non-null int64 54 months_as_customer_groups_0-50 1000 non-null int64 55 months_as_customer_groups_101-150 1000 non-null int64 56 months_as_customer_groups_151-200 1000 non-null int64 57 months_as_customer_groups_201-250 1000 non-null int64 58 months_as_customer_groups_251-300 1000 non-null int64 59 months_as_customer_groups_301-350 1000 non-null int64 60 months_as_customer_groups_351-400 1000 non-null int64 61 months_as_customer_groups_401-450 1000 non-null int64 62 months_as_customer_groups_451-500 1000 non-null int64 63 months_as_customer_groups_51-100 1000 non-null int64 64 policy_annual_premium_groups_high 1000 non-null int64 65 policy_annual_premium_groups_low 1000 non-null int64 66 policy_annual_premium_groups_medium 1000 non-null int64 67 policy_annual_premium_groups_very high 1000 non-null int64 68 policy_annual_premium_groups_very low 1000 non-null int64 dtypes: int64(69) memory usage: 539.2 KB
# df의 각 컬럼의 unique값을 확인합니다.
# your code here
df.nunique(dropna=False)
Unnamed: 0 1000
capital-gains 338
capital-loss 354
incident_hour_of_the_day 24
number_of_vehicles_involved 4
...
policy_annual_premium_groups_high 2
policy_annual_premium_groups_low 2
policy_annual_premium_groups_medium 2
policy_annual_premium_groups_very high 2
policy_annual_premium_groups_very low 2
Length: 69, dtype: int64
Task 2: describe 함수를 사용하여 데이터 세트에 대한 정보 표시
# your code here
df.describe().T
| count | mean | std | min | 25% | 50% | 75% | max | |
|---|---|---|---|---|---|---|---|---|
| Unnamed: 0 | 1000.0 | 499.500 | 288.819436 | 0.0 | 249.75 | 499.5 | 749.25 | 999.0 |
| capital-gains | 1000.0 | 25126.100 | 27872.187708 | 0.0 | 0.00 | 0.0 | 51025.00 | 100500.0 |
| capital-loss | 1000.0 | -26793.700 | 28104.096686 | -111100.0 | -51500.00 | -23250.0 | 0.00 | 0.0 |
| incident_hour_of_the_day | 1000.0 | 11.644 | 6.951373 | 0.0 | 6.00 | 12.0 | 17.00 | 23.0 |
| number_of_vehicles_involved | 1000.0 | 1.839 | 1.018880 | 1.0 | 1.00 | 1.0 | 3.00 | 4.0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... |
| policy_annual_premium_groups_high | 1000.0 | 0.153 | 0.360168 | 0.0 | 0.00 | 0.0 | 0.00 | 1.0 |
| policy_annual_premium_groups_low | 1000.0 | 0.151 | 0.358228 | 0.0 | 0.00 | 0.0 | 0.00 | 1.0 |
| policy_annual_premium_groups_medium | 1000.0 | 0.693 | 0.461480 | 0.0 | 0.00 | 1.0 | 1.00 | 1.0 |
| policy_annual_premium_groups_very high | 1000.0 | 0.001 | 0.031623 | 0.0 | 0.00 | 0.0 | 0.00 | 1.0 |
| policy_annual_premium_groups_very low | 1000.0 | 0.002 | 0.044699 | 0.0 | 0.00 | 0.0 | 0.00 | 1.0 |
69 rows × 8 columns
# Fraud_reported가 목표 열입니다. Fraud_reported의 고유값을 확인해 봅시다.
# your code here
df['fraud_reported'].unique()
array([1, 0], dtype=int64)
# 다음으로 fraud_reported 열의 0과 1의 분포를 확인할 수 있습니다.
sns.countplot(x=df['fraud_reported'])
<AxesSubplot: xlabel='fraud_reported', ylabel='count'>
# plotly 설치.
%pip install plotly==5.11.0
Collecting plotly==5.11.0Note: you may need to restart the kernel to use updated packages.
Downloading plotly-5.11.0-py2.py3-none-any.whl (15.3 MB)
--------------------------------------- 15.3/15.3 MB 40.9 MB/s eta 0:00:00
Collecting tenacity>=6.2.0
Downloading tenacity-8.1.0-py3-none-any.whl (23 kB)
Installing collected packages: tenacity, plotly
Successfully installed plotly-5.11.0 tenacity-8.1.0
# fraud_reported 열의 분포를 원형 그래프로 그려 보세요.(pie 함수 이용)
import plotly.express as px
# your code here
fig = px.pie(df['fraud_reported'], names='fraud_reported')
fig.show()

jupyter 파일로는 상관없는데 md로 할 때..
파일 용량이 괜히 커지고 해서 삭제해서 이미지로 대체 양해바람
feature간 상관관계 확인
여기서 우리는 상관 다이어그램을 그리기 위하여 plotly 라이브러리를 사용합니다.
상관 행렬은 변수 간의 관계, 즉 다른 변수가 변경될 때 한 변수가 어떻게 변경되는지를 보여주는 테이블입니다. 5개의 변수가 있는 경우 상관 행렬에는 5 곱하기 5 또는 25개의 항목이 있으며 각 항목은 두 변수 간의 상관 관계를 보여줍니다.
기계 학습 알고리즘의 정확도는 알고리즘이 얼마나 잘 수행되고 있는지, 즉 알고리즘이 데이터 포인트를 올바르게 분류하는 빈도를 측정하는 것입니다. 정확도는 다음과 같이 주어집니다:

정밀도는 관련성 있는 결과의 %를 의미하고, 재현율은 알고리즘에 의해 올바르게 분류된 전체 관련 결과의 %를 의미합니다.

True positive: 모델이 긍정 클래스를 올바르게 예측합니다.
True negative: 모델이 부정 클래스를 올바르게 예측합니다.
False positive: 모델이 긍정 클래스를 잘못 예측합니다.
False negative: 모델이 부정 클래스를 잘못 예측합니다.
우리는 plotly 라이브러리를 사용합니다.
라이브러리가 설치되어 있지 않은 경우 터미널에서 다음 단계를 수행하여 설치해주세요:
pip install plotly **<원형 그릴때="" 설치완료="">**원형>
import plotly.express as px
import plotly.graph_objects as go
# pandas의 corr() 함수를 사용하여 상관 행렬 가져오기
corr_matrix = df.corr()
fig = go.Figure(data = go.Heatmap(
z = corr_matrix.values,
x = list(corr_matrix.columns),
y = list(corr_matrix.index)))
fig.update_layout(title = 'Correlation_Insurance_Fraud')
fig.show()

jupyter 파일로는 상관없는데 md로 할 때..
파일 용량이 괜히 커지고 해서 삭제해서 이미지로 대체 양해바람
# fraud_reported를 Target으로 Dataset 나누기
X = df.loc[:, (df.columns != 'Unnamed: 0') & (df.columns != 'fraud_reported')] # your code here
y = df.loc[:, ['fraud_reported']] # your code here
from sklearn.preprocessing import StandardScaler
# Data 정규화 하기
sc = StandardScaler()
X = sc.fit_transform(X)
# 데이터를 test와 train 데이터로 나눕니다.
# your code here
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
랜덤 포레스트 분류기 적용하기
랜덤 포레스트는 많은 의사 결정 트리의 결정을 결합하여 데이터 포인트의 클래스를 결정하는 분류 알고리즘입니다. 우리는 다양한 트리를 기반으로 결정을 내리고 과반수 투표를 수행하고 최종 클래스를 결정합니다.
from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier(random_state = 1)
# your code here
rfc.fit(x_train, y_train)
rfc
C:\Users\User\AppData\Local\Temp\ipykernel_13696\2780899869.py:4: 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().
RandomForestClassifier(random_state=1)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
RandomForestClassifier(random_state=1)
Task 3: 랜덤 포레스트 분류기를 사용하여 훈련 데이터를 예측하고 결과를 변수 preds에 저장
# X_test로 test 결과값 만들기
# your code here
y_pred = rfc.predict(x_test)
y_pred
array([0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,
1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1,
0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1,
0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0,
1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1,
0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], dtype=int64)
# score 함수로 Mean accuracy 확인하기
# your code here
score = accuracy_score(y_test, y_pred)
print(score*100)
# classification_report 함수로 모델 평가하기
# your code here
print(classification_report(y_test, y_pred, target_names=['0', '1']))
82.33333333333334
precision recall f1-score support
0 0.86 0.90 0.88 220
1 0.70 0.60 0.64 80
accuracy 0.82 300
macro avg 0.78 0.75 0.76 300
weighted avg 0.82 0.82 0.82 300
from sklearn.metrics import roc_auc_score
# auc score 확인하기
# your code here
roc_auc_score(y_test, y_pred)
0.7522727272727273
from sklearn import metrics
fpr, tpr, threshold = metrics.roc_curve(y_test, y_pred)
roc_auc = metrics.auc(fpr, tpr)
f, ax = plt.subplots(figsize=(10, 10))
plt.title('Receiver Operating Characteristic')
plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)
plt.legend(loc = 'lower right')
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
plt.show()
Task 4: 랜덤 포레스트 분류기의 결과를 보았습니다. 이제 의사 결정 트리 분류기를 사용하여 데이터를 분류해 보세요.
dtc = DecisionTreeClassifier()
# your code here
dtc.fit(x_train, y_train)
# your code here
y_pred = dtc.predict(x_test)
# your code here
score = accuracy_score(y_test, y_pred)
print(score*100)
# your code here
print(classification_report(y_test, y_pred, target_names=['0', '1']))
73.0
precision recall f1-score support
0 0.80 0.84 0.82 220
1 0.49 0.44 0.46 80
accuracy 0.73 300
macro avg 0.65 0.64 0.64 300
weighted avg 0.72 0.73 0.72 300
Task 5: 의사 결정 트리 분류기의 결과를 보았습니다. 이제 로지스틱 회귀 분류기를 사용하여 데이터를 분류해 보세요.
lr = LogisticRegression()
# your code here
lr.fit(x_train, y_train)
# your code here
y_pred = lr.predict(x_test)
# your code here
score = accuracy_score(y_test, y_pred)
print(score*100)
# your code here
print(classification_report(y_test, y_pred, target_names=['0', '1']))
83.66666666666667
precision recall f1-score support
0 0.87 0.92 0.89 220
1 0.73 0.61 0.67 80
accuracy 0.84 300
macro avg 0.80 0.77 0.78 300
weighted avg 0.83 0.84 0.83 300
C:\Users\User\.conda\envs\myai\lib\site-packages\sklearn\utils\validation.py:1111: 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().
Task 6: Gradient Boosting Classifier로 데이터를 분류해 보세요.
from sklearn.ensemble import GradientBoostingClassifier
gb = GradientBoostingClassifier()
# your code here
gb.fit(x_train, y_train)
# your code here
y_pred = gb.predict(x_test)
# your code here
score = accuracy_score(y_test, y_pred)
print(score*100)
# your code here
print(classification_report(y_test, y_pred, target_names=['0', '1']))
82.0
precision recall f1-score support
0 0.87 0.89 0.88 220
1 0.67 0.64 0.65 80
accuracy 0.82 300
macro avg 0.77 0.76 0.77 300
weighted avg 0.82 0.82 0.82 300
C:\Users\User\.conda\envs\myai\lib\site-packages\sklearn\ensemble\_gb.py:570: 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().
%pip install xgboost
Collecting xgboost
Downloading xgboost-1.7.1-py3-none-win_amd64.whl (89.1 MB)
--------------------------------------- 89.1/89.1 MB 34.4 MB/s eta 0:00:00
Requirement already satisfied: numpy in c:\users\user\.conda\envs\myai\lib\site-packages (from xgboost) (1.23.4)
Requirement already satisfied: scipy in c:\users\user\.conda\envs\myai\lib\site-packages (from xgboost) (1.9.3)
Installing collected packages: xgboost
Successfully installed xgboost-1.7.1
Note: you may need to restart the kernel to use updated packages.
Task 7: XGB Classifier로 데이터를 분류해 보세요.
from xgboost import XGBClassifier
xgb = XGBClassifier()
# your code here
xgb.fit(x_train, y_train)
# your code here
y_pred = xgb.predict(x_test)
# your code here
score = accuracy_score(y_test, y_pred)
print(score*100)
# your code here
print(classification_report(y_test, y_pred, target_names=['0', '1']))
81.66666666666667
precision recall f1-score support
0 0.85 0.91 0.88 220
1 0.70 0.55 0.62 80
accuracy 0.82 300
macro avg 0.77 0.73 0.75 300
weighted avg 0.81 0.82 0.81 300
Conclusion
인공 지능은 다양한 현대 사회의 문제를 해결하는데 널리 사용되고 있습니다. 이 노트북에서는 랜덤 포레스트 알고리즘을 사용하여 사기 탐지에 인공 지능을 사용하는 방법의 예를 보았습니다. 같은 목적으로 다른 모델을 사용할 수도 있습니다. 추가적으로 다른 모델을 적용하였을 때 정확도를 비교해 보는 연습을 해보세요.
그 외 참고한 리스트들..
https://stackoverflow.com/questions/26266362/how-do-i-count-the-nan-values-in-a-column-in-pandas-dataframe
isna().sum() 등 null값 조회 및 분석,정리 참조..
https://seaborn.pydata.org/generated/seaborn.countplot.html
countplot 확인
https://plotly.com/python/pie-charts/
plotly, pie함수의 원형 그래프 그리는 방법 확인
https://hmiiing.tistory.com/entry/jupyter-notebook%EC%97%90-plotly-%EA%B7%B8%EB%9E%98%ED%94%84%EA%B0%80-%EB%82%98%EC%98%A4%EC%A7%80-%EC%95%8A%EC%9D%84-%EB%95%8C-%ED%95%B4%EA%B2%B0%EB%B0%A9%EB%B2%95
만일 plotly 그래프가 안나올때;;;;
https://jhryu1208.github.io/data/2020/12/25/pandas_practice_loc/
특정 열, 행 자르기 및 조회
https://datascienceschool.net/03%20machine%20learning/09.04%20%EB%B6%84%EB%A5%98%20%EC%84%B1%EB%8A%A5%ED%8F%89%EA%B0%80.html
classification_report를 통한 평가방법 확인 및 정확도 평가 확인
https://sumniya.tistory.com/26
f1등 인공지능 평가에 관한 수학기초
마무리;;
-
(임시) 바삐 작성한 내용이라 좀 더 조절없이 그대로 하게된 점 아쉽..
-
랜덤 포레스트에 이어 돌리고 평가하고 하는 방식이 뭔가 복붙 술술이 신기.
-
평가 기준 리스트에서 정밀도, 재현율, f1, 감지량(support) 이 데이터 중에서 f1 제일 높은쪽이 좋은 모델로..
-
특히 f1 관련 성능 정보에 대해서는 추후 찾아서 정리.
-
f1이란..
Precision과 Recall의 조화평균, 데이터 label이 불균형 구조일 때, 모델의 성능을 정확하게 평가할 수 있으며, 성능을 하나의 숫자로 표현할 수 있다 등..
주의사항
본 포트폴리오는 인텔 AI 저작권에 따라 그대로 사용하기에 상업적으로 사용하기 어려움을 말씀드립니다.
댓글남기기