Principal Component Analysis (PCA)

We will now proceed and apply Principal Component Analysis on the data, to further study it.
We start by computing its distance between each feature. We can clearly see the three species with one species very different from the other two.

Investigating the correlations we notice that our predictors have four dimensions, but three are very correlated.

By applying PCA, we are able to approximate this distance with just two dimensions, compressing the highly correlated dimensions. Using the summary function we can see the variability explained by each Principal Component.

The first two dimensions account for 97% of the variability. Thus we should be able to approximate the distance very well with two dimensions. We can visualize the results of the PCA and how the first two principal components are responsible for most of variance between species.
We compare the original data to the principal components, showing their variance by colors.

The first component is able to gather important informations of Sepal Length, Petal Length and Petal Width and the second component incorporates informations of Sepal Width.
PC1 drives most of the variability and is capable of separating the first third of samples (most blue), which is setosa. The second column, PC2, helps to separate the second and third thirds, versicolor and virginica.

We can see this better by plotting the first two PCs with color representing each species.

Since the PCA applies orthogonal transformation, the distance over the data is preserved, as shown below.

By applying PCA, we were able to reduce the number of dimensions and visualize the four-dimensional data with only two dimensions. We will now apply k-nearest neighbors (knn) technique to the first two principal components.

Knn over Principal Components

We apply knn to the first two principal components, representing the data.
We separate the data in training and test sets and apply PCA only to the training set.

We train the model based on the first two principal components. Here we will use the standard value for the parameter k.

It is necessary to apply the same transformation on the test set.

With just 2 dimensions we achieved a very good accuracy by applying Knn.
This dataset was small, presented few number of predictors and observations, however the purpose here was for illustration. PCA is a powerfull tool and better used to reduce big dimensions and to analyze big data sets.