Python ile Korelasyon Analizi
İki değişken birlikte nasıl değişiyor? Korelasyon katsayısı bu ilişkinin yönünü ve belirli bir örüntü türündeki gücünü özetler. Pearson ve Spearman yöntemlerini, katsayıların yorumunu ve Python ile görselleştirmeyi uygulamalı örneklerle inceleyin.
- İstatistik
- Araçlar

Korelasyon nedir?
Korelasyon, iki değişkenin birlikte değişme yönünü ve seçilen katsayıya göre ilişkinin gücünü özetleyen istatistiksel bir ölçüdür. Pozitif ilişki, bir değişken yükselirken diğerinin de yükselme eğiliminde olduğunu; negatif ilişki, biri yükselirken diğerinin düşme eğiliminde olduğunu anlatır. Sıfıra yakın katsayı, yöntemin ölçtüğü ilişki biçiminin zayıf olduğunu gösterir.
Korelasyon katsayıları genellikle −1 ile +1 arasında değer alır. İşaret yönü, mutlak büyüklük ise ilişkinin gücünü anlatır. Ancak “zayıf/orta/güçlü” eşikleri bağlama, alana ve örnekleme göre değişebilir; evrensel sınırlar gibi kullanılmamalıdır.
Pearson ve Spearman arasındaki fark
| Özellik | Pearson | Spearman |
|---|---|---|
| Ölçtüğü ilişki | Doğrusal ilişkinin yönü ve gücü | Sıralara dayalı monoton ilişkinin yönü ve gücü |
| Veri | Sayısal, eşleşmiş gözlemler | Sıralanabilir/sayısal eşleşmiş gözlemler |
| Uç değer | Duyarlı olabilir | Değerlerin büyüklüğü yerine sırasını kullandığı için daha dayanıklı olabilir; yine de etkilenebilir |
| İlişki biçimi | Noktalar yaklaşık doğru etrafındaysa uygun | İlişki tek yönde artıp/azalıyorsa doğrusal olmasa da yakalayabilir |
Pearson katsayısı kovaryansın standartlaştırılmış biçimidir ve doğrusal örüntüye odaklanır. Spearman, her gözlemi sıralara dönüştürüp sıralar arasındaki korelasyonu hesaplar; bu nedenle monoton ama doğrusal olmayan ilişkilerde yararlı olabilir. Spearman da her türlü ilişkiyi yakalamaz: U biçimli bir ilişki monoton olmadığından katsayısı küçük çıkabilir.
Katsayılar nasıl yorumlanır?
- İşaret: pozitif birlikte artış, negatif ters yönlü değişim eğilimi.
- Büyüklük: mutlak değer 1’e yaklaştıkça, yöntemin hedeflediği örüntü daha belirgin olur.
- Sıfıra yakınlık: doğrusal (Pearson) veya monoton (Spearman) ilişkinin zayıf olabileceğini gösterir; değişkenlerin bağımsız olduğunu tek başına kanıtlamaz.
- Örneklem ve bağlam: aynı katsayı farklı alanlarda farklı pratik anlam taşıyabilir. Örneklem sayısını, ölçüm kalitesini ve belirsizliği birlikte raporlayın.
Örneğin r = 0.82 güçlü pozitif doğrusal birlikteliğe işaret edebilir; bu, “X yüzde 82 oranında Y’ye neden olur” anlamına gelmez. Korelasyon katsayısı yüzde değildir ve tahmin doğruluğu ölçüsü olarak tek başına yorumlanmamalıdır.
Python örneği: çalışma süresi ve sınav puanı
Aşağıdaki küçük örnek, ders çalışma süresi arttıkça sınav puanının da artma eğiliminde olduğu sentetik veriyi kullanır. Gerçek analizde birimlerin, satırların aynı kişiye/döneme ait olduğunun ve eksik değerlerin nasıl ele alındığının kontrol edilmesi gerekir.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
df = pd.DataFrame({
"calisma_saati": [1, 2, 2.5, 3, 4, 5, 6, 7, 8],
"sinav_puani": [42, 50, 55, 57, 64, 72, 75, 84, 88]
})
# İlişki biçimini önce görsel olarak incele
sns.regplot(data=df, x="calisma_saati", y="sinav_puani")
plt.title("Çalışma süresi ve sınav puanı")
plt.xlabel("Çalışma saati")
plt.ylabel("Sınav puanı")
plt.tight_layout()
plt.show()
Dağılım grafiği doğrusal olmayan yapı, küme, aykırı gözlem veya eşit olmayan saçılma olup olmadığını görmeye yardım eder. Katsayıyı hesaplamadan önce çizmek, yanlış yöntemi seçme riskini azaltır.
Pearson korelasyonunu hesaplama
pandas ile korelasyon matrisi hesaplayabilir veya SciPy’den katsayı ve p-değerini birlikte alabilirsiniz. SciPy’nin pearsonr fonksiyonu Pearson korelasyon katsayısını ve sıfır korelasyon hipotezine yönelik p-değerini döndürür.
# pandas ile katsayı matrisi
pearson_matrix = df[["calisma_saati", "sinav_puani"]].corr(method="pearson")
print(pearson_matrix)
# SciPy ile katsayı ve test sonucu
pearson_result = stats.pearsonr(df["calisma_saati"], df["sinav_puani"])
print(f"r = {pearson_result.statistic:.3f}")
print(f"p-değeri = {pearson_result.pvalue:.4g}")
Bir p-değeri, sıfır korelasyon varsayımı altında gözlenen kadar uç bir sonucun ne kadar uyumlu olduğunu değerlendirmeye yardım eder. P-değeri etki büyüklüğü değildir; örneklem büyüdükçe küçük pratik ilişkiler de istatistiksel olarak anlamlı görünebilir. Katsayıyı, örneklem sayısını ve mümkünse güven aralığını birlikte raporlayın.
Spearman korelasyonunu hesaplama
Spearman yönteminde gözlemler sıralara dönüştürülür. Değişkenler arasında monoton bir artış/azalış varsa, ilişki doğrusal olmasa da bu yapı katsayıda görülebilir. Sıra temelli olması onu aykırı değerlere karşı Pearson’dan daha dayanıklı kılabilir; bu, uç değerleri göz ardı etmek için gerekçe değildir.
# pandas ile
spearman_matrix = df[["calisma_saati", "sinav_puani"]].corr(method="spearman")
print(spearman_matrix)
# SciPy ile katsayı ve p-değeri
spearman_result = stats.spearmanr(
df["calisma_saati"], df["sinav_puani"], nan_policy="omit"
)
print(f"rho = {spearman_result.statistic:.3f}")
print(f"p-değeri = {spearman_result.pvalue:.4g}")
İki katsayı benzer çıkarsa veri örüntüsü yaklaşık doğrusal olabilir; belirgin farklılık varsa monoton ama doğrusal olmayan ilişki, uç değer veya veri yapısı olasılığını inceleyin. Tek başına katsayı karşılaştırması sebebi açıklamaz; saçılım grafiği ve alan bilgisi gerekir.
Birden fazla değişken için korelasyon matrisi
Birden fazla sayısal değişkenin çiftler arası ilişkilerini pandas ile topluca hesaplayabilirsiniz. Pearson ve Spearman matrislerini ayrı inceleyin; eksik gözlemler varsa çift başına kullanılan örnek sayısı değişebilir.
numeric = df.select_dtypes(include="number")
pearson_corr = numeric.corr(method="pearson", min_periods=3)
spearman_corr = numeric.corr(method="spearman", min_periods=3)
sns.heatmap(pearson_corr, annot=True, cmap="vlag", vmin=-1, vmax=1, center=0)
plt.title("Pearson korelasyon matrisi")
plt.tight_layout()
plt.show()
min_periods bir katsayı hesaplamak için gereken en az eşleşmiş gözlem sayısını belirtir. Çok sayıda çift inceleniyorsa tesadüfen anlamlı görünen sonuçlar çıkabilir; çoklu test düzeltmesi ve önceden belirlenmiş araştırma soruları düşünülmelidir.
Sonuçları yorumlarken dikkat edin
- Doğrusal olmayan ilişki: Pearson sıfıra yakın olsa bile U biçimli güçlü bir yapı olabilir.
- Aykırı değer: Birkaç uç gözlem Pearson katsayısını ciddi biçimde değiştirebilir. Ham veriyi kontrol edin; gerekçesiz silmeyin.
- Üçüncü değişken: Yaş, sezon veya bölge gibi ortak etkenler iki değişkeni birlikte hareket ettirebilir.
- Toplulaştırma: Grup ortalamalarında görülen ilişki, bireysel düzeyde aynı olmayabilir (ekolojik yanılgı/Simpson paradoksu riski).
- Eksik veri: Çift bazında eksik gözlemleri dışarıda bırakmak örneklem bileşimini değiştirebilir; kaç satırın kullanıldığını raporlayın.
- Tekrarlı zaman gözlemleri: Zaman serilerinde trend veya otokorelasyon, standart anlamlılık testlerini etkileyebilir.
Özet
Pearson doğrusal ilişkiyi, Spearman ise sıralara dayalı monoton ilişkiyi ölçer. Katsayı yön ve ilişki gücü hakkında özet bilgi verir; nedensellik, bağımsızlık veya tahmin başarısı kanıtlamaz. Python’da hızlı keşif için pandas corr(), katsayıyla birlikte test sonucu için SciPy pearsonr() ve spearmanr() kullanılabilir. Önce grafiğe bakın, sonra sayıyı bağlam içinde yorumlayın.
Kaynaklar
What is correlation?
Correlation is a statistical measure that summarises the direction in which two variables move together and, according to the coefficient you choose, the strength of that relationship. A positive relationship means one variable tends to rise as the other rises; a negative one means one tends to fall as the other rises. A coefficient near zero means the kind of relationship the method measures is weak.
Correlation coefficients usually range from −1 to +1. The sign gives the direction and the absolute magnitude the strength. But the thresholds for "weak", "moderate" and "strong" vary with context, field and sample; they should not be treated as universal boundaries.
The difference between Pearson and Spearman
| Feature | Pearson | Spearman |
|---|---|---|
| What it measures | The direction and strength of a linear relationship | The direction and strength of a rank-based monotonic relationship |
| Data | Numeric, paired observations | Rankable or numeric paired observations |
| Outliers | Can be sensitive | More robust, since it uses ranks rather than magnitudes; still not immune |
| Shape of the relationship | Suitable when the points sit roughly around a line | Can capture a relationship that rises or falls consistently even if it is not linear |
The Pearson coefficient is a standardised form of covariance and focuses on linear patterns. Spearman converts every observation to a rank and computes the correlation between the ranks, which makes it useful for monotonic but non-linear relationships. Spearman does not catch every relationship either: a U-shaped relationship is not monotonic, so its coefficient can come out small.
How do you read the coefficients?
- Sign: positive means they tend to rise together, negative means they tend to move in opposite directions.
- Magnitude: the closer the absolute value is to 1, the more pronounced the pattern the method targets.
- Closeness to zero: suggests the linear (Pearson) or monotonic (Spearman) relationship may be weak; it does not on its own prove the variables are independent.
- Sample and context: the same coefficient can carry very different practical meaning in different fields. Report the sample size, measurement quality and uncertainty alongside it.
An r = 0.82 may point to a strong positive linear association; it does not mean "X causes Y 82% of the time". A correlation coefficient is not a percentage and should not be read on its own as a measure of predictive accuracy.
A Python example: study time and exam score
The small example below uses synthetic data in which exam scores tend to rise with study time. In real analysis you have to check the units, confirm that rows belong to the same person or period, and decide how missing values are handled.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
df = pd.DataFrame({
"study_hours": [1, 2, 2.5, 3, 4, 5, 6, 7, 8],
"exam_score": [42, 50, 55, 57, 64, 72, 75, 84, 88]
})
# Look at the shape of the relationship first
sns.regplot(data=df, x="study_hours", y="exam_score")
plt.title("Study time and exam score")
plt.xlabel("Study hours")
plt.ylabel("Exam score")
plt.tight_layout()
plt.show()
A scatter plot helps you see non-linear structure, clusters, outlying observations or uneven spread. Plotting before computing the coefficient lowers the risk of choosing the wrong method.
Computing the Pearson correlation
You can compute a correlation matrix with pandas, or get the coefficient and the p-value together from SciPy. SciPy's pearsonr returns the Pearson correlation coefficient and a p-value for the hypothesis of zero correlation.
# the coefficient matrix with pandas
pearson_matrix = df[["study_hours", "exam_score"]].corr(method="pearson")
print(pearson_matrix)
# coefficient and test result with SciPy
pearson_result = stats.pearsonr(df["study_hours"], df["exam_score"])
print(f"r = {pearson_result.statistic:.3f}")
print(f"p-value = {pearson_result.pvalue:.4g}")
A p-value helps you judge how compatible a result this extreme is with the assumption of zero correlation. It is not an effect size; as the sample grows, small practical relationships can still look statistically significant. Report the coefficient, the sample size and, where you can, a confidence interval together.
Computing the Spearman correlation
The Spearman method turns the observations into ranks. If the variables increase or decrease together consistently, that structure shows up in the coefficient even when the relationship is not linear. Being rank-based can make it more robust to outliers than Pearson; that is not a reason to ignore extreme values.
# with pandas
spearman_matrix = df[["study_hours", "exam_score"]].corr(method="spearman")
print(spearman_matrix)
# coefficient and p-value with SciPy
spearman_result = stats.spearmanr(
df["study_hours"], df["exam_score"], nan_policy="omit"
)
print(f"rho = {spearman_result.statistic:.3f}")
print(f"p-value = {spearman_result.pvalue:.4g}")
If the two coefficients come out similar, the pattern in the data may be roughly linear; if they differ noticeably, investigate a monotonic but non-linear relationship, outliers or the structure of the data. Comparing coefficients does not explain the cause on its own; you need the scatter plot and domain knowledge.
A correlation matrix for several variables
You can compute pairwise relationships across several numeric variables at once with pandas. Examine the Pearson and Spearman matrices separately; where observations are missing, the sample size used per pair can vary.
numeric = df.select_dtypes(include="number")
pearson_corr = numeric.corr(method="pearson", min_periods=3)
spearman_corr = numeric.corr(method="spearman", min_periods=3)
sns.heatmap(pearson_corr, annot=True, cmap="vlag", vmin=-1, vmax=1, center=0)
plt.title("Pearson correlation matrix")
plt.tight_layout()
plt.show()
min_periods sets the minimum number of paired observations needed to compute a coefficient. When you examine many pairs, some will look significant by chance; consider multiple-testing corrections and pre-specified research questions.
Things to watch when reading the results
- Non-linear relationships: Pearson can sit near zero while a strong U-shaped structure is present.
- Outliers: a few extreme observations can move the Pearson coefficient significantly. Check the raw data; do not delete points without reason.
- A third variable: common factors such as age, season or region can move both variables together.
- Aggregation: a relationship seen in group averages may not hold at individual level (the ecological fallacy and Simpson's paradox).
- Missing data: dropping observations pairwise changes the composition of the sample; report how many rows were used.
- Repeated time observations: in time series, trend or autocorrelation can affect standard significance tests.
Summary
Pearson measures a linear relationship and Spearman a rank-based monotonic one. The coefficient summarises direction and strength; it proves neither causation nor independence nor predictive performance. In Python, pandas corr() is handy for quick exploration, and SciPy's pearsonr() and spearmanr() give the coefficient with a test result. Look at the plot first, then read the number in context.