# R ile Makine Öğrenmesi: caret ve tidymodels

> R ile makine öğrenmesi geliştirme rehberi: caret ve tidymodels ile veri hazırlama, model eğitimi, çapraz doğrulama ve performans karşılaştırması.

Kaynak: https://ozgurnurettinozturk.com/r-ile-makine-ogrenmesi-caret-tidymodels | Bu sayfanin HTML surumu ayni adrestedir ve Ingilizce cevirisini de icerir.

---
# R ile Makine Öğrenmesi: caret ve tidymodels

R ile sınıflandırma ve regresyon modelleri kurarken veriyi hazırlamak, doğru doğrulama düzenini seçmek ve performansı yorumlamak gerekir. caret ve tidymodels bu adımlara farklı arayüzler sunar. Bu rehber, ikisini aynı örnek problem üzerinde karşılaştırıp hangi iş akışında nasıl kullanılabileceklerini gösteriyor.

- Makine Öğrenmesi

- Araçlar

## İçindekiler

- [R modelleme iş akışı](#makine)

- [caret ve tidymodels](#paketler)

- [Ortak veri bölümü](#veri)

- [caret ile modelleme](#caret)

- [tidymodels ile modelleme](#tidymodels)

- [Aşamaların karşılaştırması](#karsilastirma)

- [Paket seçimi](#secim)

- [Kontrol listesi](#iyiuygulama)

- [Kaynaklar](#kaynak)

- [Özet](#ozet)

## R ile makine öğrenmesi iş akışı

Bir makine öğrenmesi projesinde önce hedef değişken ve tahmin girdileri belirlenir. Ardından veri eğitim, doğrulama ve test parçalarına ayrılır; eksik değer, ölçek ve kategorik değişken işlemleri yalnızca eğitim verisinden öğrenilir. Model, eğitim verisinde çapraz doğrulama ile karşılaştırılır; seçilen yapı bağımsız test verisinde son kez değerlendirilir.

### Hazırla

Hedefi, özellikleri ve veri kalitesini tanımla.

### Ayır

Eğitim/test sınırını modellemeden önce kur.

### Eğit ve seç

Resampling ile model/parametre seçeneklerini kıyasla.

### Değerlendir

Test kümesinde seçilen modeli ve hata türlerini incele.

caret ve tidymodels bu akışın çoğunu tutarlı biçimde yürütmeye yardımcı olur. İkisi de tek başına doğru problem tanımını, temiz etiketleri veya tarafsız test setini garanti etmez.

## caret ve tidymodels nasıl ayrılır?

**caret** (“Classification And REgression Training”), çok sayıda algoritmayı ortak bir `train()` arayüzünde birleştiren olgun bir pakettir. Model türü `method` ile seçilir; `trainControl()` resampling ve ölçüm ayarlarını, `preProcess` ise bazı temel ön işleme adımlarını yönetir.

**tidymodels** tek bir paket yerine birlikte çalışan, görevi ayrılmış paketlerden oluşan bir ekosistemdir. `recipes` veri hazırlama tarifini, `parsnip` model tanımını/işlem motorunu, `workflows` modeli tarifle birleştirmeyi, `rsample` veri bölme ve resampling’i, `tune` parametre aramasını, `yardstick` ise performans ölçütlerini sağlar. Workflow modeli ve preprocessing adımlarını tek nesnede toplar.

| Başlık | caret | tidymodels |
|---|---|---|
| Temel model arayüzü | `train(method=...)` | `parsnip` model tanımı + engine |
| Ön işleme | `preProcess` veya ayrı R adımları | `recipes` adımları, örn. `step_normalize()` |
| Model + veri hazırlama | Fonksiyon çağrısı ve ayrı nesneler | `workflow()` içinde recipe + model |
| Resampling / tuning | `trainControl()`, `tuneGrid` | `rsample` nesneleri, `tune_grid()` |
| Ölçüm | `train` sonuç özetleri, `confusionMatrix()` | `yardstick` ölçütleri ve metrik setleri |
| Tarz | Birleşik, model merkezli, doğrudan | Modüler, adım adım, tidyverse sözdizimiyle uyumlu |

Her ikisi de çok sayıda modelleme ihtiyacını karşılayabilir. Tercih; mevcut kod tabanı, ekip alışkanlığı, kullanacağınız model motoru, reçete karmaşıklığı ve entegrasyon ihtiyaçlarına göre yapılmalıdır.

## Ortak örnek: iris türünü tahmin etme

Karşılaştırmada R ile gelen `iris` veri setinde çiçeğin ölçülerinden `Species` türünü sınıflandıracağız. Her iki örnekte de k‑NN modeli ve merkezleme/ölçekleme kullanılır. Aynı eğitim/test satırlarını paylaşmaları, son test sonuçlarını daha anlamlı biçimde yan yana değerlendirmeye imkân verir.

*R · her iki paketin kullanacağı ortak bölme*

```r
set.seed(2026)
data(iris)

# caret ile hedef sınıf oranlarını koruyarak satırları seç
train_id <- caret::createDataPartition(
  iris$Species, p = 0.8, list = FALSE
)
train_data <- iris[train_id, ]
test_data  <- iris[-train_id, ]
```

Test kümesini parametre seçmek için tekrar tekrar kullanmayın; yalnızca son değerlendirmede kullanın. Resampling katları iki pakette ayrı üretilirse aynı veri bölümü bile aynı CV katları anlamına gelmez. Tam bir yöntem kıyası için aynı fold indekslerini iki iş akışına da vermek ve aynı metrik/parametre aralığını kullanmak gerekir.

## caret ile hazırlama, eğitim ve CV

caret’te model ailesi `method` ile seçilir; parametre adayları `tuneGrid` içine verilir. Aşağıdaki örnek, merkezleme ve ölçeklemeyi model eğitimiyle birlikte uygular ve 5 katlı çapraz doğrulamayı üç kez tekrarlar.

*R · caret / k‑NN*

```r
library(caret)

cv_control <- trainControl(
  method = "repeatedcv",
  number = 5,
  repeats = 3,
  savePredictions = "final"
)

knn_grid <- expand.grid(k = c(3, 5, 7, 9, 11))

set.seed(2026)
fit_caret <- train(
  Species ~ ., data = train_data,
  method = "knn",
  preProcess = c("center", "scale"),
  trControl = cv_control,
  tuneGrid = knn_grid,
  metric = "Accuracy"
)

fit_caret$bestTune
pred_caret <- predict(fit_caret, newdata = test_data)
confusionMatrix(pred_caret, test_data$Species)
```

`trainControl()` resampling türünü ve kat/repeat sayılarını belirler. `train()` aday `k` değerlerini CV sonuçlarına göre karşılaştırır; `bestTune` en iyi parametreyi gösterir. Son tahminler test kümesinde alınır ve karışıklık matrisi sınıf bazında hataları gösterir.

caret’in `preProcess` ayarları eğitim akışına bağlanabilir. Ön işleme istatistikleri her resampling eğitim parçasından öğrenilmeli, doğrulama parçasına yalnızca uygulanmalıdır; tüm veriyi ölçekleyip sonra CV yapmak bilgi sızıntısı üretir.

## tidymodels ile recipe ve workflow

tidymodels’te önce hazırlama adımları `recipe` ile, model ve motor ise `parsnip` ile tanımlanır. Bunlar `workflow` içinde birleşir; `vfold_cv()` katları üretir ve `tune_grid()` parametreleri resampling üzerinde değerlendirir.

*R · tidymodels / recipe + k‑NN*

```r
library(tidymodels)

set.seed(2026)
folds <- vfold_cv(train_data, v = 5, repeats = 3, strata = Species)

iris_recipe <- recipe(Species ~ ., data = train_data) |>
  step_normalize(all_numeric_predictors())

knn_spec <- nearest_neighbor(neighbors = tune()) |>
  set_engine("kknn") |>
  set_mode("classification")

iris_workflow <- workflow() |>
  add_recipe(iris_recipe) |>
  add_model(knn_spec)

knn_grid <- tibble(neighbors = c(3L, 5L, 7L, 9L, 11L))

set.seed(2026)
tuned <- tune_grid(
  iris_workflow,
  resamples = folds,
  grid = knn_grid,
  metrics = metric_set(accuracy)
)

best <- select_best(tuned, metric = "accuracy")
final_workflow <- finalize_workflow(iris_workflow, best)
fit_tidymodels <- fit(final_workflow, data = train_data)

pred_tidymodels <- predict(fit_tidymodels, new_data = test_data) |>
  bind_cols(test_data |> select(Species))

conf_mat(pred_tidymodels, truth = Species, estimate = .pred_class)
accuracy(pred_tidymodels, truth = Species, estimate = .pred_class)
```

Recipe eğitim verisinde hazırlanır; öğrenilen merkez ve ölçek değerleri doğrulama/test verisine yeniden hesaplanmadan uygulanır. Workflow model ile reçeteyi birlikte taşır. `tune_grid()` CV katlarında her parametre adayını ölçer, `select_best()` seçilen ölçüte göre kazanan ayarı döndürür.

## Veri hazırlama, CV ve ölçümü kıyaslama

| Aşama | caret yaklaşımı | tidymodels yaklaşımı | Ortak dikkat noktası |
|---|---|---|---|
| Eksik değer | `preProcess` içinde desteklenen imputasyon veya önceden hazırlanmış adımlar | Recipe içinde `step_impute_*` adımları | İmputasyon değerini yalnızca eğitim katından öğren. |
| Ölçekleme | `preProcess=c("center","scale")` | `step_normalize()` | Ölçekleme k‑NN/SVM gibi uzaklığa dayalı modeller için önemlidir; ağaçlarda çoğunlukla gerekli değildir. |
| Kategorikler | Formül, kontrast ve modele göre ön işlem | `step_dummy()` gibi açık recipe adımları | Yeni seviyeler ve testte görülen bilinmeyen kategoriler için davranışı tanımla. |
| Çapraz doğrulama | `trainControl(method="repeatedcv",...)` | `vfold_cv()` + `tune_grid()` | Zaman sıralı veride rastgele fold yerine zaman temelli bölme kullan. |
| Sınıflandırma ölçümü | Accuracy/Kappa; sınıf bazlı sonuç için `confusionMatrix()` | `yardstick`: accuracy, sens/spec, roc_auc, f_meas vb. | Sınıf dengesizliğinde accuracy tek başına yeterli değildir. |
| Regresyon ölçümü | RMSE, MAE, R² gibi özetler | yardstick: `rmse()`, `mae()`, `rsq()` | İş maliyetine uygun hata ölçüsünü önceden seç. |

Sınıflandırmada accuracy doğru tahmin oranını verir; precision, recall/sensitivity, specificity ve F1 farklı hata türlerini gösterir. Regresyonda RMSE büyük hataları daha fazla cezalandırır, MAE ise ortalama mutlak sapmayı aynı hedef biriminde yorumlamayı kolaylaştırır. R² varyans açıklamasını özetler ama tek başına iş başarısını kanıtlamaz.

## Hangi durumda hangisini seçmeli?

- **Mevcut caret kodunu sürdürmek:** Ekipte çalışan bir caret iş akışı ve gereken model motorları varsa sırf paket değişimi için geçiş yapmak gerekmez.

- **Yeni, adım adım bir proje kurmak:** Preprocessing, model, tuning ve ölçümü nesneler halinde yönetmek isteniyorsa tidymodels’in modüler yapısı iş akışını görünür kılar.

- **Çok sayıda klasik model seçeneğini ortak arayüzde denemek:** caret’in tanıdık `train()` yaklaşımı hızlı bir karşılaştırma sunar; her modelin bağımlılık/parametre desteğini kontrol edin.

- **Recipe, workflow ve tidyverse ile entegrasyon:** tidymodels bileşenleri veriye hazırlama ve modelleme adımlarını aynı çatı altında tutar.

- **Üretime alma:** Model nesnesi kadar veri sözleşmesi, sürümleme, tahmin izleme ve yeniden eğitim sürecini de tasarlayın; tek başına paket seçimi üretim mimarisi değildir.

## Sağlam bir modelleme için kontrol listesi

- Hedef değişken ve tahmin anında gerçekten erişilebilir özellikler tanımlandı mı?

- Test verisi tuning ve preprocessing hesabının dışında tutuldu mu?

- İmputasyon, ölçekleme ve dummy değişken adımları her CV eğitim katında öğreniliyor mu?

- Eksik değer ve yeni faktör seviyelerinin davranışı belirlendi mi?

- CV stratejisi verinin yapısına uygun mu; kullanıcı/grup veya zaman sızıntısı önlendi mi?

- Parametre seçimi uygun metrikle ve sınıf dengesini gözeterek yapıldı mı?

- Test sonuçlarında sadece tek skor değil, hata türleri ve sınıf bazlı ölçüler de incelendi mi?

- R ve paket sürümleri, rastgele seed’ler ve modelleme adımları kaydedildi mi?

## Kaynaklar

- [caret — Model Training and Tuning](https://topepo.github.io/caret/model-training-and-tuning.html)

- [caret — Pre-Processing](https://topepo.github.io/caret/pre-processing.html)

- [tidymodels — Preprocess your data with recipes](https://www.tidymodels.org/start/recipes/)

- [tune — Model tuning via grid search](https://tune.tidymodels.org/reference/tune_grid.html)

- [workflows — Model preprocessing and fitting bundles](https://workflows.tidymodels.org/)

## Özet

caret, `train()` merkezli ortak bir modelleme arayüzü; tidymodels ise tarif, model tanımı, workflow, resampling, tuning ve metrikleri ayrıştıran modüler bir ekosistem sunar. Her ikisi de veri hazırlama, çapraz doğrulama, parametre seçimi ve performans değerlendirme için kullanılabilir. Adil model kıyası; aynı test verisini, uygun resampling düzenini, aynı ölçütleri ve sızıntısız ön işlemeyi gerektirir.

caret and tidymodels both help you run most of this consistently. Neither on its own guarantees the right problem definition, clean labels or an unbiased test set.

## How do caret and tidymodels differ?

**caret** ("Classification And REgression Training") is a mature package that unifies many algorithms behind a single `train()` interface. The model type is chosen with `method`; `trainControl()` handles resampling and measurement settings, and `preProcess` covers some basic preparation steps.

**tidymodels** is not one package but an ecosystem of task-separated packages that work together. `recipes` holds the data preparation recipe, `parsnip` the model definition and engine, `workflows` the pairing of model and recipe, `rsample` data splitting and resampling, `tune` parameter search, and `yardstick` the performance metrics. A workflow gathers model and preprocessing steps into one object.

| Topic | caret | tidymodels |
|---|---|---|
| Core model interface | `train(method=...)` | `parsnip` model definition + engine |
| Preprocessing | `preProcess` or separate R steps | `recipes` steps such as `step_normalize()` |
| Model + data preparation | Function call and separate objects | recipe + model inside a `workflow()` |
| Resampling / tuning | `trainControl()`, `tuneGrid` | `rsample` objects, `tune_grid()` |
| Measurement | `train` result summaries, `confusionMatrix()` | `yardstick` metrics and metric sets |
| Style | Unified, model-centred, direct | Modular, step by step, tidyverse-friendly syntax |

Both can cover a wide range of modelling needs. The choice should follow your existing code base, team habits, the model engine you need, how complex the recipe is, and your integration requirements.

## A shared example: predicting iris species

For the comparison we will classify `Species` from the flower measurements in R's built-in `iris` data set. Both examples use a k‑NN model with centring and scaling. Because they share the same training and test rows, the final test results can sensibly be read side by side.

*R · the shared split both packages will use*

```r
set.seed(2026)
data(iris)

# pick rows with caret, preserving the target class proportions
train_id <- caret::createDataPartition(
  iris$Species, p = 0.8, list = FALSE
)
train_data <- iris[train_id, ]
test_data  <- iris[-train_id, ]
```

Do not use the test set repeatedly to pick parameters; keep it for the final evaluation. If the two packages generate their resampling folds separately, the same data split still does not mean the same CV folds. A full like-for-like comparison means giving both workflows the same fold indices and using the same metric and parameter range.

## Preparation, training and CV with caret

In caret the model family is chosen with `method` and candidate parameters go into `tuneGrid`. The example below applies centring and scaling together with model training, and repeats 5-fold cross-validation three times.

*R · caret / k‑NN*

```r
library(caret)

cv_control <- trainControl(
  method = "repeatedcv",
  number = 5,
  repeats = 3,
  savePredictions = "final"
)

knn_grid <- expand.grid(k = c(3, 5, 7, 9, 11))

set.seed(2026)
fit_caret <- train(
  Species ~ ., data = train_data,
  method = "knn",
  preProcess = c("center", "scale"),
  trControl = cv_control,
  tuneGrid = knn_grid,
  metric = "Accuracy"
)

fit_caret$bestTune
pred_caret <- predict(fit_caret, newdata = test_data)
confusionMatrix(pred_caret, test_data$Species)
```

`trainControl()` sets the resampling type and the number of folds and repeats. `train()` compares the candidate `k` values on the CV results, and `bestTune` reports the winner. Final predictions come from the test set, and the confusion matrix shows errors class by class.

caret's `preProcess` settings can be bound into the training flow. Preprocessing statistics should be learned from each resampling training part and only applied to the validation part; scaling the whole data set and then running CV leaks information.

## Recipes and workflows with tidymodels

In tidymodels the preparation steps are defined with a `recipe` and the model and engine with `parsnip`. They come together in a `workflow`; `vfold_cv()` generates the folds and `tune_grid()` evaluates parameters across the resamples.

*R · tidymodels / recipe + k‑NN*

```r
library(tidymodels)

set.seed(2026)
folds <- vfold_cv(train_data, v = 5, repeats = 3, strata = Species)

iris_recipe <- recipe(Species ~ ., data = train_data) |>
  step_normalize(all_numeric_predictors())

knn_spec <- nearest_neighbor(neighbors = tune()) |>
  set_engine("kknn") |>
  set_mode("classification")

iris_workflow <- workflow() |>
  add_recipe(iris_recipe) |>
  add_model(knn_spec)

knn_grid <- tibble(neighbors = c(3L, 5L, 7L, 9L, 11L))

set.seed(2026)
tuned <- tune_grid(
  iris_workflow,
  resamples = folds,
  grid = knn_grid,
  metrics = metric_set(accuracy)
)

best <- select_best(tuned, metric = "accuracy")
final_workflow <- finalize_workflow(iris_workflow, best)
fit_tidymodels <- fit(final_workflow, data = train_data)

pred_tidymodels <- predict(fit_tidymodels, new_data = test_data) |>
  bind_cols(test_data |> select(Species))

conf_mat(pred_tidymodels, truth = Species, estimate = .pred_class)
accuracy(pred_tidymodels, truth = Species, estimate = .pred_class)
```

The recipe is prepared on the training data; the centre and scale values it learns are applied to validation and test data without being recomputed. The workflow carries the model and the recipe together. `tune_grid()` measures every candidate parameter across the CV folds, and `select_best()` returns the winning setting for the chosen metric.

## Comparing preparation, CV and measurement

| Stage | The caret approach | The tidymodels approach | What both must watch |
|---|---|---|---|
| Missing values | Imputation supported inside `preProcess`, or steps prepared beforehand | `step_impute_*` steps in the recipe | Learn the imputation value from the training fold only. |
| Scaling | `preProcess=c("center","scale")` | `step_normalize()` | Scaling matters for distance-based models such as k‑NN and SVM; trees mostly do not need it. |
| Categoricals | Formula, contrasts and model-specific preprocessing | Explicit recipe steps such as `step_dummy()` | Define the behaviour for new levels and unseen categories at test time. |
| Cross-validation | `trainControl(method="repeatedcv",...)` | `vfold_cv()` + `tune_grid()` | Use a time-based split rather than random folds on time-ordered data. |
| Classification metrics | Accuracy/Kappa; `confusionMatrix()` for per-class results | `yardstick`: accuracy, sens/spec, roc_auc, f_meas and more | Accuracy alone is not enough under class imbalance. |
| Regression metrics | Summaries such as RMSE, MAE and R² | yardstick: `rmse()`, `mae()`, `rsq()` | Choose the error measure that matches the business cost in advance. |

In classification, accuracy gives the proportion of correct predictions, while precision, recall/sensitivity, specificity and F1 expose different kinds of error. In regression, RMSE punishes large errors more heavily, while MAE makes the average absolute deviation easier to read in the target's own units. R² summarises explained variance but does not on its own prove business value.

## Which one should you choose?

- **Keeping existing caret code going:** if the team has a working caret workflow and the model engines it needs, there is no reason to migrate for the sake of changing package.

- **Building a new project step by step:** if you want preprocessing, model, tuning and measurement managed as objects, the modular structure of tidymodels makes the workflow visible.

- **Trying many classic models behind one interface:** caret's familiar `train()` approach gives a quick comparison; check each model's dependency and parameter support.

- **Integrating with recipes, workflows and the tidyverse:** tidymodels components keep data preparation and modelling steps under one roof.

- **Going to production:** design the data contract, versioning, prediction monitoring and retraining process alongside the model object; a package choice is not a production architecture.

## A checklist for solid modelling

- Are the target variable and the features genuinely available at prediction time defined?

- Has the test data been kept out of tuning and preprocessing calculations?

- Are imputation, scaling and dummy variable steps learned within each CV training fold?

- Is the behaviour for missing values and new factor levels settled?

- Does the CV strategy suit the structure of the data, and is user/group or time leakage prevented?

- Was the parameter choice made with a suitable metric and with class balance in mind?

- Do the test results cover error types and per-class measures, not just one headline score?

- Are the R and package versions, random seeds and modelling steps recorded?

## Resources

- [caret — Model Training and Tuning](https://topepo.github.io/caret/model-training-and-tuning.html)

- [caret — Pre-Processing](https://topepo.github.io/caret/pre-processing.html)

- [tidymodels — Preprocess your data with recipes](https://www.tidymodels.org/start/recipes/)

- [tune — Model tuning via grid search](https://tune.tidymodels.org/reference/tune_grid.html)

- [workflows — Model preprocessing and fitting bundles](https://workflows.tidymodels.org/)

## Summary

caret offers a unified, `train()`-centred modelling interface; tidymodels offers a modular ecosystem that separates recipe, model definition, workflow, resampling, tuning and metrics. Either can handle data preparation, cross-validation, parameter selection and performance evaluation. A fair model comparison needs the same test data, a suitable resampling scheme, the same metrics and leak-free preprocessing.

## Diğer Yazılar

### R ile Makine Öğrenmesi: Veri Hazırlığı ve Keşif

### R ile Sınıflandırma: Lojistik Regresyon, SVM, CART ve Rastgele Orman

### Python ve R Karşılaştırması: Veri Analizi İçin Hangisi Daha İyi?
