Iris : 프랑스의 국화
from sklearn.datasets import load_iris
iris = load_iris()
petal의 length와 width만 그렸는데 여기서 두 특징(petal length/width)만 가지고 세 개의 품종을 구분할 수 있나요?
일단 0번인 setosa는 가능하다. -> petal length가 2.5보다 작다면 모두 setosa로 분류해도 됨
# 데이터 변경
iris_12 = iris_pd[iris_pd['species']!=0]
iris_12.info()
열역학의 용어로 물질의 열적 상태를 나타내는 물리 량의 단위 중 하나. 무질서의 정도를 나타냄
엔트로피 : 얼마만큼의 정보를 담고 있는가? 또한, 무질서도를 의미, 불확실성을 나타내기도
엔트로피가 내려가면 분할 하는 것이 좋다
엔트로피의 계산량이 많아서 비슷한 개념이면서 보다 계산량이 적은 지니계수를 사용하는 경우가 많다.
from sklearn.tree import plot_tree
plt.figure(figsize=(12,8))
plot_tree(iris_tree)
우리가 느껴야할 것은?
-> 복잡한 경계선
Accuracy가 높게 나왔다고 해도 좀 더 들여다 볼 필요가 당연히 있다.
plt.figure(figsize=(12,8))
plot_tree(iris_tree)
import matplotlib.pyplot as plt
from mlxtend.plotting import plot_decision_regions
plt.figure(figsize=(12,8))
plot_decision_regions(X=X_train, y=y_train, clf=iris_tree, legend=2)
plt.show()
import matplotlib.pyplot as plt
from mlxtend.plotting import plot_decision_regions
plt.figure(figsize=(12,8))
plot_decision_regions(X=X_test, y=y_test, clf=iris_tree, legend=2)
plt.show()
scatter_highlight_kwargs = {'s':150, 'label': 'Test data', 'alpha': 0.9}
scatter_kwargs = {'s': 120, 'edgecolor':None, 'alpha':0.7}
plt.figure(figsize=(12,8))
plot_decision_regions(X=featrues, y=labels,
X_highlight=X_test, clf=iris_tree, legend=2,
scatter_highlight_kwargs=scatter_highlight_kwargs,
scatter_kwargs=scatter_kwargs,
contourf_kwargs={'alpha':0.2})
plt.show()
featrues = iris.data
labels = iris.target
X_train, X_test, y_train, y_test = train_test_split(featrues, labels,
test_size=0.2,
stratify=labels,
random_state=13)
iris_tree = DecisionTreeClassifier(max_depth=2, random_state=13)
iris_tree.fit(X_train, y_train)
import matplotlib.pyplot as plt
import seaborn as sns
# %matplotlib inline
f, ax = plt.subplots(1,2, figsize=(12,6))
titanic['survived'].value_counts().plot.pie(explode=[0,0.05],
autopct = '%1.1f%%', ax=ax[0], shadow=True)
ax[0].set_title('Pie plot - Survived')
ax[0].set_ylabel('')
sns.countplot(x='survived', data=titanic, ax=ax[1])
ax[1].set_title('Count plot - Survived')
f, ax = plt.subplots(1,2, figsize=(12,6))
sns.countplot(x='sex', data=titanic, ax=ax[0])
ax[0].set_title('Count of Passengers of Sex')
ax[0].set_ylabel('')
sns.countplot(x='sex', hue = 'survived', data=titanic, ax=ax[1])
ax[1].set_title('Sex:Survived and Unsurvived')
grid = sns.FacetGrid(titanic, row='pclass', col='sex', height=4, aspect=2)
grid.map(plt.hist, 'age', alpha=.8, bins=20)
grid.add_legend();
import plotly.express as px
fig = px.histogram(titanic, x='age')
fig.show()
grid = sns.FacetGrid(titanic, col='survived', row='pclass', height=4, aspect=2)
grid.map(plt.hist, 'age', alpha=.5, bins=20)
grid.add_legend();
plt.figure(figsize=(12,4))
plt.subplot(131)
sns.barplot(x='pclass',y='survived',data=titanic)
plt.subplot(132)
sns.barplot(x='age_cat',y='survived',data=titanic)
plt.subplot(133)
sns.barplot(x='sex',y='survived',data=titanic)
plt.subplots_adjust(top=1, bottom=0.1, left=0.1, right=1, hspace=0.5, wspace=0.5)
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14,6))
women = titanic[titanic['sex']=='female']
men = titanic[titanic['sex']== 'male']
ax = sns.distplot(women[women['survived']==1]['age'], bins=20,
label = 'survived', ax = axes[0], kde=False)
ax = sns.distplot(women[women['survived']==0]['age'], bins=40,
label = 'not_survived', ax = axes[0], kde=False)
ax.legend(); ax.set_title('Female')
ax = sns.distplot(men[men['survived']==1]['age'], bins=18,
label = 'survived', ax = axes[1], kde=False)
ax = sns.distplot(men[men['survived']==0]['age'], bins=40,
label = 'not_survived', ax = axes[1], kde=False)
ax.legend(); ax = ax.set_title('Male')
import re
titles = []
for idx, dataset in titanic.iterrows():
match = re.search('\s\w+\.', dataset['name'])
if match:
title = match.group()[1:-1]
if title in ['Miss', 'Master', 'Mrs', 'Mr','Col','Mme']:
titles.append(title)
else:
titles.append('unknown')
else:
titles.append('unknown')
titanic['title'] = titles
titanic.head()
titanic['title'] = titanic['title'].replace('Mlle','Miss')
titanic['title'] = titanic['title'].replace('Ms','Miss')
titanic['title'] = titanic['title'].replace('Mme','Mrs')
Rare_f = ['Dona','Lady','unknown']
Rare_m = ['Capt','Col','Dr','Don','Major','Rev','Sir','Jonkheer','Master']
for each in Rare_f:
titanic['title'] = titanic['title'].replace(each, 'Rare_f')
for each in Rare_m:
titanic['title'] = titanic['title'].replace(each, 'Rare_m')
from sklearn.model_selection import train_test_split
X = titanic[['pclass','age','sibsp','parch','fare','gender']]
y = titanic['survived']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=13)
문자를 숫자로 바꿔주는 데 유용하다.
정규화 시키는 과정
표준화 시키는 과정
아웃라이어의 영향을 최소화한다
wine.ipynb 참고
wine data를 불러온뒤