PCA (Temel Bileşenler Analizi)
Birbiriyle ilişkili çok sayıda değişkeni daha az sayıda yeni eksene nasıl indirgeriz? PCA’nın temel bileşenleri oluşturma mantığını, açıklanan varyans oranını ve scikit-learn ile çok değişkenli bir veri setinde uygulamayı keşfedin.
- Makine Öğrenmesi
- İstatistik

PCA nedir?
Temel Bileşenler Analizi (Principal Component Analysis, PCA), çok sayıdaki sayısal özelliği, verideki değişkenliğin büyük bölümünü koruyacak daha az sayıda yeni değişkene dönüştüren doğrusal boyut indirgeme yöntemidir. Yeni eksenler temel bileşenler olarak adlandırılır.
PCA etiketleri veya sonuç değişkenini kullanmadan özelliklerdeki varyansı inceler; bu nedenle yaygın biçimde denetimsiz bir keşif/dönüştürme yöntemi olarak kullanılır. Boyut azaltma, görselleştirme, gürültü azaltma ve bazı modelleme iş akışlarında yardımcı olabilir.
Temel bileşenler nasıl oluşturulur?
- Özellikleri ortalamadan merkezle; ölçekleri karşılaştırılabilir değilse standartlaştır.
- Değişkenler arasındaki kovaryans/ilişki yapısını hesapla veya verinin tekil değer ayrışımını (SVD) kullan.
- Varyansı en yüksek yönü birinci bileşen (PC1) olarak seç.
- PC1’e dik ve kalan varyansı en çok açıklayan yönü PC2 olarak seç; sonraki bileşenler de önceki bileşenlere diktir.
- Her gözlemi bu yeni eksenlere izdüşürerek bileşen skorlarını üret.
Her bileşen, orijinal değişkenlerin ağırlıklı doğrusal birleşimidir. Bileşenler birbirleriyle doğrusal olarak ilişkisizdir; fakat bu, orijinal değişkenlerin bağımsız olduğu veya bileşenlerin doğrudan nedensel anlam taşıdığı anlamına gelmez.
Açıklanan varyans oranı ne demektir?
Bir bileşenin açıkladığı varyans, o bileşen doğrultusundaki veri değişkenliğini özetler. Açıklanan varyans oranı, o bileşenin varyansının tüm bileşenlerin toplam varyansına oranıdır. Örneğin PC1’in oranı 0.60 ise, kullanılan ölçekleme ve veri kümesi altında toplam varyansın yaklaşık %60’ı ilk bileşen yönündedir.
İlk birkaç bileşenin oranlarını toplamak, bu bileşenlerle korunmuş toplam varyans payını verir. Daha fazla varyans tutmak genellikle daha fazla bileşen gerektirir; boyut azaltmanın amacı ise kabul edilebilir bilgi kaybı karşılığında daha yalın temsil elde etmektir.
Ölçekleme neden önemlidir?
PCA, varyansı en yüksek yönleri aradığı için büyük ölçekte ölçülen bir değişken sonucu domine edebilir. Örneğin santimetre cinsinden uzunluk ile binlerce birimlik yıllık gelir aynı tabloda ise, ölçekleme olmadan PCA gelir sütununu daha baskın görebilir.
Özellikler farklı birim ve aralıklardaysa genellikle StandardScaler ile her değişkeni ortalama 0 ve standart sapma 1 olacak şekilde standardize etmek uygundur. Değişkenler zaten benzer ölçekteyse veya mutlak varyansların alan anlamı korunmalıysa ölçekleme kararı ayrıca düşünülmelidir. StandardScaler aykırı değerlere duyarlı olduğu için PCA öncesi uç değerleri de inceleyin.
Python uygulaması: Iris veri seti
Iris veri seti, 150 çiçeğin dört ölçümünü içerir: çanak yaprak uzunluğu/genişliği ve taç yaprak uzunluğu/genişliği. PCA’yı yalnızca bu dört ölçüm üzerinde eğiteceğiz; tür etiketlerini bileşenleri üretmekte kullanmayıp grafikte renk olarak göstereceğiz.
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
iris = load_iris(as_frame=True)
X = iris.data
species = iris.target # PCA eğitiminde kullanılmayacak
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
pca = PCA(n_components=2)
scores = pca.fit_transform(X_scaled)
score_df = pd.DataFrame(scores, columns=["PC1", "PC2"])
score_df["tur"] = species.map(dict(enumerate(iris.target_names)))
print(score_df.head())
Bu keşif amaçlı örnek bütün iris gözlemleriyle standardizasyon ve PCA’yı fit eder. Bir tahmin modeli kurup test performansı raporlayacaksanız önce train/test ayırın; scaler ve PCA’yı yalnızca eğitim verisinde fit edip test verisine transform uygulayın. Pipeline bu sızıntıyı önlemeye yardımcı olur.
Bileşen varyans oranlarını inceleme
explained = pca.explained_variance_ratio_
cumulative = explained.cumsum()
variance_table = pd.DataFrame({
"bilesen": ["PC1", "PC2"],
"aciklanan_oran": explained,
"birikimli_oran": cumulative
})
print(variance_table.round(3))
plt.bar(variance_table["bilesen"], explained)
plt.ylabel("Açıklanan varyans oranı")
plt.title("PCA bileşenlerinin açıkladığı varyans")
plt.tight_layout()
plt.show()
explained_variance_ratio_ bileşen başına oranları; bunların toplamı ise ilk iki bileşenin birlikte koruduğu varyans payını verir. Kümülatif oran hedeflediğiniz bilgi korunumu için kaç bileşen seçileceğine karar vermeye yardımcı olur; tek başına kesin eşik değildir.
İki bileşen üzerinde gözlemleri çizme
fig, ax = plt.subplots(figsize=(8, 6))
for name, group in score_df.groupby("tur"):
ax.scatter(group["PC1"], group["PC2"], label=name, alpha=0.75)
ax.set_xlabel(f"PC1 ({explained[0]:.1%} varyans)")
ax.set_ylabel(f"PC2 ({explained[1]:.1%} varyans)")
ax.set_title("Iris gözlemlerinin PCA izdüşümü")
ax.legend(title="Tür (yalnızca görsel etiket)")
plt.tight_layout()
plt.show()
Noktaların bileşen düzlemindeki yakınlığı, seçilen doğrusal dönüşüm altında örüntüleri görmeyi sağlar. İki boyutlu grafikte ayrışma görmek, yeni gözlemlerde sınıflandırma başarısını tek başına kanıtlamaz. Aynı şekilde görselde üst üste binme de tüm bileşenlerde grupların aynı olduğu anlamına gelmez.
Bileşen yükleri nasıl yorumlanır?
pca.components_ her bileşenin orijinal sütunlara verdiği ağırlıkları (yük vektörlerini) içerir. Büyük mutlak ağırlık, bileşenin o özellik ile daha güçlü doğrusal bileşimi olduğunu düşündürür; artı/eksi işaretler bileşen yönünü tanımlar. Bileşenin işaretini ters çevirmek matematiksel olarak aynı ekseni verir; bu yüzden işaretin kendisine aşırı anlam yüklemeyin.
loadings = pd.DataFrame(
pca.components_.T,
index=X.columns,
columns=["PC1", "PC2"]
)
print(loadings.round(3))
Yükleri alan bilgisiyle birlikte okuyun. PCA bileşenleri matematiksel yönlerdir; “genel büyüklük” veya “çiçek şekli” gibi adlandırmalar yorumlayıcı etiketlerdir, yöntemin kendiliğinden verdiği gerçekler değildir.
Kaç bileşen seçilmeli?
- Kümülatif açıklanan varyans: Analiz amacına göre makul bir korunmuş varyans düzeyi belirleyin ve bu düzeye kaç bileşende ulaşıldığını görün.
- Scree grafiği: Bileşen başına açıklanan varyansın azalmaya başladığı “dirsek” bölgesini keşfedin.
- Model performansı: PCA tahmin öncesi kullanılıyorsa bileşen sayısını yalnızca eğitim verisi içindeki çapraz doğrulamayla seçin.
- Yorumlanabilirlik ve maliyet: Daha az bileşen daha sade temsil sunar; ancak bilgi kaybı ve yorum kolaylığı arasında denge gerekir.
“%95 varyansı koru” yaygın bir sezgisel hedef olabilir, fakat her proje için doğru seçim değildir. Gürültü, görev hedefi ve sonraki modelin ihtiyacı farklı bir boyut seçimini destekleyebilir.
PCA’nın varsayımları ve sınırlılıkları
- PCA doğrusal dönüşümdür; karmaşık doğrusal olmayan manifold yapısını doğrudan temsil etmez.
- Varyansı en çok korumaya çalışır; sınıfları ayırmayı veya tahmin hatasını en aza indirmeyi hedeflemez.
- Ölçekleme ve aykırı değer kararı bileşenleri değiştirebilir.
- Bileşenler orijinal değişkenlerden daha zor yorumlanabilir; her biri çok sayıda değişkenin birleşimidir.
- Eksik değerleri doğrudan her iş akışında otomatik çözmez; uygun imputasyon gerekir.
- Train/test kullanılan modellemelerde PCA tüm veriye önceden fit edilirse test bilgisini öğrenmiş olur ve değerlendirme yanlılaşır.
Özet
PCA, ilişkili çok sayıdaki sayısal özelliği varyansı yüksek ve birbirine dik doğrusal bileşenlere dönüştürür. Açıklanan varyans oranı, her bileşenin toplam değişkenlikten ne kadarını taşıdığını belirtir. Özelliklerin ölçeğini değerlendirin, bileşen yüklerini ve grafikleri bağlamla yorumlayın; modelleme yapıyorsanız ölçekleyici ve PCA’yı yalnızca eğitim verisinde fit edin.
Kaynaklar
What is PCA?
Principal Component Analysis (PCA) is a linear dimensionality reduction method that turns a large set of numeric features into a smaller set of new variables while preserving most of the variability in the data. The new axes are called principal components.
PCA examines variance in the features without using labels or an outcome variable, which is why it is widely used as an unsupervised exploration and transformation method. It can help with dimension reduction, visualisation, noise reduction and some modelling workflows.
How are principal components built?
- Centre the features on their means; standardise them if their scales are not comparable.
- Compute the covariance/correlation structure between the variables, or use the singular value decomposition (SVD) of the data.
- Take the direction of highest variance as the first component (PC1).
- Take the direction perpendicular to PC1 that explains the most remaining variance as PC2; every later component is perpendicular to all the earlier ones.
- Project each observation onto these new axes to produce component scores.
Each component is a weighted linear combination of the original variables. The components are linearly uncorrelated with one another, but that does not mean the original variables are independent, or that the components carry causal meaning on their own.
What does the explained variance ratio mean?
The variance a component explains summarises the variability of the data along that component's direction. The explained variance ratio is that component's variance divided by the total variance of all components. If PC1's ratio is 0.60, then under the scaling and data set you used, roughly 60% of the total variance lies along the first component.
Adding up the ratios of the first few components gives the share of total variance those components retain. Keeping more variance usually means keeping more components; the point of dimension reduction is to get a leaner representation in exchange for an acceptable loss of information.
Why does scaling matter?
Because PCA looks for the directions of highest variance, a variable measured on a large scale can dominate the result. If a table holds a length in centimetres alongside an annual income in the thousands, PCA without scaling may treat the income column as far more prominent.
When features come in different units and ranges, standardising each variable to mean 0 and standard deviation 1 with StandardScaler is usually the right move. If the variables are already on similar scales, or if the domain meaning of the absolute variances must be preserved, the scaling decision needs separate thought. StandardScaler is sensitive to outliers, so inspect extreme values before running PCA as well.
Python example: the Iris data set
The Iris data set holds four measurements for 150 flowers: sepal length and width, petal length and width. We will fit PCA on those four measurements only; the species labels will not be used to produce the components, just as colour on the chart.
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
iris = load_iris(as_frame=True)
X = iris.data
species = iris.target # not used when fitting PCA
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
pca = PCA(n_components=2)
scores = pca.fit_transform(X_scaled)
score_df = pd.DataFrame(scores, columns=["PC1", "PC2"])
score_df["species"] = species.map(dict(enumerate(iris.target_names)))
print(score_df.head())
This exploratory example fits the standardisation and PCA on every iris observation. If you are building a prediction model and will report test performance, split train and test first; fit the scaler and PCA on the training data only and transform the test data. A pipeline helps prevent that leakage.
Inspecting the component variance ratios
explained = pca.explained_variance_ratio_
cumulative = explained.cumsum()
variance_table = pd.DataFrame({
"component": ["PC1", "PC2"],
"explained_ratio": explained,
"cumulative_ratio": cumulative
})
print(variance_table.round(3))
plt.bar(variance_table["component"], explained)
plt.ylabel("Explained variance ratio")
plt.title("Variance explained by the PCA components")
plt.tight_layout()
plt.show()
explained_variance_ratio_ gives the ratio per component, and their sum gives the share of variance the first two components retain together. The cumulative ratio helps you decide how many components to keep for the level of information you are targeting; it is not a hard threshold on its own.
Plotting the observations on two components
fig, ax = plt.subplots(figsize=(8, 6))
for name, group in score_df.groupby("species"):
ax.scatter(group["PC1"], group["PC2"], label=name, alpha=0.75)
ax.set_xlabel(f"PC1 ({explained[0]:.1%} variance)")
ax.set_ylabel(f"PC2 ({explained[1]:.1%} variance)")
ax.set_title("PCA projection of the iris observations")
ax.legend(title="Species (visual label only)")
plt.tight_layout()
plt.show()
How close the points sit in the component plane lets you see patterns under the chosen linear transformation. Seeing separation on a two-dimensional chart does not by itself prove classification performance on new observations. Equally, overlap in the picture does not mean the groups are identical across all components.
How do you read component loadings?
pca.components_ holds the weights (the loading vectors) each component gives to the original columns. A large absolute weight suggests the component is a stronger linear combination of that feature; the plus and minus signs define the component's direction. Flipping a component's sign gives mathematically the same axis, so do not read too much into the sign itself.
loadings = pd.DataFrame(
pca.components_.T,
index=X.columns,
columns=["PC1", "PC2"]
)
print(loadings.round(3))
Read the loadings together with domain knowledge. PCA components are mathematical directions; names like "overall size" or "flower shape" are interpretive labels, not facts the method hands you.
How many components should you keep?
- Cumulative explained variance: set a sensible level of retained variance for your purpose and see how many components reach it.
- Scree plot: look for the "elbow" where the variance explained per component starts to flatten.
- Model performance: if PCA feeds a prediction step, choose the component count by cross-validation inside the training data only.
- Interpretability and cost: fewer components give a simpler representation, but you are trading information loss against ease of interpretation.
"Keep 95% of the variance" is a common rule of thumb, but it is not the right choice for every project. Noise, the goal of the task and what the next model needs may all point to a different number.
Assumptions and limits of PCA
- PCA is a linear transformation; it does not directly represent complex non-linear manifold structure.
- It tries to retain the most variance; it does not aim to separate classes or minimise prediction error.
- Decisions about scaling and outliers can change the components.
- Components are harder to interpret than the original variables; each is a blend of many of them.
- It does not automatically resolve missing values in every workflow; you need suitable imputation.
- In train/test modelling, fitting PCA on all the data in advance means it has learned from the test set, biasing your evaluation.
Summary
PCA turns a large set of correlated numeric features into high-variance components that are perpendicular to each other. The explained variance ratio tells you how much of the total variability each component carries. Weigh up the scale of your features, read the loadings and the charts in context, and if you are modelling, fit the scaler and PCA on the training data alone.