Ravindra BagaleCourses & study guides English Track your progress

31. Machine Learning मध्ये Train Test Split

Data Science

31.3 Stratify आणि random_state सोप्या भाषेत

का. दोन छोटे arguments silent bias पासून वाचवतात: stratify आणि random_state.

काय.

  • random_state — shuffle पक्के करते म्हणजे तोच split पुन्हा मिळतो. Teaching आणि debugging साठी चांगले.
  • stratify=y — train आणि test मध्ये तोच yes/no ratio ठेवते. Late orders दुर्मिळ असताना उपयुक्त (उदा. फक्त 10% late).

कसे.

import pandas as pd
from sklearn.model_selection import train_test_split

df = pd.DataFrame({
 "x": range(20),
 "was_late": [0]*18 + [1, 1], # rare late cases (fictional)
})
X = df[["x"]]
y = df["was_late"]

X_tr, X_te, y_tr, y_te = train_test_split(
 X, y, test_size=0.25, random_state=42, stratify=y
)
print("train late rate", y_tr.mean())
print("test late rate", y_te.mean())

तुम्हाला काय दिसायला हवे. Train आणि test मधील late rates जवळ राहतात. stratify नसेल तर छोट्या dataset मध्ये दोन्ही late rows फक्त train मध्ये जाऊ शकतात — मग test ला late case दिसतच नाही.

Ravindra Bagale's Tip

If you are doing classification and one class is rare, you should almost always use stratify. For regression, where you predict a number, you usually do not need stratify. Keep this difference in mind when you split your data.