Classification model using NN

Hi, I have a network that accepts 30 inputs and outputs 4 outputs.
Each action can receive an integer between 1 and 5 (meaning each action can be an integer between 1 and 5).
Something doesn’t work out for me in what the network puts out. I want to get for each action the probability that the value of the action is 1,2,3,4,5 and from there choose the maximum probability.
How do I update the code to make this happen?
Again, I have 4 actions and each action can be one of the numbers 1-5

this is my code

import torch

import torch.nn as nn

import torch.optim as optim

from torch.utils.data import DataLoader, TensorDataset

import pandas as pd

import numpy as np

from sklearn.model_selection import train_test_split

# Load data from CSV file

file_path = '/content/data.csv'

df = pd.read_csv(file_path)

# Extract features and target outputs

X = df.iloc[:, :-4].values # Assuming the last 4 columns are the target outputs

Y = df.iloc[:, -4:].values # Extracting the last 4 columns as target outputs

# Split the dataset into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=42)

# Convert to PyTorch tensors

X_train_tensor = torch.tensor(X_train, dtype=torch.float32)

y_train_tensor = torch.tensor(y_train, dtype=torch.long)

X_test_tensor = torch.tensor(X_test, dtype=torch.float32)

y_test_tensor = torch.tensor(y_test, dtype=torch.long)

# Create datasets and dataloaders

train_dataset = TensorDataset(X_train_tensor, y_train_tensor)

test_dataset = TensorDataset(X_test_tensor, y_test_tensor)

train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)

test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)

# Define the neural network model

class NeuralNetwork(nn.Module):

def __init__(self, input_size, num_classes):

super(NeuralNetwork, self).__init__()

self.layer1 = nn.Linear(input_size, 64*2)

self.relu = nn.ReLU()

self.layer2 = nn.Linear(64*2, 32*2)

self.output_layer = nn.Linear(32*2, num_classes)

def forward(self, x):

out = self.layer1(x)

out = self.relu(out)

out = self.layer2(out)

out = self.relu(out)

out = self.output_layer(out)

return out

# Initialize the model

input_size = X.shape[1] # Number of input features

num_classes = Y.shape[1] # Number of output classes

model = NeuralNetwork(input_size, num_classes)

# Define the loss function and optimizer

criterion = nn.CrossEntropyLoss()

optimizer = optim.Adam(model.parameters(), lr=0.001)

# Training loop

num_epochs = 30

for epoch in range(num_epochs):

total_loss = 0

for inputs, labels in train_loader:

# Forward pass

outputs = model(inputs)

loss = criterion(outputs, torch.argmax(labels, axis=1)) # Assuming one-hot encoding for labels

# Backward pass and optimization

optimizer.zero_grad()

loss.backward()

optimizer.step()

total_loss += loss.item()

print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {total_loss / len(train_loader):.4f}')

print("Training complete")

tnx!!! :slight_smile:

Two thoughts:

  1. If you’re going to post your code, please use the “preformatted text” tag. This will let your code appear as code, rather than as Markdown. I’ll edit your post on this thread to fix it.

  2. I think this would be better placed in the “AI Projects” category. You can move it there using the “pencil” icon in the thread title.

And a question: What do you mean by “action”? Are you discussing the values of the input features?