ANOVA (Varyans Analizi) Nedir?

Üç veya daha fazla grubun ortalamaları arasında istatistiksel olarak anlamlı fark olup olmadığını test edin. Tek yönlü ve iki yönlü ANOVA’nın farkını, F istatistiğinin mantığını, varsayımları ve Python uygulamalarını öğrenin.

  • İstatistik

ANOVA ne zaman kullanılır?

ANOVA (Analysis of Variance / Varyans Analizi), kategorik bir veya daha fazla faktörün sürekli bir sonuç değişkeninin ortalamasıyla ilişkisini inceleyen istatistiksel testler ailesidir. Örneğin üç farklı eğitim programının sınav puanları, dört reklam tasarımının dönüşüm başına harcaması veya iki faktörün (eğitim yöntemi ve sınıf türü) performans puanına etkisi karşılaştırılabilir.

İki bağımsız grubun ortalamasını karşılaştırmak için t-testi sık kullanılan seçenektir. Üç veya daha fazla grubun ortalamasını karşılaştırmada her ikili çift için ayrı t-testleri yapmak, yanlış pozitif olasılığını artırır. ANOVA önce genel bir fark olup olmadığını tek bir omnibus testle değerlendirir.

ANOVA’nın temel sorusu: Gözlenen grup ortalamaları arasındaki değişkenlik, grupların kendi içindeki değişkenliğe kıyasla ne kadar büyüktür?

F istatistiği nasıl çalışır?

ANOVA, toplam değişkenliği iki parçaya ayırır: grup ortalamalarının genel ortalamadan uzaklığı (gruplar arası değişkenlik) ve her grubun kendi içindeki dağılım (grup içi değişkenlik). F istatistiği, bu iki değişkenlik ölçüsünün serbestlik derecelerine göre hesaplanan ortalama karelerinin oranıdır.

F = Gruplar arası ortalama kare / Grup içi ortalama kare
Gruplar arası fark, grup içi saçılmaya göre büyüdükçe F değeri yükselir. F dağılımı altında p-değeri hesaplanarak, tüm grup ortalamalarının eşit olduğu sıfır hipotezi değerlendirilir.

F değeri tek başına “hangi gruplar farklı?” sorusunu yanıtlamaz. Anlamlı bir omnibus sonuç, en az bir grup ortalamasının farklı olduğuna dair kanıt sunar; hangi çiftlerin farklı olduğunu bulmak için uygun post-hoc karşılaştırmalar gerekir.

p-değeri, sıfır hipotezi ve test varsayımları altında gözlenen kadar uç bir F değerinin ne kadar uyumlu olduğunu ölçer. Etki büyüklüğünü veya farkın pratik önemini tek başına göstermez; ortalamaları, güven aralıklarını ve etki büyüklüğünü de raporlayın.

Tek yönlü ANOVA

Tek yönlü ANOVA’da bir kategorik bağımsız değişken (faktör) ve bir sürekli sonuç değişkeni vardır. Örneğin bir çevrimiçi mağaza, üç farklı ürün sayfası tasarımının ortalama sipariş değerini değiştirip değiştirmediğini inceler.

  • Faktör: sayfa tasarımı (A, B, C)
  • Sonuç: sipariş tutarı
  • H₀: üç tasarımın popülasyon ortalamaları eşittir.
  • H₁: en az bir tasarımın ortalaması farklıdır.
from scipy import stats

tasarim_a = [42, 45, 39, 51, 47, 44]
tasarim_b = [49, 53, 46, 55, 52, 50]
tasarim_c = [43, 41, 48, 46, 44, 42]

result = stats.f_oneway(tasarim_a, tasarim_b, tasarim_c)
print(f"F = {result.statistic:.3f}, p = {result.pvalue:.4f}")

Bu örnek, klasik tek yönlü ANOVA’yı çalıştırır ve eşit grup varyansları varsayımına dayanır. p-değeri seçtiğiniz anlamlılık düzeyinden küçükse H₀ reddedilir; ardından Tukey HSD gibi çoklu karşılaştırma yöntemleriyle hangi tasarım çiftlerinin farklı olduğu incelenebilir.

import pandas as pd
from statsmodels.stats.multicomp import pairwise_tukeyhsd

scores = [*tasarim_a, *tasarim_b, *tasarim_c]
groups = (["A"] * len(tasarim_a) + ["B"] * len(tasarim_b)
          + ["C"] * len(tasarim_c))
tukey = pairwise_tukeyhsd(endog=scores, groups=groups, alpha=0.05)
print(tukey)

Çoklu karşılaştırma testleri, ikili testler arasındaki ailewise hata oranını kontrol etmeye yardımcı olur. Önceden planlanmış karşılaştırmalar ve keşif amaçlı tüm çiftleri karşılaştırma aynı şey değildir; test seçimini araştırma sorusuna göre belirleyin.

İki yönlü ANOVA

İki yönlü ANOVA, sürekli bir sonuç üzerinde iki kategorik faktörün ana etkilerini ve aralarındaki etkileşimi inceler. Örneğin ürün sayfası tasarımı (A/B/C) ve cihaz türü (mobil/masaüstü), ortalama sipariş tutarıyla ilişkili olabilir.

EtkiSoruÖrnek yorum
Tasarım ana etkisiCihaz türleri üzerinden ortalama alındığında tasarımlar farklı mı?Tasarım B genel olarak daha yüksek ortalama üretiyor mu?
Cihaz ana etkisiTasarım türleri üzerinden ortalama alındığında cihaz türleri farklı mı?Masaüstü ve mobil ortalamaları farklı mı?
EtkileşimBir faktörün etkisi diğer faktör seviyesine göre değişiyor mu?B tasarımı masaüstünde iyi, mobilde etkisiz mi?

Etkileşim anlamlıysa, tek başına ana etkileri yorumlamak yanıltıcı olabilir. Faktörlerden birinin etkisi diğer faktörün seviyesine bağlı demektir; grafikle ve uygun basit etkiler/karşılaştırmalarla açımlanmalıdır.

import pandas as pd
import statsmodels.api as sm
from statsmodels.formula.api import ols

df = pd.DataFrame({
    "siparis_tutari": [42,45,47,51,46,50,
                      49,53,55,48,52,56,
                      43,41,46,44,48,45],
    "tasarim": ["A"]*6 + ["B"]*6 + ["C"]*6,
    "cihaz": ["mobil","mobil","mobil","masaustu","masaustu","masaustu"]*3
})

model = ols("siparis_tutari ~ C(tasarim) * C(cihaz)", data=df).fit()
table = sm.stats.anova_lm(model, typ=2)
print(table)

C(tasarim) * C(cihaz) iki ana etkiyi ve etkileşim terimini içerir. typ=2 dengeli olmayan tasarımlarda her faktörün diğer terimler kontrolündeki etkisini Type II toplam kareler yaklaşımıyla test eder. Dengeli/ dengesiz tasarım ve hipotez türüne göre Type II/III seçimi uzmanlık gerektirebilir; raporda kullanılan tipi belirtin.

Tek yönlü ve iki yönlü ANOVA karşılaştırması

ÖzellikTek yönlüİki yönlü
Faktör sayısıBir kategorik faktörİki kategorik faktör
Test edilenlerFaktörün grup ortalamalarıyla ilişkisiİki ana etki ve etkileşim
Gerçek hayat örneğiÜç eğitim biçiminin sınav puanlarıEğitim biçimi ve sınıf seviyesinin puana etkisi
EtkileşimModelde faktörler arası etkileşim yokFaktörlerden birinin etkisi diğer faktör düzeyine bağlı olabilir

İki yönlü ANOVA ikinci bir faktörü ve etkileşimi hesaba kattığı için daha zengin bir tasarım sunar; fakat yeterli örneklem ve her faktör kombinasyonunda gözlem gerektirir. Yalnızca faktör sayısı arttı diye iki yönlü model kurmayın; araştırma sorusu ve veri tasarımı desteklemelidir.

Temel varsayımlar ve alternatifler

  • Bağımsızlık: Gözlemler birbirinden bağımsız olmalı. Aynı kişinin tekrarlı ölçümleri standart bağımsız ANOVA’ya doğrudan uymaz; tekrarlı ölçümler ANOVA’sı veya karma etkili modeller gerekebilir.
  • Artıkların yaklaşık normalliği: Model artıklarının dağılımı grup içlerinde makul olmalı. Özellikle küçük örneklemlerde aşırı sapmalar önemlidir.
  • Varyans homojenliği: Grupların varyansları benzer olmalı. Grup büyüklükleri çok farklı ve varyanslar eşit değilse klasik F testi sorunlu olabilir.
  • Aykırı değerler: Uç gözlemler ortalamaları ve varyansları etkileyebilir; veri hatası olup olmadığını inceleyin, gerekçesiz silmeyin.
  • Ölçüm düzeyi ve tasarım: Sonuç sürekli olmalı; gruplama/faktör yapısı çalışma tasarımına uygun kurulmalı.

Varyanslar belirgin eşit değilse tek yönlü karşılaştırmada Welch ANOVA düşünülebilir. SciPy’nin güncel f_oneway arayüzünde equal_var=False Welch sürümünü seçer (SciPy 1.16+). Dağılım ve tasarıma göre Kruskal–Wallis gibi parametrik olmayan seçenekler de değerlendirilebilir; bunlar her koşulda ANOVA’nın birebir ikamesi değildir.

# SciPy 1.16 ve üzeri: Welch tek yönlü ANOVA
welch = stats.f_oneway(tasarim_a, tasarim_b, tasarim_c, equal_var=False)
print(f"Welch F = {welch.statistic:.3f}, p = {welch.pvalue:.4f}")

Sonuç nasıl raporlanır?

  1. Hangi ANOVA türünü ve faktörleri kullandığınızı belirtin.
  2. F istatistiğini serbestlik dereceleri ve p-değeriyle raporlayın: ör. F(df1, df2) = ..., p = ....
  3. Grup ortalamalarını, standart sapmaları ve örneklem sayılarını gösterin.
  4. Omnibus test anlamlıysa uygun post-hoc/planlı karşılaştırmaları ve çoklu test düzeltmesini ekleyin.
  5. Etki büyüklüğü (ör. eta-kare/partial eta-kare) ve güven aralığıyla pratik önemini değerlendirin.
  6. Varsayım kontrollerini, alternatif test kullandıysanız gerekçesini açıklayın.
ANOVA sonucu “tüm gruplar birbirinden farklı” demek değildir. Sadece tüm ortalamaların eşit olduğu varsayımına karşı kanıtın düzeyini test eder; farkın hangi gruplarda olduğunu ek karşılaştırmalarla belirleyin.

Özet

ANOVA, grup içi ve gruplar arası değişkenliği karşılaştırarak ortalamalar hakkında genel bir test yapar. Tek yönlü ANOVA bir faktörü; iki yönlü ANOVA iki faktörün ana etkileriyle birlikte etkileşimini inceler. F istatistiği büyüdükçe gözlenen gruplar arası değişkenlik, grup içi saçılmaya kıyasla artar; p-değeri sıfır hipoteziyle uyumu değerlendirir. Anlamlı sonuç sonrası hangi grupların ayrıştığını ve farkın pratik önemini ayrıca analiz edin.

Kaynaklar

When do you use ANOVA?

ANOVA (Analysis of Variance) is a family of statistical tests that examines how one or more categorical factors relate to the mean of a continuous outcome. You might compare exam scores across three training programmes, cost per conversion across four ad designs, or the effect of two factors (teaching method and class type) on a performance score.

For comparing the means of two independent groups, the t-test is the common choice. For three or more groups, running a separate t-test for every pair raises the chance of a false positive. ANOVA first asks, in a single omnibus test, whether there is any difference at all.

ANOVA's core question: how large is the variability between the observed group means compared with the variability inside the groups?

How does the F statistic work?

ANOVA splits total variability into two parts: how far the group means sit from the overall mean (between-group variability) and the spread inside each group (within-group variability). The F statistic is the ratio of the mean squares of those two, each computed against its degrees of freedom.

F = between-group mean square / within-group mean square
The larger the difference between groups relative to the scatter inside them, the higher F becomes. A p-value is computed under the F distribution to assess the null hypothesis that all group means are equal.

The F value alone does not answer "which groups differ?". A significant omnibus result is evidence that at least one group mean is different; finding out which pairs differ requires suitable post-hoc comparisons.

The p-value measures how compatible an F value this extreme is with the null hypothesis and the test's assumptions. It does not on its own show effect size or practical importance; report the means, confidence intervals and an effect size too.

One-way ANOVA

One-way ANOVA has one categorical independent variable (the factor) and one continuous outcome. An online store, for instance, might look at whether three different product page designs change the average order value.

  • Factor: page design (A, B, C)
  • Outcome: order amount
  • H₀: the population means of the three designs are equal.
  • H₁: at least one design has a different mean.
from scipy import stats

design_a = [42, 45, 39, 51, 47, 44]
design_b = [49, 53, 46, 55, 52, 50]
design_c = [43, 41, 48, 46, 44, 42]

result = stats.f_oneway(design_a, design_b, design_c)
print(f"F = {result.statistic:.3f}, p = {result.pvalue:.4f}")

This runs the classic one-way ANOVA and rests on the assumption of equal group variances. If the p-value falls below your significance level, H₀ is rejected; you can then use multiple comparison methods such as Tukey HSD to see which pairs of designs differ.

import pandas as pd
from statsmodels.stats.multicomp import pairwise_tukeyhsd

scores = [*design_a, *design_b, *design_c]
groups = (["A"] * len(design_a) + ["B"] * len(design_b)
          + ["C"] * len(design_c))
tukey = pairwise_tukeyhsd(endog=scores, groups=groups, alpha=0.05)
print(tukey)

Multiple comparison tests help control the familywise error rate across pairwise tests. Pre-planned comparisons and exploratory all-pairs comparisons are not the same thing; let the research question drive the choice of test.

Two-way ANOVA

Two-way ANOVA examines the main effects of two categorical factors on a continuous outcome, plus the interaction between them. Product page design (A/B/C) and device type (mobile/desktop) may both relate to average order value.

EffectQuestionExample reading
Design main effectAveraged over device types, do the designs differ?Does design B produce a higher mean overall?
Device main effectAveraged over designs, do the device types differ?Do desktop and mobile means differ?
InteractionDoes one factor's effect change with the level of the other?Is design B good on desktop but ineffective on mobile?

If the interaction is significant, reading the main effects on their own can mislead. It means one factor's effect depends on the level of the other, and you need a plot and appropriate simple-effects comparisons to unpack it.

import pandas as pd
import statsmodels.api as sm
from statsmodels.formula.api import ols

df = pd.DataFrame({
    "order_value": [42,45,47,51,46,50,
                    49,53,55,48,52,56,
                    43,41,46,44,48,45],
    "design": ["A"]*6 + ["B"]*6 + ["C"]*6,
    "device": ["mobile","mobile","mobile","desktop","desktop","desktop"]*3
})

model = ols("order_value ~ C(design) * C(device)", data=df).fit()
table = sm.stats.anova_lm(model, typ=2)
print(table)

C(design) * C(device) includes both main effects and the interaction term. typ=2 tests each factor's effect controlling for the other terms with the Type II sum of squares approach, which suits unbalanced designs. Choosing between Type II and Type III depends on balance and the hypothesis you want, and can take expertise; state the type you used in the report.

One-way versus two-way ANOVA

FeatureOne-wayTwo-way
Number of factorsOne categorical factorTwo categorical factors
What is testedThe factor's relationship with group meansTwo main effects plus the interaction
Real-life exampleExam scores across three teaching formatsEffect of teaching format and class level on scores
InteractionNo interaction between factors in the modelOne factor's effect may depend on the other's level

A two-way ANOVA gives a richer design because it accounts for a second factor and the interaction, but it needs enough sample and observations in every factor combination. Do not fit a two-way model just because you have two factors; the research question and the study design have to support it.

Core assumptions and alternatives

  • Independence: observations must be independent of each other. Repeated measurements on the same person do not fit standard independent ANOVA; you may need repeated-measures ANOVA or mixed-effects models.
  • Approximate normality of residuals: the distribution of the model residuals should be reasonable within groups. Extreme deviations matter most in small samples.
  • Homogeneity of variance: group variances should be similar. If group sizes differ a lot and variances are unequal, the classic F test becomes problematic.
  • Outliers: extreme observations can shift means and variances; check whether they are data errors, and do not delete them without reason.
  • Measurement level and design: the outcome must be continuous, and the grouping/factor structure must fit the study design.

If variances are clearly unequal, consider Welch ANOVA for a one-way comparison. In SciPy's current f_oneway interface, equal_var=False selects the Welch version (SciPy 1.16+). Depending on the distribution and design, non-parametric options such as Kruskal–Wallis are also worth considering; they are not a like-for-like replacement for ANOVA in every situation.

# SciPy 1.16 and later: Welch one-way ANOVA
welch = stats.f_oneway(design_a, design_b, design_c, equal_var=False)
print(f"Welch F = {welch.statistic:.3f}, p = {welch.pvalue:.4f}")

How do you report the result?

  1. State which kind of ANOVA and which factors you used.
  2. Report the F statistic with its degrees of freedom and the p-value: F(df1, df2) = ..., p = ....
  3. Show the group means, standard deviations and sample sizes.
  4. If the omnibus test is significant, add the appropriate post-hoc or planned comparisons and the multiple-testing correction.
  5. Assess practical importance with an effect size (eta-squared or partial eta-squared) and a confidence interval.
  6. Describe your assumption checks, and the reason for any alternative test you used.
An ANOVA result does not mean "all groups differ from each other". It tests the strength of evidence against the assumption that all means are equal; use further comparisons to find where the difference lies.

Summary

ANOVA makes a general test about means by comparing within-group and between-group variability. One-way ANOVA examines one factor; two-way ANOVA examines two factors' main effects along with their interaction. A larger F means the observed between-group variability has grown relative to the scatter within groups; the p-value assesses compatibility with the null hypothesis. After a significant result, analyse separately which groups diverge and whether the difference matters in practice.

Resources