Summary - Pipeline
- Machine Learning course
- Intermediate
- Lesson 12/112
- 6 min
In this group you learned the Pipeline structure and advantages.
Summary: pipelines
In this group:
- A pipeline makes preprocessing and the model one estimator; it prevents leakage structurally, especially for steps that look at the target.
- Intermediate steps must be transformers; steps are reached with
pipe["name"],pipe[:-1];"passthrough"turns a step off. fit_transformruns in fit,transformin predict.- With
joblibthe whole chain is saved and moved to production. ColumnTransformerapplies different transformations to different column groups.
Practice End-to-end chain
For the mixed table, build a make_pipeline from a ColumnTransformer (numbers with StandardScaler, city with OneHotEncoder(handle_unknown="ignore")) and LogisticRegression(), and train it with y. Print the prediction for a new row containing the city "Antalya", unseen in training.
Starter code
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
df = pd.DataFrame({
"yas": [25, 32, 47, 51],
"gelir": [3000, 4500, 8000, 6000],
"sehir": ["Ankara", "İzmir", "Ankara", "Bursa"],
})
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
y = np.array([0, 0, 1, 1])
yeni = pd.DataFrame({"yas": [50], "gelir": [7500], "sehir": ["Antalya"]})
# buraya yazSample solution
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
df = pd.DataFrame({
"yas": [25, 32, 47, 51],
"gelir": [3000, 4500, 8000, 6000],
"sehir": ["Ankara", "İzmir", "Ankara", "Bursa"],
})
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
y = np.array([0, 0, 1, 1])
yeni = pd.DataFrame({"yas": [50], "gelir": [7500], "sehir": ["Antalya"]})
ct = ColumnTransformer([("sayi", StandardScaler(), ["yas", "gelir"]), ("kat", OneHotEncoder(handle_unknown="ignore"), ["sehir"])])
model = make_pipeline(ct, LogisticRegression()).fit(df, y)
print(model.predict(yeni))Expected output
[1]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is the <code>gamma</code> parameter of an SVC inside a pipeline written in a grid (step name "svc")?
- "svc_gamma"
- "svc__gamma" Correct answer
- "gamma"
- "svc.gamma"
Explanation: The step name and the parameter name are separated by a double underscore.
2 Combine preprocessing and the model with automatic names.
model = ____(ct, LogisticRegression())
model = make_pipeline(ct, LogisticRegression())
Explanation: With make_pipeline the names become "columntransformer", "logisticregression".
3 Match the tools.
| Term | Meaning |
|---|---|
Pipeline |
Sequential steps |
ColumnTransformer |
Parallel column groups |
joblib |
Saving |
passthrough |
Turning a step off |