# Split the data into training and testing setsX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
Show the code
# Standardize the featuresscaler = StandardScaler()X_train = scaler.fit_transform(X_train)X_test = scaler.transform(X_test)
Show the code
# Convert the data to PyTorch tensorsX_train = torch.tensor(X_train, dtype=torch.float32)Y_train = torch.tensor(Y_train, dtype=torch.long)X_test = torch.tensor(X_test, dtype=torch.float32)Y_test = torch.tensor(Y_test, dtype=torch.long)
Show the code
# Define the neural network architectureclass Net(nn.Module):def__init__(self):super(Net, self).__init__()self.fc1 = nn.Linear(4, 10)self.fc2 = nn.Linear(10, 10)self.fc3 = nn.Linear(10, 3)def forward(self, x): x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) x =self.fc3(x)return x
Show the code
# Create an instance of the neural networkmodel = Net()
Show the code
# Define the loss function and optimizercriterion = nn.CrossEntropyLoss()optimizer = optim.Adam(model.parameters(), lr=0.001)
Show the code
# Train the modelnum_epochs =100batch_size =16for epoch inrange(num_epochs): running_loss =0.0for i inrange(0, X_train.size(0), batch_size): inputs = X_train[i:i+batch_size] labels = Y_train[i:i+batch_size] optimizer.zero_grad()# Forward pass outputs = model(inputs) loss = criterion(outputs, labels)# Backward pass and optimization loss.backward() optimizer.step() running_loss += loss.item()if (epoch+1) %10==0:print(f"Epoch {epoch+1}: Loss = {running_loss:.4f}")
Epoch 10: Loss = 7.9727
Epoch 20: Loss = 5.2169
Epoch 30: Loss = 3.1653
Epoch 40: Loss = 2.2043
Epoch 50: Loss = 1.5700
Epoch 60: Loss = 1.1596
Epoch 70: Loss = 0.9131
Epoch 80: Loss = 0.7656
Epoch 90: Loss = 0.6722
Epoch 100: Loss = 0.6093
Show the code
# Evaluate the model on the test setmodel.eval()with torch.no_grad(): outputs = model(X_test) _, predicted = torch.max(outputs, 1) accuracy = torch.sum(predicted == Y_test).item() / Y_test.size(0)print(f"Test Accuracy: {accuracy*100:.2f}%")
Test Accuracy: 100.00%
Show the code
#import torch#import torch.nn as nnimport matplotlib.pyplot as plt# Assuming you have an input tensor 'input_tensor'input_tensor = torch.tensor([1, 2, 3, 4], dtype=torch.float32)# Create an instance of the 'Net' modelmodel = Net()# Set the model to evaluation modemodel.eval()# Store the intermediate layer outputsoutputs = []# Forward pass and store intermediate outputsdef hook(module, input, output): outputs.append(output)# Register the hook to capture intermediate outputshook_handle = model.fc3.register_forward_hook(hook)model(input_tensor.unsqueeze(0))hook_handle.remove()# Plot the intermediate outputsfor i, output inenumerate(outputs):print(i) plt.figure() plt.title(f'Layer {i+1} Output') plt.bar(range(output.size(-1)), output.squeeze().detach().numpy()) plt.show()