## 머신러닝 이진 분류모델
빅데이터 분석기사 등 분석 스터디 하시는 분들에게 도움이 되시기를 바랍니다.
Colab을 통해 진행하실수 있게 별도로 준비 없이 진행하도록 코드를 준비했습니다.
와인 품질 데이터에 대해서는 아래 사이트의 데이터를 사용하였습니다.
https://archive.ics.uci.edu/dataset/186/wine+quality
UCI Machine Learning Repository
This dataset is licensed under a Creative Commons Attribution 4.0 International (CC BY 4.0) license. This allows for the sharing and adaptation of the datasets for any purpose, provided that the appropriate credit is given.
archive.ics.uci.edu
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# CSV 파일 불러오기
url = 'https://archive.ics.uci.edu/static/public/186/data.csv'
df = pd.read_csv(url)
df.head()
df.head() 는 상위 5개 행을 보여줌 df.tail()은 아래 5개를 표신한다.
10개 행을 보고 싶으면 df.head(10)으로 숫자를 넣어주면 됩니다.
df.info()
df.info() 는 컬럼수, 각 컬럼의 이름, 결측치가 아닌 값의 개수, data type, 메모리 사용량을 제공한다
df.describe().T
describe()는 수치형 데이터를 중심으로 데이터의 기본 통계 요약을 제공합니다.
저는 가로와 세로 변경해서 보는게 편해서 전치를 하였습니다.
추가적으로 범주형 변수를 포함하고 싶으면 df.describe(include='all') 로 사용하면 됩니다.
df.isnull().sum() # null 체크
df['quality'].value_counts()
※ numpy 함수로는 np.unique(df['quality'], return_counts=True) 사용하면 유사한 결과를 얻을 수 있음
dfSummary도 사용해 봅시다.
#미설치되어 있으면 !pip install summarytools
from summarytools import dfSummary
dfSummary(df)
df.hist(figsize=(20, 10))
df1 = df[df.columns.difference(['color'])] #color는 제외 categorical 변수
plt.figure(figsize=(20, 10))
sns.heatmap(df1.corr(), annot=True, cmap='coolwarm', fmt=".2f", linewidths=0.5) #히드맵
quality에 영향을 주는 변수를 확인 가능함
df = df.drop('total sulfur dioxide', axis=1) #변수간 인과관계 높아서 제거
df['best quality'] = [1 if x > 5 else 0 for x in df['quality']]
df.replace({'white': 1, 'red': 0}, inplace=True)
#인코딩도 가능
df['color'].value_counts()
#훈련:80% 테스트:20% 데이터 split함
y = df['best quality']
X = df.drop(columns='best quality')
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=89)
X_train.shape, X_test.shape # (5197, 12), (1300, 12))
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.fit_transform(X_test)
#로지스틱 회귀분석
from sklearn.linear_model import LogisticRegression
lr_model = LogisticRegression()
lr_model.fit(X_train, y_train)
lr_prediction = lr_model.predict(X_test)
from sklearn.metrics import accuracy_score
print(lr_prediction)
lr_accuracy = accuracy_score(y_test, lr_prediction)
print(lr_accuracy)
## 0.73
from sklearn.svm import SVC
svc_model = SVC()
svc_model.fit(X_train, y_train)
svc_prediction = svc_model.predict(X_test)
svc_accuracy = accuracy_score(y_test, svc_prediction)
svc_accuracy
# 0.75
from sklearn.ensemble import RandomForestClassifier
y = df['best quality']
X = df.drop(columns='best quality')
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=89)
X_train.shape, X_test.shape # (5197, 12), (1300, 12))
rf_model = RandomForestClassifier()
rf_model.fit(X_train, y_train)
rf_prediction = rf_model.predict(X_test)
rf_accuracy = accuracy_score(y_test, rf_prediction)
rf_accuracy
#0.85
랜덤포레스터 모델이 85% 제일 나은 정확도를 보여주고 있습니다. 랜덤포레스터는 scale이 필요가 없습니다.
'머신러닝' 카테고리의 다른 글
[ML] 스팸메일 분류 모델(MultinomialNB) (0) | 2025.04.18 |
---|---|
[ML] 타이타닉 생존 예측 분류모델 (0) | 2025.04.16 |