
































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

































One case study: predicting the fuel efficiency of cars
The Case Study
Question. Can we predict a carโs fuel efficiency, in miles per gallon (mpg), from its specifications? Data. The mpg dataset in seaborn (a copy of the UCI Auto MPG data): 398 car models from 1970 to 1982, 9 columns.
Plan. Each hour applies one step of the data science life cycle to this same dataset. At the end we have a clean, explored, scaled and split dataset, ready for a model.
Standard Imports
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy import stats
mpg = sns.load_dataset("mpg") # the raw data, 398 x 9
These aliases are the community convention. Outputs were produced with pandas 3. In pandas 2, text columns show the dtype object instead of str; the code runs unchanged.
H1: Creating Arrays
An ndarray holds values of one dtype in a contiguous block of memory. weight = np.array([3504, 3693, 3436, 3433, 3449]) # first 5 cars (lb) print(weight.dtype, weight.shape, weight.ndim) # int64 (5,) 1 print(np.arange(70, 83, 4)) # [70 74 78 82] stop excluded print(np.linspace(0, 1, 5)) # [0. 0.25 0.5 0.75 1.] print(np.zeros((2, 3)).shape) # (2, 3) print(np.array([18, 15.5]).dtype) # float64 int upcast to float
Mixed types are converted to one common type, so check dtype after loading data.
Reshaping, Views and Copies
w = X[:, 0] print(w.shape, w.reshape(-1, 1).shape) # (392,) (392, 1) B = X[:2].copy() f = B.flatten(); f[0] = 0 print(B[0, 0]) # 3504.0 flatten() made a copy r = B.ravel(); r[0] = 0 print(B[0, 0]) # 0.0 ravel() gave a view first = X[0]; first[2] = 99 print(X[0]) # [3504. 130. 99.] slice is a view X[0, 2] = 18.0 # restore
reshape(-1, 1) makes one column, the 2D shape scikit-learn expects. Basic slices share memory. Use .copy() before changing a part you must keep.
Aggregation Along an Axis and Broadcasting
print(X.mean(axis=0).round(2)) # [2977.58 104.47 23.45] print(X.std(axis=0, ddof=1).round(2)) # [849.4 38.49 7.81] print(np.percentile(X[:, 2], [25, 50, 75])) # [17. 22.75 29.]
mu, sd = X.mean(axis=0), X.std(axis=0) Z = (X - mu) / sd # (392, 3) with (3,): broadcast print(Z.mean(axis=0).round(10), Z.std(axis=0)) # [0. 0. 0.] [1. 1. 1.]
axis=0 collapses the rows: one result per column. ddof=1 gives the sample SD. Broadcasting : compare shapes from the right; sizes must be equal or 1. Here (3,) is stretched over all 392 rows, giving z-scores for every column.
Distances Between Cars
After standardisation, each car is a vector of z-scores; similar cars are close togetherse together. a, b = Z[0], Z[1] # chevrolet chevelle, buick skylark print(round(a @ b, 3)) # 2.326 dot product print(round(np.linalg.norm(a - b), 3)) # 1. print(round(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)), 3))
far = Z[np.argmax(X[:, 2])] # mazda glc, the most efficient car print(round(np.linalg.norm(a - far), 3)) # 4.
Euclidean distance on standardised features is the basis of nearest-neighbour methods. Without standardising, weight (in thousands of lb) would dominate.
Reproducible Random Sampling
rng = np.random.default_rng(42) idx = rng.choice(len(X), size=5, replace=False) # 5 random cars print(idx, X[idx, 2])
rng2 = np.random.default_rng(42) print(rng2.choice(len(X), size=5, replace=False)) # same 5 rows
The same seed gives the same sample on every run. Fix a seed for every random step (sampling, splitting, simulation).
Reading Data
mpg = sns.load_dataset("mpg") # seaborn copy raw = pd.read_csv("auto-mpg.csv", na_values="?") # "?" means missing book = pd.read_excel("cars.xlsx", sheet_name="1982") # needs openpyxl
The original UCI file marks missing horsepower with "?". na_values turns such markers into NaN while reading. Other useful options: usecols (load some columns), parse_dates (convert dates).
Counting and Selecting
print(mpg["origin"].value_counts().to_dict())
print(mpg["cylinders"].value_counts().sort_index().to_dict())
mpg.loc[0:2, ["name", "mpg"]] # labels 0, 1 AND 2 mpg.iloc[0:2, 0:3] # positions 0 and 1 only
Filtering Rows and Changing Columns
jp80 = mpg[(mpg["origin"] == "japan") & (mpg["model_year"] >= 80)] print(jp80.shape, jp80["mpg"].mean().round(2)) # (34, 9) 34. print(mpg.query("cylinders == 8 and mpg > 20").shape) # (4, 9)
cars = mpg.copy() cars["year"] = cars["model_year"] + 1900 # new column cars["power_to_weight"] = 1000 * cars["horsepower"] / cars["weight"] cars = cars.rename(columns={"year": "calendar_year"}) cars = cars.drop(columns=["calendar_year"])
Imputing Horsepower by Cylinders
Horsepower depends strongly on engine size, so fill each gap with the median of cars with the same number of cylinders. print(mpg["horsepower"].median()) # 93.5 one global value print(mpg.groupby("cylinders")["horsepower"].median().to_dict())
cars = mpg.copy() cars["hp_missing"] = cars["horsepower"].isna() # keep a record grp = cars.groupby("cylinders")["horsepower"].transform("median") cars["horsepower"] = cars["horsepower"].fillna(grp) print(cars["horsepower"].isna().sum()) # 0
This is fine for exploration. For modelling, imputation is moved inside a pipeline fitted only on the training data g data (H7).
Duplicates and Type Conversion
print(mpg.duplicated().sum()) # 0 print(mpg["name"].duplicated().sum()) # 93 print(mpg.duplicated(subset=["name", "model_year"]).sum()) # 2
hp = pd.to_numeric(pd.Series(["130", "165", "?", " 150 "]).str.strip(), errors="coerce") print(hp.tolist()) # [130.0, 165.0, nan, 150.0] cars["origin"] = cars["origin"].astype("category")
Repeated names are the same model in different years; the 2 name-year repeats are different engines. Nothing is removed. errors="coerce" turns invalid text into NaN. A category column stores a fixed set of labels compactly.