|
11 | 11 | from sklearn.model_selection import train_test_split |
12 | 12 | from sklearn.neural_network import MLPClassifier |
13 | 13 | from sklearn.preprocessing import LabelEncoder, StandardScaler |
| 14 | +import torch |
| 15 | +import torch.nn as nn |
| 16 | +from skorch import NeuralNetClassifier |
| 17 | + |
| 18 | +device = "cuda" if torch.cuda.is_available() else "cpu" |
| 19 | +print(f"Using device: {device}") # should print: Using device: cuda |
14 | 20 |
|
15 | 21 | print("Loading dataset...") |
16 | | -data = fetch_diabetes_hospital(as_frame=True) |
| 22 | +# data = fetch_diabetes_hospital(as_frame=True) |
| 23 | +data = fetch_diabetes_hospital(as_frame=True, cache=True) |
17 | 24 | X, y = data.data, data.target |
18 | 25 |
|
19 | 26 | # TODO: Extract the sensitive feature (gender) |
|
38 | 45 | scaler = StandardScaler() |
39 | 46 | X_train = scaler.fit_transform(X_train) |
40 | 47 | X_test = scaler.transform(X_test) |
| 48 | +X_train = X_train.astype(np.float32) |
| 49 | +X_test = X_test.astype(np.float32) |
| 50 | +y_train = y_train.astype(np.int64) |
| 51 | + |
| 52 | +class MLP(nn.Module): |
| 53 | + def __init__(self, input_dim=24, output_dim=2): |
| 54 | + super().__init__() |
| 55 | + self.net = nn.Sequential( |
| 56 | + nn.Linear(input_dim, 64), |
| 57 | + nn.ReLU(), |
| 58 | + nn.Linear(64, 32), |
| 59 | + nn.ReLU(), |
| 60 | + nn.Linear(32, output_dim), |
| 61 | + ) |
| 62 | + def forward(self, x): |
| 63 | + return self.net(x) |
41 | 64 |
|
42 | 65 | print("Training MLP...") |
43 | | -model = MLPClassifier(hidden_layer_sizes=(64, 32), max_iter=100, random_state=42) |
| 66 | +# model = MLPClassifier(hidden_layer_sizes=(64, 32), max_iter=100, random_state=42) |
| 67 | +model = NeuralNetClassifier( |
| 68 | + MLP, |
| 69 | + module__input_dim=X_train.shape[1], |
| 70 | + module__output_dim=len(np.unique(y_train)), |
| 71 | + max_epochs=100, |
| 72 | + lr=0.001, |
| 73 | + batch_size=256, # larger batch = better GPU utilization |
| 74 | + device=device, # ← this line is what actually puts the model on the GPU/CPU |
| 75 | + train_split=None, # mirrors original — no internal val split |
| 76 | + verbose=1, |
| 77 | +) |
44 | 78 | model.fit(X_train, y_train) |
45 | 79 |
|
46 | 80 | joblib.dump({"model": model, "scaler": scaler}, "model.joblib") |
|
0 commit comments