Spaces:
Sleeping
Sleeping
Download model/train.py from nutripath/nutripath-ml: direct link, hf CLI and curl.
- Browser
- Download file 1.93 kB
-
https://huggingface.co/spaces/nutripath/nutripath-ml/resolve/main/model/train.py
- Command line
-
hf download hf://spaces/nutripath/nutripath-ml/model/train.py
-
curl -L -o train.py https://huggingface.co/spaces/nutripath/nutripath-ml/resolve/main/model/train.py
1.93 kB
| import torch | |
| import torch.nn as nn | |
| from .model import FoodMLP | |
| from collections import Counter | |
| def train_model(X_train, y_train, X_test, y_test, epochs=100): | |
| input_size = X_train.shape[1] | |
| model = FoodMLP(input_size) | |
| counts = Counter(y_train) | |
| total = len(y_train) | |
| weights = [total / counts[i] for i in range(3)] | |
| class_weights = torch.tensor(weights, dtype=torch.float32) | |
| criterion = nn.CrossEntropyLoss(weight=class_weights) # ← FIX aici | |
| optimizer = torch.optim.Adam(model.parameters(), lr=0.001) | |
| X_train_t = torch.tensor(X_train, dtype=torch.float32) | |
| y_train_t = torch.tensor(y_train, dtype=torch.long) | |
| X_test_t = torch.tensor(X_test, dtype=torch.float32) | |
| y_test_t = torch.tensor(y_test, dtype=torch.long) | |
| train_loss_history = [] | |
| val_loss_history = [] | |
| train_acc_history = [] | |
| val_acc_history = [] | |
| for epoch in range(epochs): | |
| model.train() | |
| optimizer.zero_grad() | |
| outputs = model(X_train_t) | |
| loss = criterion(outputs, y_train_t) | |
| loss.backward() | |
| optimizer.step() | |
| train_loss_history.append(loss.item()) | |
| train_preds = torch.argmax(outputs, dim=1) | |
| train_acc = (train_preds == y_train_t).float().mean().item() | |
| train_acc_history.append(train_acc) | |
| model.eval() | |
| with torch.no_grad(): | |
| val_outputs = model(X_test_t) | |
| val_loss = criterion(val_outputs, y_test_t) | |
| val_loss_history.append(val_loss.item()) | |
| val_preds = torch.argmax(val_outputs, dim=1) | |
| val_acc = (val_preds == y_test_t).float().mean().item() | |
| val_acc_history.append(val_acc) | |
| print(f"Epoch {epoch+1}/{epochs} | Train Loss: {loss.item():.4f} | Val Loss: {val_loss.item():.4f} | Train Acc: {train_acc:.4f} | Val Acc: {val_acc:.4f}") | |
| return model, train_loss_history, val_loss_history, train_acc_history, val_acc_history |