Skip to content
dreamcode
dreamcode
Map
ML with sklearn
Lesson 77 of 77
+15 XP on finish
PYTHON APPLIEDChapter 13 · Python for Data Science

Intro to machine learning with scikit-learn

scikit-learn provides a consistent API for machine learning in Python. The core workflow is: prepare data, split into training and test sets, choose a model, call .fit() to train, and .predict() to classify or regress on new data.

Worked example
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

# Sample dataset: cloud features -> rain prediction
X = [[8000, 10], [2000, 80], [1500, 90], [7000, 15],
     [2500, 75], [9000, 5], [1800, 85], [6000, 20]]
y = [0, 1, 1, 0, 1, 0, 1, 0]  # 0 = no rain, 1 = rain

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42
)

model = DecisionTreeClassifier()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))

How it reads

  • train_test_split divides data into training and evaluation portions
  • model.fit(X_train, y_train) trains the model on labeled examples
  • model.predict(X_test) generates predictions on unseen data
Cloud tip: Always evaluate on a held-out test set, never on training data. Training accuracy can be misleadingly high if the model memorizes rather than generalizes.

Check your understanding

0 / 3

Answer all 3 to complete this lesson and earn 15 XP.

  1. 1. What does model.fit(X, y) do in scikit-learn?
  2. 2. Why should you split data into training and test sets?
  3. 3. What does accuracy_score measure?
Answer every question to unlock the next lesson.