PCA Explained with Dynamic Plotly Visualizations
PCA Explained with Dynamic Plotly Visualizations

A practical guide on PCA and Plotly.

PCA (Principal component analysis) is an unsupervised learning algorithm that finds the relations among features within a dataset. It is also widely used as a preprocessing step for supervised learning algorithms.

The aim of using PCA is to reduce the number of features by finding principal components that explain the variance within the dataset as much as possible. The principal components are linear combinations of the features of original dataset.

The advantage of PCA is that a significant amount of variance of the original dataset is retained using much smaller number of features than the original dataset. Principal components are ordered according to the amount of variance they represent.

In this post, we will first implement a PCA algorithm and then create dynamic visualizations with Plotly to explain the idea behind the PCA more clearly.

This post is more of a practical one. If you want to go deeper on how PCA actually works, here is more detailed post on the theoretical side.

Plotly Python (plotly.py) is an open-source plotting library built on plotly javascript (plotly.js) and it offers a high-level API (plotly express) and a low level API (graph objects) to create dynamic and interactive visualizations. With plotly express, we can create a nice plot with very few lines of code. On the other hand, we need to write more code with graph objects but have more control on what we create.

Let’s start with importing the related libraries:

import numpy as np

import pandas as pd

from sklearn.decomposition import PCA

from sklearn.datasets import load_breast_cancer

I will use the breast cancer dataset which contains 30 features and a target variable indicating whether the cell is malignant or benign. To simplify the visualizations, I will randomly select 5 features.
['Soner Yıldırım']
['Machine Learning', 'Artificial Intelligence', 'Data Science', 'Programming', 'Data Visualization']