0Pricing
Machine Learning Academy · บทเรียน

PCA: ความแปรปรวน เวกเตอร์ลักษณะเฉพาะ และองค์ประกอบหลัก

ผู้เรียนจะฝึก PCA กับชุดข้อมูลมิติสูง ตรวจสอบสัดส่วนความแปรปรวนที่อธิบายได้ และเลือกจำนวนองค์ประกอบที่รักษาความแปรปรวนรวมไว้ได้ 95%

PCA: ความแปรปรวน เวกเตอร์ลักษณะเฉพาะ และองค์ประกอบหลัก เป็นบทเรียน Machine Learning Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Machine Learning Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

The Problem with High-Dimensional Data

As feature count grows, datasets become increasingly sparse — the curse of dimensionality. Many features are redundant or correlated, carrying overlapping information. Principal Component Analysis (PCA) solves this by finding a new, smaller set of axes (principal components) that capture the maximum variance in the data with the fewest dimensions.

Variance: What PCA Maximises

PCA seeks directions in feature space along which the data varies the most. A direction with high variance captures rich information; a direction with near-zero variance is essentially noise. The first principal component (PC1) is the direction of maximum variance, PC2 is orthogonal to PC1 with the next highest variance, and so on.

Covariance Matrix and Eigenvectors

PCA operates on the covariance matrix of the centred data. The eigenvectors of this matrix point in the directions of maximum variance, and the corresponding eigenvalues measure how much variance each direction captures. The eigenvectors are the principal components; sorting them by eigenvalue in descending order gives PC1, PC2, ... PCn.

import numpy as np

X = np.array([[2.5, 2.4], [0.5, 0.7], [2.2, 2.9],
              [1.9, 2.2], [3.1, 3.0], [2.3, 2.7]])

# Centre the data
X_centered = X - X.mean(axis=0)

# Compute covariance matrix
cov = np.cov(X_centered.T)
print('Covariance matrix:\n', cov)

# Eigenvectors and eigenvalues
eigenvalues, eigenvectors = np.linalg.eigh(cov)
idx = np.argsort(eigenvalues)[::-1]
print('Eigenvalues:', eigenvalues[idx])
print('PC1 direction:', eigenvectors[:, idx[0]])

Explained Variance Ratio

The explained variance ratio of each component is its eigenvalue divided by the sum of all eigenvalues. If PC1 explains 90% of variance and PC2 explains 8%, the first two components together retain 98% of all information. This ratio guides how many components to keep — a common threshold is 95%.

from sklearn.decomposition import PCA
from sklearn.datasets import load_digits

X, _ = load_digits(return_X_y=True)  # 64 features

pca = PCA()
pca.fit(X)

cumulative_variance = pca.explained_variance_ratio_.cumsum()
n_95 = (cumulative_variance < 0.95).sum() + 1

print(f'Components to retain 95% variance: {n_95}')
print(f'Explained by first 10 components: {cumulative_variance[9]:.3f}')

Choosing n_components

Set n_components as an integer (e.g., PCA(n_components=10)) to keep exactly 10 components, or as a float between 0 and 1 (e.g., PCA(n_components=0.95)) to automatically keep enough components to explain that fraction of variance. The latter is the cleanest approach for pipelines where you want variance-based truncation without knowing the count upfront.

from sklearn.decomposition import PCA
from sklearn.datasets import load_digits

X, _ = load_digits(return_X_y=True)

# Retain 95% of variance automatically
pca = PCA(n_components=0.95)
pca.fit(X)

print('Number of components chosen:', pca.n_components_)
print('Total variance retained:', pca.explained_variance_ratio_.sum().round(4))

The Scree Plot

A scree plot shows explained variance ratio (or eigenvalue) on the y-axis and component index on the x-axis. The plot typically shows a steep drop then a flat plateau. The elbow — where the drop becomes gradual — is another heuristic for the number of components to retain, similar to the elbow method in K-Means.

import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.datasets import load_wine

X, _ = load_wine(return_X_y=True)
pca = PCA()
pca.fit(X)

plt.figure(figsize=(8, 4))
plt.subplot(1, 2, 1)
plt.bar(range(1, 14), pca.explained_variance_ratio_)
plt.xlabel('Component')
plt.ylabel('Explained variance ratio')
plt.title('Scree Plot')
plt.subplot(1, 2, 2)
plt.plot(pca.explained_variance_ratio_.cumsum(), marker='o')
plt.axhline(0.95, color='red', linestyle='--')
plt.xlabel('Number of components')
plt.ylabel('Cumulative variance')
plt.tight_layout()
plt.show()

Centering and Scaling Before PCA

PCA is sensitive to feature scale. A feature measured in thousands will dominate the covariance matrix. Always standardise with StandardScaler before PCA to give each feature unit variance. Centring (zero mean) is essential — PCA implicitly does this, but if you use a Pipeline, the scaler should come first so PCA operates on already-centred, equal-scale features.

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.datasets import load_wine

X, _ = load_wine(return_X_y=True)

pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('pca', PCA(n_components=0.95))
])
pipe.fit(X)

print('Original shape:', X.shape)
print('Reduced shape:', pipe.transform(X).shape)

What Do Principal Components Represent?

Each principal component is a linear combination of the original features — a weighted sum. Inspecting the component loadings (the coefficients) reveals which original features contribute most to each PC. However, components are often not directly interpretable because they mix features together. PCA is primarily a compression tool, not a feature selection tool.

from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_wine
import pandas as pd

X, _ = load_wine(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X)

pca = PCA(n_components=2)
pca.fit(X_scaled)

feature_names = load_wine().feature_names
loadings = pd.DataFrame(pca.components_.T, index=feature_names,
                        columns=['PC1', 'PC2'])
print(loadings.round(2))

SVD: The Efficient Implementation

In practice, scikit-learn computes PCA via Singular Value Decomposition (SVD) rather than explicit eigendecomposition of the covariance matrix, because SVD is numerically more stable and works directly on the data matrix without forming the covariance matrix. The result is mathematically identical. For very large datasets, PCA(svd_solver='randomized') uses an approximate randomised SVD for speed.

PCA Is Linear and Orthogonal

Important limitations: PCA finds only linear relationships between features. If the meaningful structure in your data lies on a curved manifold (e.g., a Swiss roll), PCA will not discover it effectively — kernel PCA or t-SNE are better alternatives. Also, PCA components are orthogonal by construction, which can be a mismatch if your underlying factors are correlated.

PCA on a Real Dataset: Quick End-to-End

Here is the full workflow: scale, PCA to 2D, and scatter-plot with class colour to check if the reduced space still separates classes visually. This is a standard exploratory step before training a classifier on the full feature set.

from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt

X, y = load_iris(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X)

pca = PCA(n_components=2)
X_2d = pca.fit_transform(X_scaled)

plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y, cmap='Set1', s=30)
plt.xlabel(f'PC1 ({pca.explained_variance_ratio_[0]:.1%} var)')
plt.ylabel(f'PC2 ({pca.explained_variance_ratio_[1]:.1%} var)')
plt.title('Iris in PCA space')
plt.colorbar(label='Class')
plt.show()

Quick Check

Test your understanding of PCA from this lesson.

Lesson Recap

In this lesson you learned: PCA finds directions of maximum variance via the covariance matrix eigenvectors, explained variance ratio guides how many components to keep (typically aim for 95%), and always standardise features before PCA so scale differences do not bias the components. Next up we project data into principal-component space and reconstruct it to quantify information loss.

คำถามที่พบบ่อย

บทเรียน “PCA: ความแปรปรวน เวกเตอร์ลักษณะเฉพาะ และองค์ประกอบหลัก” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “PCA: ความแปรปรวน เวกเตอร์ลักษณะเฉพาะ และองค์ประกอบหลัก” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Machine Learning Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “PCA: ความแปรปรวน เวกเตอร์ลักษณะเฉพาะ และองค์ประกอบหลัก”

ผู้เรียนจะฝึก PCA กับชุดข้อมูลมิติสูง ตรวจสอบสัดส่วนความแปรปรวนที่อธิบายได้ และเลือกจำนวนองค์ประกอบที่รักษาความแปรปรวนรวมไว้ได้ 95% คุณปฏิบัติ Machine Learning Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Machine Learning Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Machine Learning Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “PCA: ความแปรปรวน เวกเตอร์ลักษณะเฉพาะ และองค์ประกอบหลัก” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Machine Learning Academy นี้ได้ไหม

ได้ บทเรียน Machine Learning Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. PCA: ความแปรปรวน เวกเตอร์ลักษณะเฉพาะ และองค์ประกอบหลัก
  2. การฉายข้อมูลและการสร้างข้อมูลกลับจากองค์ประกอบ
  3. t-SNE: การรักษาความใกล้เคียงสำหรับการแสดงภาพ
  4. PCA ในการเตรียมข้อมูล: ความเร็วและการลดสัญญาณรบกวนในไปป์ไลน์
← กลับไปที่ Machine Learning Academy