from sklearn.datasets import load_iris
import pandas as pd
import numpy as np
import sklearn
import matplotlib.pyplot as plt
import koreanize_matplotlib
import seaborn as sns
iris_raw = sklearn.datasets.load_iris()
print(iris_raw['DESCR'])
.. _iris_dataset:
Iris plants dataset
--------------------
**Data Set Characteristics:**
:Number of Instances: 150 (50 in each of three classes)
:Number of Attributes: 4 numeric, predictive attributes and the class
:Attribute Information:
- sepal length in cm
- sepal width in cm
- petal length in cm
- petal width in cm
- class:
- Iris-Setosa
- Iris-Versicolour
- Iris-Virginica
:Summary Statistics:
============== ==== ==== ======= ===== ====================
Min Max Mean SD Class Correlation
============== ==== ==== ======= ===== ====================
sepal length: 4.3 7.9 5.84 0.83 0.7826
sepal width: 2.0 4.4 3.05 0.43 -0.4194
petal length: 1.0 6.9 3.76 1.76 0.9490 (high!)
petal width: 0.1 2.5 1.20 0.76 0.9565 (high!)
============== ==== ==== ======= ===== ====================
:Missing Attribute Values: None
:Class Distribution: 33.3% for each of 3 classes.
:Creator: R.A. Fisher
:Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
:Date: July, 1988
The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken
from Fisher's paper. Note that it's the same as in R, but not as in the UCI
Machine Learning Repository, which has two wrong data points.
This is perhaps the best known database to be found in the
pattern recognition literature. Fisher's paper is a classic in the field and
is referenced frequently to this day. (See Duda & Hart, for example.) The
data set contains 3 classes of 50 instances each, where each class refers to a
type of iris plant. One class is linearly separable from the other 2; the
latter are NOT linearly separable from each other.
|details-start|
**References**
|details-split|
- Fisher, R.A. "The use of multiple measurements in taxonomic problems"
Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to
Mathematical Statistics" (John Wiley, NY, 1950).
- Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.
(Q327.D83) John Wiley & Sons. ISBN 0-471-22361-1. See page 218.
- Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
Structure and Classification Rule for Recognition in Partially Exposed
Environments". IEEE Transactions on Pattern Analysis and Machine
Intelligence, Vol. PAMI-2, No. 1, 67-71.
- Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule". IEEE Transactions
on Information Theory, May 1972, 431-433.
- See also: 1988 MLC Proceedings, 54-64. Cheeseman et al"s AUTOCLASS II
conceptual clustering system finds 3 classes in the data.
- Many, many more ...
|details-end|
X, y = iris_raw['data'], iris_raw['target']
iris_df = pd.DataFrame(X, columns = iris_raw['feature_names'])
iris_df.head()
| sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | |
|---|---|---|---|---|
| 0 | 5.1 | 3.5 | 1.4 | 0.2 |
| 1 | 4.9 | 3.0 | 1.4 | 0.2 |
| 2 | 4.7 | 3.2 | 1.3 | 0.2 |
| 3 | 4.6 | 3.1 | 1.5 | 0.2 |
| 4 | 5.0 | 3.6 | 1.4 | 0.2 |
iris_df['species'] = iris_raw['target']
iris_df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 sepal length (cm) 150 non-null float64
1 sepal width (cm) 150 non-null float64
2 petal length (cm) 150 non-null float64
3 petal width (cm) 150 non-null float64
4 species 150 non-null int32
dtypes: float64(4), int32(1)
memory usage: 5.4 KB
iris_df
| sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | species | |
|---|---|---|---|---|---|
| 0 | 5.1 | 3.5 | 1.4 | 0.2 | 0 |
| 1 | 4.9 | 3.0 | 1.4 | 0.2 | 0 |
| 2 | 4.7 | 3.2 | 1.3 | 0.2 | 0 |
| 3 | 4.6 | 3.1 | 1.5 | 0.2 | 0 |
| 4 | 5.0 | 3.6 | 1.4 | 0.2 | 0 |
| ... | ... | ... | ... | ... | ... |
| 145 | 6.7 | 3.0 | 5.2 | 2.3 | 2 |
| 146 | 6.3 | 2.5 | 5.0 | 1.9 | 2 |
| 147 | 6.5 | 3.0 | 5.2 | 2.0 | 2 |
| 148 | 6.2 | 3.4 | 5.4 | 2.3 | 2 |
| 149 | 5.9 | 3.0 | 5.1 | 1.8 | 2 |
150 rows × 5 columns
iris_df.describe()
| sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | species | |
|---|---|---|---|---|---|
| count | 150.000000 | 150.000000 | 150.000000 | 150.000000 | 150.000000 |
| mean | 5.843333 | 3.057333 | 3.758000 | 1.199333 | 1.000000 |
| std | 0.828066 | 0.435866 | 1.765298 | 0.762238 | 0.819232 |
| min | 4.300000 | 2.000000 | 1.000000 | 0.100000 | 0.000000 |
| 25% | 5.100000 | 2.800000 | 1.600000 | 0.300000 | 0.000000 |
| 50% | 5.800000 | 3.000000 | 4.350000 | 1.300000 | 1.000000 |
| 75% | 6.400000 | 3.300000 | 5.100000 | 1.800000 | 2.000000 |
| max | 7.900000 | 4.400000 | 6.900000 | 2.500000 | 2.000000 |
sns.boxplot(data = iris_df, y = 'sepal length (cm)', x = 'species')
<Axes: xlabel='species', ylabel='sepal length (cm)'>

sns.boxplot(data = iris_df, x = 'species', y = 'sepal width (cm)')
<Axes: xlabel='species', ylabel='sepal width (cm)'>

sns.boxplot(data=iris_df, y='petal length (cm)', x='species')
<Axes: xlabel='species', ylabel='petal length (cm)'>

sns.boxplot(data=iris_df, x='species', y='petal width (cm)')
<Axes: xlabel='species', ylabel='petal width (cm)'>

sns.pairplot(iris_df, hue = 'species', palette= 'Set1')

sns.lmplot(iris_df, x='petal length (cm)', y='petal width (cm)', hue='species')
<seaborn.axisgrid.FacetGrid at 0x15bf62caf10>


plt.figure(figsize=(12,6))
sns.scatterplot(iris_df, x='petal length (cm)', y='petal width (cm)', hue = 'species', palette = 'Set1')
plt.show()

iris_12 = iris_df.loc[iris_df['species']!=0]
iris_12.info()
<class 'pandas.core.frame.DataFrame'>
Index: 100 entries, 50 to 149
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 sepal length (cm) 100 non-null float64
1 sepal width (cm) 100 non-null float64
2 petal length (cm) 100 non-null float64
3 petal width (cm) 100 non-null float64
4 species 100 non-null int32
dtypes: float64(4), int32(1)
memory usage: 4.3 KB
iris_12
| sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | species | |
|---|---|---|---|---|---|
| 50 | 7.0 | 3.2 | 4.7 | 1.4 | 1 |
| 51 | 6.4 | 3.2 | 4.5 | 1.5 | 1 |
| 52 | 6.9 | 3.1 | 4.9 | 1.5 | 1 |
| 53 | 5.5 | 2.3 | 4.0 | 1.3 | 1 |
| 54 | 6.5 | 2.8 | 4.6 | 1.5 | 1 |
| ... | ... | ... | ... | ... | ... |
| 145 | 6.7 | 3.0 | 5.2 | 2.3 | 2 |
| 146 | 6.3 | 2.5 | 5.0 | 1.9 | 2 |
| 147 | 6.5 | 3.0 | 5.2 | 2.0 | 2 |
| 148 | 6.2 | 3.4 | 5.4 | 2.3 | 2 |
| 149 | 5.9 | 3.0 | 5.1 | 1.8 | 2 |
100 rows × 5 columns
plt.figure(figsize=(12,6))
sns.scatterplot(data=iris_12, x='petal length (cm)', y='petal width (cm)', hue = 'species')
<Axes: xlabel='petal length (cm)', ylabel='petal width (cm)'>




-(10/16) * np.log2(10/16) - (6/16) * np.log2(6/16)
0.954434002924965

# 왼쪽 부분의 엔트로피(0.5를 곱해주는 것은 두 부분 중 하나를 선택할 확률)
0.5 * (-(7/8)*np.log2(7/8) - (1/8)*np.log2(1/8)) +\
0.5 * (-(3/8)*np.log2(3/8) - (5/8)*np.log2(5/8))
0.7489992230622807


1-((10/16)**2 + (6/16) ** 2)
0.46875

(0.5)*(1-((1/8)**2 + (7/8)**2) + (1-((3/8)**2 + (5/8)**2)))
0.34375

from sklearn.tree import DecisionTreeClassifier
dt = DecisionTreeClassifier(max_depth = 2, criterion ='entropy', random_state=2024)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X[:,2:], y,
stratify = y, test_size=0.2, random_state=2024)
# 테스트셋의 Accuracy Score
dt.fit(X_train, y_train)
dt.score(X_test, y_test)
0.9333333333333333
y_train_pred = dt.predict(X_train)
from sklearn.metrics import accuracy_score
accuracy_score(y_train, y_train_pred)
0.9583333333333334
y_pred = dt.predict(X_test)
y_pred
array([0, 2, 0, 1, 2, 0, 2, 1, 0, 1, 0, 1, 2, 2, 2, 2, 2, 0, 0, 1, 1, 1,
1, 0, 1, 2, 0, 0, 2, 1])
dt.predict_proba(X_train)
array([[1. , 0. , 0. ],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 1. , 0. ],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[0. , 1. , 0. ],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[0. , 0.11111111, 0.88888889],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[1. , 0. , 0. ],
[0. , 1. , 0. ],
[1. , 0. , 0. ]])
from sklearn.tree import plot_tree
plt.figure(figsize=(15,15))
plot_tree(dt,label='all',feature_names=iris_raw['feature_names'][2:],\
filled=True, precision=3);

from mlxtend.plotting import plot_decision_regions
plt.figure(figsize=(14,10))
plot_decision_regions(X=X_train, y=y_train_pred, clf=dt, legend=2)
plt.show()

plt.figure(figsize=(14,10))
plot_decision_regions(X=X_test, y=y_pred, clf=dt, legend=2)
plt.show()

from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import roc_auc_score
from mlxtend.plotting import plot_decision_regions
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import koreanize_matplotlib
import seaborn as sns
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,
stratify=y,random_state=2024)
dt_clf = DecisionTreeClassifier(max_depth=5, random_state=2024)
dt_clf.fit(X_train,y_train)
print(dt_clf.score(X_test,y_test))
0.9666666666666667
y_train_pred = dt_clf.predict(X_train)
print(accuracy_score(y_train, y_train_pred))
0.9916666666666667
tmp_data = np.array([[2, 1.5, 2, 3.3]])
dt_clf.predict(tmp_data)
array([1])
dt_clf.predict_proba(tmp_data)
array([[0., 1., 0.]])
dt_clf.classes_
array([0, 1, 2])
dt_clf.feature_importances_
array([0. , 0.01694915, 0.42021683, 0.56283402])
feature_importances = dict(zip(iris_raw.feature_names, dt_clf.feature_importances_))
feature_importances
{'sepal length (cm)': 0.0,
'sepal width (cm)': 0.016949152542372878,
'petal length (cm)': 0.42021682699648794,
'petal width (cm)': 0.5628340204611392}
pairs = ('a',1), ('b',2), ('c',3)
dict(pairs)
{'a': 1, 'b': 2, 'c': 3}
a = list(zip(*pairs))
b = list(a[0])
c = list(a[1])
print(b, c)
['a', 'b', 'c'] [1, 2, 3]
titanic_df = pd.read_excel('../titanic/titanic.xls')
titanic_df.head()
| pclass | survived | name | sex | age | sibsp | parch | ticket | fare | cabin | embarked | boat | body | home.dest | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | Allen, Miss. Elisabeth Walton | female | 29.0000 | 0 | 0 | 24160 | 211.3375 | B5 | S | 2 | NaN | St Louis, MO |
| 1 | 1 | 1 | Allison, Master. Hudson Trevor | male | 0.9167 | 1 | 2 | 113781 | 151.5500 | C22 C26 | S | 11 | NaN | Montreal, PQ / Chesterville, ON |
| 2 | 1 | 0 | Allison, Miss. Helen Loraine | female | 2.0000 | 1 | 2 | 113781 | 151.5500 | C22 C26 | S | NaN | NaN | Montreal, PQ / Chesterville, ON |
| 3 | 1 | 0 | Allison, Mr. Hudson Joshua Creighton | male | 30.0000 | 1 | 2 | 113781 | 151.5500 | C22 C26 | S | NaN | 135.0 | Montreal, PQ / Chesterville, ON |
| 4 | 1 | 0 | Allison, Mrs. Hudson J C (Bessie Waldo Daniels) | female | 25.0000 | 1 | 2 | 113781 | 151.5500 | C22 C26 | S | NaN | NaN | Montreal, PQ / Chesterville, ON |
titanic_df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1309 entries, 0 to 1308
Data columns (total 14 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 pclass 1309 non-null int64
1 survived 1309 non-null int64
2 name 1309 non-null object
3 sex 1309 non-null object
4 age 1046 non-null float64
5 sibsp 1309 non-null int64
6 parch 1309 non-null int64
7 ticket 1309 non-null object
8 fare 1308 non-null float64
9 cabin 295 non-null object
10 embarked 1307 non-null object
11 boat 486 non-null object
12 body 121 non-null float64
13 home.dest 745 non-null object
dtypes: float64(3), int64(4), object(7)
memory usage: 143.3+ KB
titanic_df.describe(exclude='object')
| pclass | survived | age | sibsp | parch | fare | body | |
|---|---|---|---|---|---|---|---|
| count | 1309.000000 | 1309.000000 | 1046.000000 | 1309.000000 | 1309.000000 | 1308.000000 | 121.000000 |
| mean | 2.294882 | 0.381971 | 29.881135 | 0.498854 | 0.385027 | 33.295479 | 160.809917 |
| std | 0.837836 | 0.486055 | 14.413500 | 1.041658 | 0.865560 | 51.758668 | 97.696922 |
| min | 1.000000 | 0.000000 | 0.166700 | 0.000000 | 0.000000 | 0.000000 | 1.000000 |
| 25% | 2.000000 | 0.000000 | 21.000000 | 0.000000 | 0.000000 | 7.895800 | 72.000000 |
| 50% | 3.000000 | 0.000000 | 28.000000 | 0.000000 | 0.000000 | 14.454200 | 155.000000 |
| 75% | 3.000000 | 1.000000 | 39.000000 | 1.000000 | 0.000000 | 31.275000 | 256.000000 |
| max | 3.000000 | 1.000000 | 80.000000 | 8.000000 | 9.000000 | 512.329200 | 328.000000 |
titanic_df.describe(exclude='number')
| name | sex | ticket | cabin | embarked | boat | home.dest | |
|---|---|---|---|---|---|---|---|
| count | 1309 | 1309 | 1309 | 295 | 1307 | 486 | 745 |
| unique | 1307 | 2 | 939 | 186 | 3 | 28 | 369 |
| top | Connolly, Miss. Kate | male | CA. 2343 | C23 C25 C27 | S | 13 | New York, NY |
| freq | 2 | 843 | 11 | 6 | 914 | 39 | 64 |
survival_cnt = titanic_df['survived'].value_counts()
sex_cnt = titanic_df['sex'].value_counts()
fig, ax = plt.subplots(1,2, figsize=(20,13))
ax[0].pie(survival_cnt, autopct = '%1.1f%%', explode = [0, 0.05],
labels=['Not Survived','Survived']);
sns.countplot(data=titanic_df, x='survived',hue='sex',ax=ax[1])
<Axes: xlabel='survived', ylabel='count'>

import numpy as np
fig, ax = plt.subplots(1,2, figsize=(20,12))
sns.countplot(data=titanic_df, x='sex',ax=ax[0])
sns.countplot(data=titanic_df,x='sex',hue='survived',ax=ax[1])
plt.show();

pd.crosstab(titanic_df['pclass'], titanic_df['survived'], margins=True)
| survived | 0 | 1 | All |
|---|---|---|---|
| pclass | |||
| 1 | 123 | 200 | 323 |
| 2 | 158 | 119 | 277 |
| 3 | 528 | 181 | 709 |
| All | 809 | 500 | 1309 |
grid = sns.FacetGrid(titanic_df, row='pclass',col='survived', height=4, aspect=2,dropna=True)
grid.map(plt.hist, 'age',alpha=0.5,bins=20)
grid.add_legend();

titanic_df['age_bin'] = pd.cut(titanic_df['age'], bins = [0,7,15,30,60,100],
include_lowest=True, labels=['baby','teen','young',
'adult','old'])
titanic_df.head()
| pclass | survived | name | sex | age | sibsp | parch | ticket | fare | cabin | embarked | boat | body | home.dest | age_bin | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | Allen, Miss. Elisabeth Walton | female | 29.0000 | 0 | 0 | 24160 | 211.3375 | B5 | S | 2 | NaN | St Louis, MO | young |
| 1 | 1 | 1 | Allison, Master. Hudson Trevor | male | 0.9167 | 1 | 2 | 113781 | 151.5500 | C22 C26 | S | 11 | NaN | Montreal, PQ / Chesterville, ON | baby |
| 2 | 1 | 0 | Allison, Miss. Helen Loraine | female | 2.0000 | 1 | 2 | 113781 | 151.5500 | C22 C26 | S | NaN | NaN | Montreal, PQ / Chesterville, ON | baby |
| 3 | 1 | 0 | Allison, Mr. Hudson Joshua Creighton | male | 30.0000 | 1 | 2 | 113781 | 151.5500 | C22 C26 | S | NaN | 135.0 | Montreal, PQ / Chesterville, ON | young |
| 4 | 1 | 0 | Allison, Mrs. Hudson J C (Bessie Waldo Daniels) | female | 25.0000 | 1 | 2 | 113781 | 151.5500 | C22 C26 | S | NaN | NaN | Montreal, PQ / Chesterville, ON | young |
plt.figure(figsize=(16,8))
plt.subplot(131)
sns.barplot(data=titanic_df, x='pclass',y='survived')
plt.subplot(132)
sns.barplot(data=titanic_df, x='sex', y='survived')
plt.subplot(133)
sns.barplot(data=titanic_df, x='age_bin', y='survived')
plt.show()
C:\Users\kd010\miniconda3\Lib\site-packages\seaborn\categorical.py:641: FutureWarning: The default of observed=False is deprecated and will be changed to True in a future version of pandas. Pass observed=False to retain current behavior or observed=True to adopt the future default and silence this warning.
grouped_vals = vals.groupby(grouper)
