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

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.

1

Hazırla

Hedefi, özellikleri ve veri kalitesini tanımla.

2

Ayır

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

3

Eğit ve seç

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

4

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ıkcarettidymodels
Temel model arayüzütrain(method=...)parsnip model tanımı + engine
Ön işlemepreProcess veya ayrı R adımlarırecipes adımları, örn. step_normalize()
Model + veri hazırlamaFonksiyon çağrısı ve ayrı nesnelerworkflow() içinde recipe + model
Resampling / tuningtrainControl(), tuneGridrsample nesneleri, tune_grid()
Ölçümtrain sonuç özetleri, confusionMatrix()yardstick ölçütleri ve metrik setleri
TarzBirleşik, model merkezli, doğrudanModü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
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
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
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.

Engine notu: Örnekte kknn model motoru kullanılıyor. Gerekirse install.packages(c("tidymodels", "kknn", "caret")) ile paketleri kurun. caret’te k‑NN motoru farklı bağımlılıklar kullanabilir; sisteminizde ilgili model paketi kurulu olmalıdır.

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

Aşamacaret yaklaşımıtidymodels yaklaşımıOrtak dikkat noktası
Eksik değerpreProcess içinde desteklenen imputasyon veya önceden hazırlanmış adımlarRecipe içinde step_impute_* adımlarıİmputasyon değerini yalnızca eğitim katından öğren.
ÖlçeklemepreProcess=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.
KategoriklerFormül, kontrast ve modele göre ön işlemstep_dummy() gibi açık recipe adımlarıYeni seviyeler ve testte görülen bilinmeyen kategoriler için davranışı tanımla.
Çapraz doğrulamatrainControl(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 özetleryardstick: 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.
Karar kuralı: Küçük bir pilotta aynı veri bölümü, hedef ölçüt ve makul parametre aralığıyla iki seçeneği de deneyin. Kodun okunabilirliğini, ekip bakımını, model motoru desteğini ve ölçüt sonuçlarını birlikte değerlendirin.

Sağlam bir modelleme için kontrol listesi

  1. Hedef değişken ve tahmin anında gerçekten erişilebilir özellikler tanımlandı mı?
  2. Test verisi tuning ve preprocessing hesabının dışında tutuldu mu?
  3. İmputasyon, ölçekleme ve dummy değişken adımları her CV eğitim katında öğreniliyor mu?
  4. Eksik değer ve yeni faktör seviyelerinin davranışı belirlendi mi?
  5. CV stratejisi verinin yapısına uygun mu; kullanıcı/grup veya zaman sızıntısı önlendi mi?
  6. Parametre seçimi uygun metrikle ve sınıf dengesini gözeterek yapıldı mı?
  7. Test sonuçlarında sadece tek skor değil, hata türleri ve sınıf bazlı ölçüler de incelendi mi?
  8. R ve paket sürümleri, rastgele seed’ler ve modelleme adımları kaydedildi mi?

Kaynaklar

Ö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.

A machine learning workflow in R

A machine learning project starts by settling the target variable and the predictors. The data is then split into training, validation and test parts, and missing values, scaling and categorical handling are learned from the training data only. Models are compared on the training data with cross-validation, and the chosen structure is evaluated once on an independent test set.

1

Prepare

Define the target, the features and the data quality.

2

Split

Draw the train/test boundary before any modelling.

3

Train and choose

Compare model and parameter options with resampling.

4

Evaluate

Examine the chosen model and its error types on the test set.

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.

Topiccarettidymodels
Core model interfacetrain(method=...)parsnip model definition + engine
PreprocessingpreProcess or separate R stepsrecipes steps such as step_normalize()
Model + data preparationFunction call and separate objectsrecipe + model inside a workflow()
Resampling / tuningtrainControl(), tuneGridrsample objects, tune_grid()
Measurementtrain result summaries, confusionMatrix()yardstick metrics and metric sets
StyleUnified, model-centred, directModular, 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
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
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
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.

A note on engines: the example uses the kknn engine. Install the packages if you need them with install.packages(c("tidymodels", "kknn", "caret")). caret's k‑NN engine may use different dependencies; the relevant model package must be installed on your system.

Comparing preparation, CV and measurement

StageThe caret approachThe tidymodels approachWhat both must watch
Missing valuesImputation supported inside preProcess, or steps prepared beforehandstep_impute_* steps in the recipeLearn the imputation value from the training fold only.
ScalingpreProcess=c("center","scale")step_normalize()Scaling matters for distance-based models such as k‑NN and SVM; trees mostly do not need it.
CategoricalsFormula, contrasts and model-specific preprocessingExplicit recipe steps such as step_dummy()Define the behaviour for new levels and unseen categories at test time.
Cross-validationtrainControl(method="repeatedcv",...)vfold_cv() + tune_grid()Use a time-based split rather than random folds on time-ordered data.
Classification metricsAccuracy/Kappa; confusionMatrix() for per-class resultsyardstick: accuracy, sens/spec, roc_auc, f_meas and moreAccuracy alone is not enough under class imbalance.
Regression metricsSummaries 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 decision rule: try both in a small pilot with the same data split, the same target metric and a sensible parameter range. Weigh code readability, team maintenance, engine support and the metric results together.

A checklist for solid modelling

  1. Are the target variable and the features genuinely available at prediction time defined?
  2. Has the test data been kept out of tuning and preprocessing calculations?
  3. Are imputation, scaling and dummy variable steps learned within each CV training fold?
  4. Is the behaviour for missing values and new factor levels settled?
  5. Does the CV strategy suit the structure of the data, and is user/group or time leakage prevented?
  6. Was the parameter choice made with a suitable metric and with class balance in mind?
  7. Do the test results cover error types and per-class measures, not just one headline score?
  8. Are the R and package versions, random seeds and modelling steps recorded?

Resources

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.