|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Download and preprocess the Air Quality UCI dataset for PLS regression. |
| 3 | +
|
| 4 | +Also computes sklearn PLSR reference results for comparison. |
| 5 | +Run with CPython: python3 examples/datasets/airquality/prepare.py |
| 6 | +""" |
| 7 | + |
| 8 | +from pathlib import Path |
| 9 | +import os |
| 10 | +import urllib.request |
| 11 | +import zipfile |
| 12 | + |
| 13 | +import numpy as np |
| 14 | +import pandas as pd |
| 15 | +from sklearn.model_selection import train_test_split |
| 16 | +from sklearn.preprocessing import StandardScaler |
| 17 | +from sklearn.cross_decomposition import PLSRegression |
| 18 | +from sklearn.metrics import r2_score, mean_squared_error |
| 19 | + |
| 20 | + |
| 21 | +def main(): |
| 22 | + |
| 23 | + here = os.path.dirname(__file__) |
| 24 | + OUTPUT_DIR = Path(here) |
| 25 | + OUTPUT_DIR.mkdir(exist_ok=True) |
| 26 | + |
| 27 | + # Download |
| 28 | + url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00360/AirQualityUCI.zip" |
| 29 | + zip_path = OUTPUT_DIR / "AirQualityUCI.zip" |
| 30 | + if not zip_path.exists(): |
| 31 | + print("Downloading Air Quality UCI dataset...") |
| 32 | + urllib.request.urlretrieve(url, zip_path) |
| 33 | + with zipfile.ZipFile(zip_path, 'r') as zf: |
| 34 | + zf.extractall(OUTPUT_DIR) |
| 35 | + |
| 36 | + # Load and preprocess |
| 37 | + csv_file = OUTPUT_DIR / "AirQualityUCI.csv" |
| 38 | + df = pd.read_csv(csv_file, sep=';', decimal=',') |
| 39 | + df = df.iloc[:, :-2] # drop last two empty columns |
| 40 | + df.replace(-200, np.nan, inplace=True) |
| 41 | + df.dropna(inplace=True) |
| 42 | + |
| 43 | + X = df.iloc[:, 2:].values.astype(np.float32) # sensor columns |
| 44 | + y = df["CO(GT)"].values.astype(np.float32) |
| 45 | + |
| 46 | + scaler_X = StandardScaler() |
| 47 | + X = scaler_X.fit_transform(X).astype(np.float32) |
| 48 | + |
| 49 | + X_train, X_test, y_train, y_test = train_test_split( |
| 50 | + X, y, test_size=0.2, random_state=42 |
| 51 | + ) |
| 52 | + |
| 53 | + FILENAMES = { |
| 54 | + 'X_train': OUTPUT_DIR / 'X_train.npy', |
| 55 | + 'X_test': OUTPUT_DIR / 'X_test.npy', |
| 56 | + 'y_train': OUTPUT_DIR / 'y_train.npy', |
| 57 | + 'y_test': OUTPUT_DIR / 'y_test.npy', |
| 58 | + } |
| 59 | + |
| 60 | + np.save(FILENAMES['X_train'], X_train) |
| 61 | + np.save(FILENAMES['X_test'], X_test) |
| 62 | + np.save(FILENAMES['y_train'], y_train) |
| 63 | + np.save(FILENAMES['y_test'], y_test) |
| 64 | + |
| 65 | + print('Saved datasets:') |
| 66 | + print(f" X_train: {X_train.shape} -> {FILENAMES['X_train']}") |
| 67 | + print(f" X_test : {X_test.shape} -> {FILENAMES['X_test']}") |
| 68 | + print(f" y_train: {y_train.shape} -> {FILENAMES['y_train']}") |
| 69 | + print(f" y_test : {y_test.shape} -> {FILENAMES['y_test']}") |
| 70 | + |
| 71 | + # Sklearn PLSR reference results |
| 72 | + print('\nSklearn PLSR reference:') |
| 73 | + for nc in [3, 5]: |
| 74 | + pls = PLSRegression(n_components=nc) |
| 75 | + pls.fit(X_train, y_train) |
| 76 | + y_pred = pls.predict(X_test).ravel() |
| 77 | + mse = mean_squared_error(y_test, y_pred) |
| 78 | + r2 = r2_score(y_test, y_pred) |
| 79 | + print(f" n_components={nc}: MSE={mse:.5f}, R^2={r2:.5f}") |
| 80 | + |
| 81 | + |
| 82 | +if __name__ == '__main__': |
| 83 | + main() |
0 commit comments