3D to 2D Dimensionality Reduction with PCA: A Python Visualization
Explore dimensionality reduction using Principal Component Analysis (PCA) with this Python script. It visualizes a 3D spiral dataset and its 2D projection using matplotlib and scikit-learn, showcasing the power of PCA. See how to transform high-dimensional data into a lower-dimensional space.
PythonAI
AG
Ala GARBAA 🚀 Full-Stack & DevOps Engineer
Check out the code and output, and try running the notebook yourself on Colab:
To install the necessary libraries for the provided script, run the following command:
pip install numpy matplotlib scikit-learn
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.decomposition import PCA
# Generate sample 3D data (spiral)
t = np.linspace(0, 10, 1000)
x = t * np.cos(t)
y = t * np.sin(t)
z = t
data_3d = np.column_stack((x, y, z))
# Apply PCA for dimensionality reduction
pca = PCA(n_components=2)
data_2d = pca.fit_transform(data_3d)
# Create subplots
fig = plt.figure(figsize=(12, 5), facecolor='none') # Set figure background transparent
# Set figure-level text color
plt.rcParams['text.color'] = 'white'
plt.rcParams['axes.labelcolor'] = 'white'
plt.rcParams['xtick.color'] = 'white'
plt.rcParams['ytick.color'] = 'white'
# Plot original 3D data
ax1 = fig.add_subplot(121, projection='3d')
ax1.scatter(x, y, z, c=t, cmap='viridis')
ax1.set_title('Original 3D Data', color='white')
ax1.set_xlabel('X', color='white')
ax1.set_ylabel('Y', color='white')
ax1.set_zlabel('Z', color='white')
ax1.set_facecolor('none') # Set subplot background transparent
ax1.tick_params(colors='white')
# Plot reduced 2D data
ax2 = fig.add_subplot(122)
scatter = ax2.scatter(data_2d[:, 0], data_2d[:, 1], c=t, cmap='viridis')
ax2.set_title('Reduced 2D Data', color='white')
ax2.set_xlabel('First Principal Component', color='white')
ax2.set_ylabel('Second Principal Component', color='white')
ax2.set_facecolor('none') # Set subplot background transparent
ax2.tick_params(colors='white')
# Add white border colors
for spine in ax2.spines.values():
spine.set_color('white')
# Add colorbar with white label and border
cbar = plt.colorbar(scatter)
cbar.ax.yaxis.set_tick_params(color='white')
cbar.ax.yaxis.label.set_color('white')
for t in cbar.ax.get_yticklabels():
t.set_color('white')
# Add white border to colorbar
cbar.outline.set_edgecolor('white')
plt.tight_layout()
# Save with transparent background
plt.savefig('dimensionality_reduction.png', transparent=True, bbox_inches='tight', dpi=300)
plt.show()