Nice, How about pca = PCA(n_components=3), and plot 3d scatter?
- User
Nice, How about pca = PCA(n_components=3), and plot 3d scatter?
- Assistant
Nice, How about pca = PCA(n_components=3), and plot 3d scatter?
Certainly! Performing Principal Component Analysis (PCA) with three components and visualizing the results using a 3D scatter plot can provide deeper insights into your data's structure. Below is a step-by-step guide using Python's scikit-learn for PCA and matplotlib for 3D plotting.
I'll demonstrate this process using the popular Iris dataset, but you can adapt the code to your own dataset.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # Necessary for 3D plotting
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
For this example, we'll use the Iris dataset, which is readily available in scikit-learn. It's a multiclass dataset with 150 samples and 4 features.
# Load the Iris dataset
iris = load_iris()
X = iris.data # Features
y = iris.target # Target labels
target_names = iris.target_names
PCA is affected by the scale of the variables. It's a good practice to standardize the data before applying PCA.
# Standardize the features
scaler = StandardScaler()
X_std = scaler.fit_transform(X)
# Initialize PCA with 3 components
pca = PCA(n_components=3)
# Fit and transform the standardized data
X_pca = pca.fit_transform(X_std)
# Explained variance ratio
print("Explained variance ratio:", pca.explained_variance_ratio_)
Output:
Explained variance ratio: [0.45440118 0.24532334 0.19394293]
This output indicates how much variance each principal component captures from the data.
# Create a new figure for 3D plotting
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
# Define colors for different classes
colors = ['r', 'g', 'b']
# Plot each class with a different color
for target, color, target_name in zip([0, 1, 2], colors, target_names):
ax.scatter(
X_pca[y == target, 0],
X_pca[y == target, 1],
X_pca[y == target, 2],
label=target_name,
color=color,
s=50,
alpha=0.6,
edgecolors='w'
)
# Labeling the axes
ax.set_xlabel('Principal Component 1', fontsize=12)
ax.set_ylabel('Principal Component 2', fontsize=12)
ax.set_zlabel('Principal Component 3', fontsize=12)
# Set title
ax.set_title('3D PCA of Iris Dataset', fontsize=15)
# Show legend
ax.legend()
# Show the plot
plt.show()
Result:
You will see a 3D scatter plot where each point represents a sample from the Iris dataset, colored according to its class (e.g., Setosa, Versicolor, Virginica). The axes correspond to the first three principal components, which capture the most variance in the data.
For a more interactive visualization, you can use Plotly:
import plotly.express as px
# Create a DataFrame for Plotly
import pandas as pd
df_pca = pd.DataFrame(X_pca, columns=['PC1', 'PC2', 'PC3'])
df_pca['Species'] = [target_names[i] for i in y]
# Create an interactive 3D scatter plot
fig = px.scatter_3d(
df_pca, x='PC1', y='PC2', z='PC3',
color='Species',
size_max=18,
title='3D PCA of Iris Dataset'
)
fig.show()
This will generate an interactive 3D plot where you can rotate, zoom, and hover over points to get more information.
Interpretation of Components: While PCA reduces dimensionality, the principal components are linear combinations of the original features. Interpreting them can sometimes provide insights into which features contribute most to the variance.
Explained Variance: Always check the explained variance ratio to understand how much information is retained by the selected components. In the example above, the first three components explain approximately 89% of the variance.
Visualization Limits: While 3D plots can provide more information than 2D plots, they can also become cluttered and harder to interpret with large datasets. Interactive plots (like those from Plotly) can alleviate some of these issues.
Further Dimensionality Reduction: If you need to visualize data with more than three dimensions, consider techniques like t-SNE or UMAP, which are designed for high-dimensional data visualization.
Using PCA with three components and visualizing the results in 3D can offer a more comprehensive view of your data's structure. Whether you're exploring clusters, separations, or other patterns, 3D scatter plots are a valuable tool in your data analysis toolkit.
Feel free to adapt the code above to your specific dataset and requirements!
Not yet included in a published release.