PCA with the iris data set¶
Preparing the Iris Dataset
For the following tutorial, we will be working with the famous "Iris" dataset that has been deposited on the UCI machine learning repository (https://archive.ics.uci.edu/ml/datasets/Iris).
The iris dataset contains measurements for 150 iris flowers from three different species.
The three classes in the Iris dataset are:
- Iris-setosa (n=50)
- Iris-versicolor (n=50)
- Iris-virginica (n=50)
And the four features of in Iris dataset are:
- sepal length in cm
- sepal width in cm
- petal length in cm
- petal width in cm
Loading the Dataset¶
In order to load the Iris data directly from the UCI repository, we are going to use the superb pandas library.
In [12]:
import numpy as np # linear algebra
import pandas as pd
from sklearn.decomposition import PCA
from sklearn import datasets
import seaborn as sns
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.style.use('seaborn-v0_8')
%matplotlib inline
Principal compomenet analysis¶
Import iris dataset and view as a dataframe¶
In [13]:
# import some data to play with
iris = datasets.load_iris()
df = pd.DataFrame(data=iris['data'],columns=iris['feature_names'])
df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
df.head()
Out[13]:
| sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | species | |
|---|---|---|---|---|---|
| 0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa |
| 1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa |
| 2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa |
| 3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa |
| 4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa |
Describe Features¶
In [14]:
sns.pairplot(data=df,kind='scatter', hue='species')
Out[14]:
<seaborn.axisgrid.PairGrid at 0x7f0b1d573110>
Conclusion¶
Three features describes relally good the classes so we could reduce the number of features to 3
In [17]:
reduced = PCA(n_components=3).fit_transform(df.iloc[:,0:4])
In [18]:
# plot
fig = plt.figure(figsize=(18, 10))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(reduced[:,0], reduced[:,1],reduced[:,2], c=iris.target, s=100)
ax.view_init(20, 90)
plt.show()
In [ ]: