31. Machine Learning मध्ये Train Test Split
31.2 sklearn मध्ये train_test_split कसे काम करते
का. sklearn एक स्पष्ट function देते, म्हणजे हाताने split करताना rows चुकून leak होणार नाहीत.
काय. sklearn.model_selection मधील train_test_split arrays किंवा DataFrames यादृच्छिकपणे train आणि test भागांत विभागते.
कसे.
Jupyter मध्ये copy-run
- sklearn install/import करा (packages Chapter 2 मध्ये सेट केले).
- छोटी काल्पनिक table तयार करा.
test_size=0.2आणिrandom_state=42सहtrain_test_splitबोलावा.- Shapes print करा. Rows overlap होत नाहीत हे तपासा.
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.DataFrame({
"items": [2, 3, 5, 8, 1, 4, 7, 6, 2, 9],
"distance_km": [1.2, 3.0, 4.5, 6.1, 0.8, 2.2, 5.0, 3.3, 1.0, 7.4],
"was_late": [0, 0, 1, 1, 0, 0, 1, 0, 0, 1],
})
X = df[["items", "distance_km"]]
y = df["was_late"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print("train rows", len(X_train), "test rows", len(X_test))
print(X_train.head())
तुम्हाला काय दिसायला हवे. या छोट्या set वर सुमारे 8 train rows आणि 2 test rows. खऱ्या data वर जास्त rows ठेवा; इथे फक्त API शिकायची आहे.
अजून model fit नाही
आपण फक्त split करतो. Fitting Chapter 33 पासून सुरू (linear regression). आधी foundations.
Ravindra Bagale's Tip
Make it a habit to write random_state=42 when you split data. Then your output matches your classmate's output, which makes debugging much easier. Later, in a real project, your team can decide its own policy for random_state.
Ravindra Bagale's Tip – मराठी
Data split करताना random_state=42 लिहायची सवय लावा. त्यामुळे तुमचा output तुमच्या classmate च्या output शी match होतो, आणि debugging खूप सोपं होतं. नंतर खऱ्या project मध्ये random_state साठी कोणती policy वापरायची हे तुमची team ठरवू शकते.
Ravindra Bagale's Tip – हिंदी
Data split करते समय random_state=42 लिखने की आदत डालो. इससे तुम्हारा output तुम्हारे classmate के output से match होता है, और debugging बहुत आसान हो जाती है. बाद में असली project में random_state के लिए कौन सी policy रखनी है, यह तुम्हारी team तय कर सकती है.