File size: 1,932 Bytes
5e4dd9c
 
49e1ec5
5e4dd9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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