Ki-Kare Testi Nedir?
Kategorik değişkenler arasında ilişki olup olmadığını çapraz tablo üzerinden inceleyin. Ki-kare bağımsızlık testinin mantığını, beklenen frekansları ve p-değerini öğrenin; Python ile testi uygulayıp sonuçları doğru yorumlayın.
- İstatistik

Ki-kare bağımsızlık testi neyi sorar?
Ki-kare bağımsızlık testi, iki kategorik değişkenin birbiriyle bağımsız olup olmadığına ilişkin kanıtı değerlendirir. Örneğin kampanya mesajını gören ve görmeyen müşterilerin satın alma oranlarının farklı olup olmadığını; cihaz türü ile üyelik tercihi arasında ilişki bulunup bulunmadığını inceleyebilir.
Veri, satırlarında bir değişkenin kategorileri; sütunlarında diğer değişkenin kategorileri bulunan bir çapraz tablo ile özetlenir. Hücrelerde gözlenen kişi/kayıt sayıları yer alır. Bu test ortalama karşılaştırmaz; kategorilerin frekans dağılımını karşılaştırır.
Hipotezler ve p-değerinin yorumu
- H₀ (sıfır hipotezi): İki kategorik değişken bağımsızdır; çapraz tablodaki dağılım farkları örnekleme değişkenliğiyle açıklanabilir.
- H₁ (alternatif hipotez): Değişkenler arasında ilişki vardır; dağılım bağımsızlık varsayımından farklıdır.
Test, gözlenen hücre sayılarını bağımsızlık varsayımı altında beklenen sayılarla karşılaştırır. p-değeri; H₀ ve test varsayımları geçerliyken gözlenen kadar veya daha uç bir ki-kare istatistiğinin ne kadar uyumlu olduğunu ölçer. p-değeri önceden belirlenen anlamlılık düzeyinden küçükse H₀ reddedilir.
Ki-kare istatistiğinin mantığı
Her hücre için gözlenen frekans O ve bağımsızlık varsayımı altındaki beklenen frekans E karşılaştırılır. Farkların karesi beklenen frekansa bölünür ve hücreler üzerinden toplanır:
Bağımsızlık altında beklenen hücre sayısı: E = (satır toplamı × sütun toplamı) / genel toplam
χ² büyüdükçe gözlenen tablo ile bağımsızlık varsayımından beklenen tablo arasındaki toplam sapma artar. Serbestlik derecesi iki yönlü bir çapraz tabloda (satır sayısı − 1) × (sütun sayısı − 1) formülüyle hesaplanır; p-değeri bu derece ve χ² üzerinden bulunur.
Python ile çapraz tablo ve test
Örnek veri: 400 müşterinin kampanya grubuna ve satın alma sonucuna göre sayıları. Her satır bir kişiyi temsil etsin; aynı kişi tabloda birden çok kez sayılmasın.
import pandas as pd
from scipy.stats import chi2_contingency
from scipy.stats.contingency import association
data = pd.DataFrame({
"kampanya": ["Gordu"] * 200 + ["Gormedi"] * 200,
"sonuc": (["Aldi"] * 70 + ["Almadi"] * 130
+ ["Aldi"] * 45 + ["Almadi"] * 155)
})
table = pd.crosstab(data["kampanya"], data["sonuc"])
print(table)
chi2, p, dof, expected = chi2_contingency(table, correction=True)
print(f"Ki-kare = {chi2:.3f}; sd = {dof}; p = {p:.4f}")
print("Beklenen frekanslar:")
print(pd.DataFrame(expected, index=table.index, columns=table.columns))
pd.crosstab kategorik değişkenlerin çapraz frekans tablosunu çıkarır. chi2_contingency test istatistiği, p-değeri, serbestlik derecesi ve beklenen frekans matrisini döndürür. 2×2 tabloda varsayılan correction=True, Yates süreklilik düzeltmesini uygular; seçeneği ve gerekçeyi raporda belirtin.
Beklenen frekanslar ve test koşulları
Ki-kare yaklaşımının geçerliliği için beklenen hücre sayıları yeterince büyük olmalıdır. SciPy belgeleri sık kullanılan bir kılavuz olarak tüm gözlenen ve beklenen frekansların en az 5 olması gerektiğini aktarır; bu katı, evrensel bir yasa değildir. Seyrek hücreler ve küçük örneklemde asimptotik p-değeri yanıltıcı olabilir.
expected_df = pd.DataFrame(expected, index=table.index, columns=table.columns)
print("En küçük beklenen frekans:", expected_df.to_numpy().min())
print("5'in altındaki hücre sayısı:", (expected_df < 5).to_numpy().sum())
Beklenen frekanslar düşükse kategori birleştirmek yalnızca alan açısından anlamlıysa düşünülebilir; sonuçları görmek için kategorileri keyfî biçimde birleştirmeyin. 2×2 tabloda Fisher kesin testi; bazı sürümlerde ve uygun tablolarda permütasyon/Monte Carlo yöntemleri değerlendirilebilir. Gözlemlerin bağımsızlığı da önemlidir: tekrarlı ölçümler veya eşleştirilmiş tasarımlar için başka yöntemler gerekebilir.
İlişkinin büyüklüğü: Cramér’s V
Test anlamlı olsa bile ilişkinin pratik gücü küçük olabilir. Cramér’s V, çapraz tablo değişkenleri arasındaki ilişkinin büyüklüğünü 0 ile 1 arasında özetleyen bir ölçüdür. 0 ilişkisizliğe, 1 ise tam ilişkiye karşılık gelir; orta değerleri yorumlarken tablo boyutu ve alan bağlamını dikkate alın.
v = association(table.to_numpy(), method="cramer", correction=False)
print(f"Cramér's V = {v:.3f}")
# Grup içi satın alma oranlarını da incele
row_pct = table.div(table.sum(axis=1), axis=0) * 100
print(row_pct.round(1))
Oran tablosu ilişkinin hangi yönde/pratik düzeyde göründüğünü açıklar; örneğin kampanya görenlerde satın alma oranı ne kadar yüksek? Ki-kare testinin kendisi yön ve nedensellik göstermez. Kampanyanın satın almaya neden olduğu iddiası için deney tasarımı ve olası karıştırıcılar ayrıca ele alınmalıdır.
Sonucu nasıl raporlayabilirsiniz?
Örnek bir raporlama kalıbı:
Şablondaki sayıları kendi çıktınızla doldurun; burada sonuç değerleri verilmemiştir. İstatistik, serbestlik derecesi, örneklem sayısı, p-değeri, etki ölçüsü ve grup oranlarını birlikte raporlamak okuyucunun sonucu anlamasına yardımcı olur.
Sık yapılan hatalar
- Yüzde değerleriyle test: Ki-kare bağımsızlık testi hücrelerdeki gözlem sayılarını bekler; yuvarlanmış yüzdeleri doğrudan frekans gibi kullanmayın.
- Bağımlı gözlemler: Aynı kişi birden çok hücreye katkı veriyorsa standart bağımsızlık testi uygun olmayabilir.
- p-değerini abartmak: “İlişki vardır” sonucu ilişkinin güçlü, önemli veya nedensel olduğunu göstermez.
- Beklenen sayıları atlamak: Seyrek hücreleri kontrol etmeden yaklaşık p-değerine güvenmeyin.
- Çoklu testleri hesaba katmamak: Çok sayıda değişken çifti test ediyorsanız yanlış pozitif olasılığını ve düzeltmeleri değerlendirin.
- Kategorileri sonuca göre birleştirmek: Birleştirme kararını test çıktısına göre değil, analitik anlamına göre önceden verin.
Özet
Ki-kare bağımsızlık testi, kategorik değişkenler için gözlenen çapraz tablo ile bağımsızlık altında beklenen tabloyu karşılaştırır. p-değeri istatistiksel kanıtı değerlendirir; ilişki gücünü Cramér’s V ve grup oranlarıyla ayrıca inceleyin. Beklenen frekansları, gözlem bağımsızlığını ve tasarım yapısını kontrol ederek sonucu bağlam içinde yorumlayın.
Kaynaklar
What does the chi-square test of independence ask?
The chi-square test of independence weighs the evidence on whether two categorical variables are independent of each other. You might examine whether purchase rates differ between customers who saw a campaign message and those who did not, or whether device type relates to membership preference.
The data is summarised in a contingency table, with the categories of one variable down the rows and the categories of the other across the columns. The cells hold observed counts of people or records. The test compares no means; it compares the frequency distribution across categories.
Hypotheses and reading the p-value
- H₀ (null hypothesis): the two categorical variables are independent; the differences in the contingency table can be explained by sampling variability.
- H₁ (alternative hypothesis): there is a relationship between the variables; the distribution departs from the independence assumption.
The test compares the observed cell counts with the counts expected under independence. The p-value measures how compatible a chi-square statistic this extreme or more is with H₀ and the test's assumptions. If the p-value falls below your chosen significance level, H₀ is rejected.
The logic of the chi-square statistic
For each cell, the observed frequency O is compared with the frequency E expected under independence. The squared difference is divided by the expected frequency and summed over the cells:
The expected cell count under independence: E = (row total × column total) / grand total
The larger χ² grows, the greater the total deviation between the observed table and the table expected under independence. In a two-way contingency table the degrees of freedom are (rows − 1) × (columns − 1); the p-value follows from that and χ².
The contingency table and the test in Python
Example data: counts for 400 customers by campaign group and purchase outcome. Let each row represent one person, with nobody counted twice in the table.
import pandas as pd
from scipy.stats import chi2_contingency
from scipy.stats.contingency import association
data = pd.DataFrame({
"campaign": ["Saw"] * 200 + ["Did not see"] * 200,
"outcome": (["Bought"] * 70 + ["Did not buy"] * 130
+ ["Bought"] * 45 + ["Did not buy"] * 155)
})
table = pd.crosstab(data["campaign"], data["outcome"])
print(table)
chi2, p, dof, expected = chi2_contingency(table, correction=True)
print(f"Chi-square = {chi2:.3f}; df = {dof}; p = {p:.4f}")
print("Expected frequencies:")
print(pd.DataFrame(expected, index=table.index, columns=table.columns))
pd.crosstab produces the cross-frequency table for categorical variables. chi2_contingency returns the test statistic, the p-value, the degrees of freedom and the matrix of expected frequencies. On a 2×2 table the default correction=True applies the Yates continuity correction; state your choice and the reason in the report.
Expected frequencies and test conditions
For the chi-square approximation to hold, the expected cell counts have to be large enough. SciPy's documentation cites a common guideline that all observed and expected frequencies should be at least 5; that is not a strict universal law. With sparse cells and small samples the asymptotic p-value can mislead.
expected_df = pd.DataFrame(expected, index=table.index, columns=table.columns)
print("Smallest expected frequency:", expected_df.to_numpy().min())
print("Cells below 5:", (expected_df < 5).to_numpy().sum())
If expected frequencies are low, merging categories is worth considering only where it makes sense in the domain; do not merge categories arbitrarily to see a result. On a 2×2 table, Fisher's exact test is an option, and in some versions and suitable tables permutation or Monte Carlo methods can be used. Independence of observations matters too: repeated measures or matched designs need other methods.
The size of the relationship: Cramér's V
Even a significant test can describe a relationship of little practical strength. Cramér's V summarises the size of the association between contingency table variables on a scale from 0 to 1, where 0 means no association and 1 a perfect one; interpret the middle of that range with the table size and the domain context in mind.
v = association(table.to_numpy(), method="cramer", correction=False)
print(f"Cramér's V = {v:.3f}")
# Also examine the purchase rate inside each group
row_pct = table.div(table.sum(axis=1), axis=0) * 100
print(row_pct.round(1))
The percentage table shows the direction and the practical level of the relationship: how much higher is the purchase rate among those who saw the campaign? The chi-square test itself shows neither direction nor causation. A claim that the campaign caused the purchases needs an experimental design and a separate treatment of possible confounders.
How can you report the result?
A reporting template:
Fill the numbers in from your own output; no result values are given here. Reporting the statistic, the degrees of freedom, the sample size, the p-value, an effect measure and the group rates together helps the reader understand what you found.
Common mistakes
- Testing on percentages: the chi-square test of independence expects observed counts in the cells; do not feed it rounded percentages as if they were frequencies.
- Dependent observations: if one person contributes to several cells, the standard independence test may not apply.
- Overstating the p-value: "there is a relationship" does not show that it is strong, important or causal.
- Skipping the expected counts: do not trust the approximate p-value without checking for sparse cells.
- Ignoring multiple testing: if you test many variable pairs, weigh the false positive risk and the available corrections.
- Merging categories to suit the result: decide on merges by analytical meaning in advance, not from the test output.
Summary
The chi-square test of independence compares an observed contingency table for categorical variables with the table expected under independence. The p-value weighs the statistical evidence; examine the strength of the relationship separately with Cramér's V and the group rates. Check the expected frequencies, the independence of observations and the design structure, and read the result in context.