| 1 | package PDL::Demos::ML_Preprocess; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | sub info { ('ml_preprocess', 'Feature scaling, encoding, and train/test splits for PDL') } | ||
| 7 | |||
| 8 | my @demo = ( | ||
| 9 | [comment => q| | ||
| 10 | Welcome to the PDL::ML::Preprocess demo! | ||
| 11 | |||
| 12 | PDL::ML::Preprocess provides scikit-learn-style feature scaling | ||
| 13 | (StandardScaler, MinMaxScaler), one-hot encoding, and train/test | ||
| 14 | splitting directly on PDL ndarrays. | ||
| 15 | |], | ||
| 16 | |||
| 17 | [act => q| | ||
| 18 | use PDL; | ||
| 19 | use PDL::ML::Preprocess; | ||
| 20 | |||
| 21 | # 6 samples x 2 features (columns = features, rows = samples) | ||
| 22 | my $X = double([ | ||
| 23 | [10, 100], | ||
| 24 | [20, 200], | ||
| 25 | [30, 300], | ||
| 26 | [40, 400], | ||
| 27 | [50, 500], | ||
| 28 | [60, 600], | ||
| 29 | ]); | ||
| 30 | print "Raw features:\n$X\n"; | ||
| 31 | |||
| 32 | my $scaler = PDL::ML::Preprocess::StandardScaler->new; | ||
| 33 | my $X_scaled = $scaler->fit_transform($X); | ||
| 34 | print "StandardScaled (zero mean, unit variance):\n$X_scaled\n"; | ||
| 35 | |], | ||
| 36 | |||
| 37 | [act => q| | ||
| 38 | # MinMaxScaler maps each feature into [0, 1]: | ||
| 39 | my $mm = PDL::ML::Preprocess::MinMaxScaler->new; | ||
| 40 | my $X_mm = $mm->fit_transform($X); | ||
| 41 | print "MinMaxScaled [0, 1]:\n$X_mm\n"; | ||
| 42 | |||
| 43 | # Deterministic train/test split: | ||
| 44 | my $y = double(0, 0, 0, 1, 1, 1); | ||
| 45 | my ($X_tr, $X_te, $y_tr, $y_te) = PDL::ML::Preprocess::train_test_split( | ||
| 46 | $X, $y, test_size => 0.33, seed => 42 | ||
| 47 | ); | ||
| 48 | print "Train shape: [", join(',', $X_tr->dims), "], Test shape: [", join(',', $X_te->dims), "]\n"; | ||
| 49 | |], | ||
| 50 | |||
| 51 | [comment => q| | ||
| 52 | That's PDL::ML::Preprocess! See `perldoc PDL::ML::Preprocess` for | ||
| 53 | OneHotEncoder, Imputer, and Pipeline composition. | ||
| 54 | |], | ||
| 55 | ); | ||
| 56 | |||
| 57 | sub demo { @demo } | ||
| 58 | |||
| 59 | 1; |