import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
wine= pd.read_csv('https://bit.ly/wine-date')
data = wine[['alcohol','sugar','pH']].to_numpy()
target = wine[['class']].to_numpy()
train_input, test_input, train_target, test_target = train_test_split(data, target, test_size=0.2, random_state=42) #data 훈련세트, 테스트세트로 나누기
ss = StandardScaler()
ss.fit(train_input)
train_scaled = ss.transform(train_input)
test_scaled = ss.transform(test_input) #데이터 정규화
lr = LogisticRegression()
lr.fit(train_scaled, train_target)
print(lr.score(train_scaled, train_target))
print(lr.score(test_scaled, test_target))
# -> 0.7808350971714451, 0.7776923076923077
# 점수가 모두 낮으므로 과소적합.
-> 로지스틱 회귀로 분류했을 때, 과소적합이 일어남 + 결과를 설명하기 어려움
from sklearn.tree import DecisionTreeClassifier
dt = DecisionTreeClassifier(random_state=42)
dt.fit(train_scaled, train_target) #결정 트리 학습
print(dt.score(train_scaled, train_target))
print(dt.score(test_scaled, test_target))
# -> 0.996921300750433, 0.8592307692307692
-> 훈련 세트에 대한 점수가 엎청 높은 것을 확인할 수 있음.
import matplotlib.pyplot as plt from sklearn.tree import plot_tree plt.figure(figsize=(10,7)) plot_tree(dt) plt.show()
위의 코드로 트리의 모양을 확인할 수도 있음