my_project.train
Training utilities for the automobile price prediction model.
1"""Training utilities for the automobile price prediction model.""" 2 3from pathlib import Path 4 5import torch 6import torch.nn as nn 7from torch.utils.data import DataLoader 8 9from my_project.dataset import AutomobileDataset 10 11 12def create_model(input_size: int) -> nn.Module: 13 """ 14 Create the neural network used for price prediction. 15 16 Parameters 17 ---------- 18 input_size : int 19 Number of input features 20 21 Returns 22 ------- 23 torch.nn.Module 24 Neural network for predicting automobile selling prices 25 """ 26 27 return nn.Sequential( 28 nn.Linear(input_size, 32), 29 nn.ReLU(), 30 nn.Linear(32, 1) 31 ) 32 33 34def train_model( 35 model: nn.Module, 36 train_loader: DataLoader, 37 epochs: int = 100, 38 learning_rate: float = 0.001 39) -> nn.Module: 40 41 """Train the automobile price prediction model. 42 43 Parameters 44 ---------- 45 model : torch.nn.Module 46 Neural network to train 47 train_loader : torch.utils.data.DataLoader 48 DataLoader containing the training data 49 epochs : int, default=100 50 Number of training epochs 51 learning_rate : float, default=0.001 52 Learning rate used by the Adam optimizer 53 54 Returns 55 ------- 56 torch.nn.Module 57 The trained model 58 """ 59 60 loss_fn = nn.MSELoss() 61 62 optimizer = torch.optim.Adam( 63 model.parameters(), 64 lr=learning_rate 65 ) 66 67 for epoch in range(epochs): 68 69 epoch_loss = 0.0 70 samples = 0 71 72 for X, y in train_loader: 73 74 prediction = model(X).squeeze() 75 76 loss = loss_fn( 77 prediction, 78 y 79 ) 80 81 optimizer.zero_grad() 82 83 loss.backward() 84 85 optimizer.step() 86 87 batch_size = X.size(0) 88 89 epoch_loss += loss.item() * batch_size 90 samples += batch_size 91 92 average_loss = epoch_loss / samples 93 94 print( 95 f"Epoch {epoch + 1}/{epochs} " 96 f"- Loss: {average_loss:.4f}" 97 ) 98 99 return model 100 101def train_model_with_history( 102 model: nn.Module, 103 train_loader: DataLoader, 104 epochs: int = 100, 105 learning_rate: float = 0.001 106) -> tuple[nn.Module, list[float]]: 107 """ 108 Train model and return loss history. 109 110 Parameters 111 ---------- 112 model : torch.nn.Module 113 Neural network to train 114 train_loader : torch.utils.data.DataLoader 115 DataLoader for the training data 116 epochs : int, default=100 117 Amount of epochs to train for 118 learning_rate : float, default=0.001 119 Learning rate of the neural network 120 121 Returns 122 ------- 123 df : pd.DataFrame 124 Dataframe with the preprocessed data 125 history : list[float] 126 List with the history of the loss, of `epochs` lenght 127 """ 128 129 loss_fn = nn.MSELoss() 130 131 optimizer = torch.optim.Adam( 132 model.parameters(), 133 lr=learning_rate 134 ) 135 136 history = [] 137 138 for epoch in range(epochs): 139 140 epoch_loss = 0.0 141 samples = 0 142 143 for X, y in train_loader: 144 145 prediction = model(X).squeeze() 146 147 loss = loss_fn( 148 prediction, 149 y 150 ) 151 152 optimizer.zero_grad() 153 154 loss.backward() 155 156 optimizer.step() 157 158 batch_size = X.size(0) 159 160 epoch_loss += loss.item() * batch_size 161 samples += batch_size 162 163 average_loss = epoch_loss / samples 164 165 history.append(average_loss) 166 167 return model, history 168 169 170def main() -> None: 171 """ 172 Train the automobile price prediction model and save it to disk. 173 """ 174 175 PROCESSED_TRAIN_FILE = "data/processed/automobile_dataset" 176 PROCESSED_TEST_FILE = "data/processed/automobile_test" 177 MODEL_PATH = Path("models/automobile_model.pth") 178 179 MODEL_PATH.parent.mkdir(parents=True, exist_ok=True) 180 181 train_dataset = AutomobileDataset( 182 f"{PROCESSED_TRAIN_FILE}.parquet" 183 ) 184 185 test_dataset = AutomobileDataset( 186 f"{PROCESSED_TEST_FILE}.parquet" 187 ) 188 189 train_loader = DataLoader( 190 train_dataset, 191 batch_size=32, 192 shuffle=True 193 ) 194 195 # The test loader is prepared here for later evaluation. 196 test_loader = DataLoader( 197 test_dataset, 198 batch_size=32, 199 shuffle=False 200 ) 201 202 model = create_model(train_dataset.X.shape[1]) 203 204 model = train_model( 205 model, 206 train_loader 207 ) 208 209 torch.save( 210 model.state_dict(), 211 MODEL_PATH 212 ) 213 214 print(f"Model saved to {MODEL_PATH}") 215 216 217if __name__ == "__main__": 218 main()
def
create_model(input_size: int) -> torch.nn.modules.module.Module:
13def create_model(input_size: int) -> nn.Module: 14 """ 15 Create the neural network used for price prediction. 16 17 Parameters 18 ---------- 19 input_size : int 20 Number of input features 21 22 Returns 23 ------- 24 torch.nn.Module 25 Neural network for predicting automobile selling prices 26 """ 27 28 return nn.Sequential( 29 nn.Linear(input_size, 32), 30 nn.ReLU(), 31 nn.Linear(32, 1) 32 )
Create the neural network used for price prediction.
Parameters
- input_size (int): Number of input features
Returns
- torch.nn.Module: Neural network for predicting automobile selling prices
def
train_model( model: torch.nn.modules.module.Module, train_loader: torch.utils.data.dataloader.DataLoader, epochs: int = 100, learning_rate: float = 0.001) -> torch.nn.modules.module.Module:
35def train_model( 36 model: nn.Module, 37 train_loader: DataLoader, 38 epochs: int = 100, 39 learning_rate: float = 0.001 40) -> nn.Module: 41 42 """Train the automobile price prediction model. 43 44 Parameters 45 ---------- 46 model : torch.nn.Module 47 Neural network to train 48 train_loader : torch.utils.data.DataLoader 49 DataLoader containing the training data 50 epochs : int, default=100 51 Number of training epochs 52 learning_rate : float, default=0.001 53 Learning rate used by the Adam optimizer 54 55 Returns 56 ------- 57 torch.nn.Module 58 The trained model 59 """ 60 61 loss_fn = nn.MSELoss() 62 63 optimizer = torch.optim.Adam( 64 model.parameters(), 65 lr=learning_rate 66 ) 67 68 for epoch in range(epochs): 69 70 epoch_loss = 0.0 71 samples = 0 72 73 for X, y in train_loader: 74 75 prediction = model(X).squeeze() 76 77 loss = loss_fn( 78 prediction, 79 y 80 ) 81 82 optimizer.zero_grad() 83 84 loss.backward() 85 86 optimizer.step() 87 88 batch_size = X.size(0) 89 90 epoch_loss += loss.item() * batch_size 91 samples += batch_size 92 93 average_loss = epoch_loss / samples 94 95 print( 96 f"Epoch {epoch + 1}/{epochs} " 97 f"- Loss: {average_loss:.4f}" 98 ) 99 100 return model
Train the automobile price prediction model.
Parameters
- model (torch.nn.Module): Neural network to train
- train_loader (torch.utils.data.DataLoader): DataLoader containing the training data
- epochs (int, default=100): Number of training epochs
- learning_rate (float, default=0.001): Learning rate used by the Adam optimizer
Returns
- torch.nn.Module: The trained model
def
train_model_with_history( model: torch.nn.modules.module.Module, train_loader: torch.utils.data.dataloader.DataLoader, epochs: int = 100, learning_rate: float = 0.001) -> tuple[torch.nn.modules.module.Module, list[float]]:
102def train_model_with_history( 103 model: nn.Module, 104 train_loader: DataLoader, 105 epochs: int = 100, 106 learning_rate: float = 0.001 107) -> tuple[nn.Module, list[float]]: 108 """ 109 Train model and return loss history. 110 111 Parameters 112 ---------- 113 model : torch.nn.Module 114 Neural network to train 115 train_loader : torch.utils.data.DataLoader 116 DataLoader for the training data 117 epochs : int, default=100 118 Amount of epochs to train for 119 learning_rate : float, default=0.001 120 Learning rate of the neural network 121 122 Returns 123 ------- 124 df : pd.DataFrame 125 Dataframe with the preprocessed data 126 history : list[float] 127 List with the history of the loss, of `epochs` lenght 128 """ 129 130 loss_fn = nn.MSELoss() 131 132 optimizer = torch.optim.Adam( 133 model.parameters(), 134 lr=learning_rate 135 ) 136 137 history = [] 138 139 for epoch in range(epochs): 140 141 epoch_loss = 0.0 142 samples = 0 143 144 for X, y in train_loader: 145 146 prediction = model(X).squeeze() 147 148 loss = loss_fn( 149 prediction, 150 y 151 ) 152 153 optimizer.zero_grad() 154 155 loss.backward() 156 157 optimizer.step() 158 159 batch_size = X.size(0) 160 161 epoch_loss += loss.item() * batch_size 162 samples += batch_size 163 164 average_loss = epoch_loss / samples 165 166 history.append(average_loss) 167 168 return model, history
Train model and return loss history.
Parameters
- model (torch.nn.Module): Neural network to train
- train_loader (torch.utils.data.DataLoader): DataLoader for the training data
- epochs (int, default=100): Amount of epochs to train for
- learning_rate (float, default=0.001): Learning rate of the neural network
Returns
- df (pd.DataFrame): Dataframe with the preprocessed data
- history (list[float]):
List with the history of the loss, of
epochslenght
def
main() -> None:
171def main() -> None: 172 """ 173 Train the automobile price prediction model and save it to disk. 174 """ 175 176 PROCESSED_TRAIN_FILE = "data/processed/automobile_dataset" 177 PROCESSED_TEST_FILE = "data/processed/automobile_test" 178 MODEL_PATH = Path("models/automobile_model.pth") 179 180 MODEL_PATH.parent.mkdir(parents=True, exist_ok=True) 181 182 train_dataset = AutomobileDataset( 183 f"{PROCESSED_TRAIN_FILE}.parquet" 184 ) 185 186 test_dataset = AutomobileDataset( 187 f"{PROCESSED_TEST_FILE}.parquet" 188 ) 189 190 train_loader = DataLoader( 191 train_dataset, 192 batch_size=32, 193 shuffle=True 194 ) 195 196 # The test loader is prepared here for later evaluation. 197 test_loader = DataLoader( 198 test_dataset, 199 batch_size=32, 200 shuffle=False 201 ) 202 203 model = create_model(train_dataset.X.shape[1]) 204 205 model = train_model( 206 model, 207 train_loader 208 ) 209 210 torch.save( 211 model.state_dict(), 212 MODEL_PATH 213 ) 214 215 print(f"Model saved to {MODEL_PATH}")
Train the automobile price prediction model and save it to disk.