[Python] How do I use my trained AI model to make predictions?

Discussão em 'Python' iniciado por Stack, Março 9, 2025.

  1. Stack

    Stack Membro Participativo

    I made an AI model for multiclass classification, it ran good and all, but I don't know how to use the trained model to make a single prediction or maybe many more.

    I know that it may be in the piece of code below, but I can't figure it out.

    n_epochs = 200
    batch_size = 5
    batches_per_epoch = len(X_train) // batch_size

    best_acc = 0
    best_weights = None
    train_loss_hist = []
    train_acc_hist = []
    test_loss_hist = []
    test_acc_hist = []

    # training loop
    for epoch in range(n_epochs):

    epoch_loss = []
    epoch_acc = []
    model.train()
    with tqdm.trange(batches_per_epoch, unit="batch", mininterval=0) as bar:
    bar.set_description(f"Epoch {epoch}")
    for i in bar:
    #take a batch
    start = i * batch_size
    X_batch = X_train[start:start+batch_size]
    y_batch = y_train[start:start+batch_size]
    # forward pass
    y_pred = model(X_batch)
    loss = loss_fn(y_pred, y_batch)
    # backward pass
    optimizer.zero_grad()
    loss.backward()
    # Update weights
    optimizer.step()
    # compute and store metrics
    acc = (torch.argmax(y_pred, 1) == torch.argmax(y_batch, 1)).float().mean()
    epoch_loss.append(float(loss))
    epoch_acc.append(float(acc))
    bar.set_postfix(
    loss=float(loss),
    acc=float(acc)
    )
    # set model in evaluation mode and run throught the test set
    model.eval()
    y_pred = model(X_test)
    ce = loss_fn(y_pred, y_test)
    acc = (torch.argmax(y_pred, 1) == torch.argmax(y_test, 1)).float().mean()
    ce = float(ce)
    acc = float(acc)
    # save best model
    train_loss_hist.append(np.mean(epoch_loss))
    train_acc_hist.append(np.mean(epoch_acc))
    test_loss_hist.append(ce)
    test_acc_hist.append(acc)
    if acc > best_acc:
    best_acc = acc
    best_weights = copy.deepcopy(model.state_dict())
    print(f"Epoch {epoch} validation: Cross-entropy={ce:.2f}, Accuracy={acc*100:.1f}%")


    I used pytorch to build the model. This is my model:

    class Multiclass(nn.Module):
    def __init__(self):
    super().__init__()
    self.hidden = nn.Linear(4, 8)
    self.act = nn.ReLU()
    self.output = nn.Linear(8, 3)

    def forward(self, x):
    x = self.act(self.hidden(x))
    x = self.output(x)
    return x

    Continue reading...

Compartilhe esta Página