Using the following inputs, answer the next few questions.
perform the necessary imports
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression, LinearRegression, Ridge
from sklearn.metrics import recall_score, make_scorer, mean_squared_error, confusion_matrix, precision_score, roc_curve, auc, accuracy_score, f1_score, roc_auc_score
from sklearn.utils.multiclass import unique_labels
from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder
import torch
import time
Plotting
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
Question 1: Load Datasets (15pts)
A) Load the "Dataset.csv" file.
B) Encode the output classes Label (0: Normal, 1: Abnormal) and separate inputs and outputs (features and target). (2 pts)
C) Split the data into equals-sized training and test sets. Use a random_state = 42, and ensure the balanced distribution of labels when splitting data.
D) How many observations do you have in your training set?
E) How many observations for each class in your training set?
F) Z-standarize the input features of the training and test sets.
Assistant
I'll guide you through the steps to achieve each of the tasks using the provided imports and libraries as well as Python code, assuming that you have the necessary dataset and environment set up.
A) Load the "Dataset.csv" file.
# Load the dataset
data = pd.read_csv('Dataset.csv')
B) Encode the output classes Label (0: Normal, 1: Abnormal) and separate inputs and outputs (features and target).
User
Now, answer the next set of questions:
A) Build a L1-regularized logistic regression model to all the training data, and then get the predicted labels for each item of the test set. Tip: use the 'saga' solver for L1 regularization.
B) Print out the precision, recall, and F1-score of the test set.
C) Print out the model execution time (both training and test time) in milliseconds. Please keep two decimal places.
D) Plot ROC curve and report the area under the ROC curve for the test data set.
Assistant
To complete the next set of tasks, I'll provide you with the Python code snippets based on the provided imports.
A) Build a L1-regularized logistic regression model and get predictions
# Start the timer
start_time = time.time()
# Create the logistic regression model with L1 regularization
# Note: C parameter controls the strength of regularization, inversely related to Lambda;
# smaller values specify stronger regularization. By default, C=1 provides a reasonable balance.
log_reg_l1 = LogisticRegression(penalty='l1', solver='saga', random_state=42)
# Train the model
log_reg_l1.fit(X_train_scaled, y_train)
# Make predictions on the test set
y_pred = log_reg_l1.predict(X_test_scaled)
# Stop the timer and calculate execution time
end_time = time.time()
execution_time = (end_time - start_time) * 1000 # Convert time to milliseconds
print(f"Model execution time: {execution_time:.2f} ms")
User
Build a simple neural network model (NN_model1) using PyTorch packages with the features in the data set as the input units and two output units for the two output classes:
Use a LogSigmoid as your output non-linearity.
Use the Cross-entropy loss as a training criterion.
Use Stochastic gradient descent optimizer with a learning rate of 0.01.
Run the optimization for 8000 iterations and record the loss for each iteration.
Plot the loss versus iterations.
Assistant
User
TypeError: NN_model1.init() takes 1 positional argument but 2 were given
Assistant
My apologies for the oversight. The error occurs because the custom neural network class NN_model1 is not properly defined to receive any additional arguments in the __init__ method apart from self. This can be rectified by updating the __init__ method to accept num_features. Here is the corrected neural network class definition:
# Define the Neural Network Model
class NN_model1(nn.Module):
def __init__(self, num_features):
super(NN_model1, self).__init__()
self.output = nn.Linear(num_features, 2) # Output layer with two units for binary classification
def forward(self, x):
x = self.output(x)
x = nn.LogSigmoid()(x) # Output non-linearity
return x
User
20 num_features = X_train_tensor.shape[1]
---> 21 model = NN_model1(num_features)
22
23 # Define Cross-Entropy Loss
TypeError: NN_model1.init() takes 1 positional argument but 2 were given
Assistant
Let's correct the issue. You are receiving this error because the class NN_model1 is not being instantiated correctly. The error message indicates that the __init__ method of the NN_model1 class is expecting only one argument (the self reference which is implicit), but it is receiving two arguments. This indicates that there is something off in the way the class is defined or instantiated.
The possible reason for this error might be because the function is not being called correctly in the method. Let's rewrite the class definition and instantiation code to make sure that this error doesn't happen:
User
TypeError: NN_model1.init() got an unexpected keyword argument 'num_features'
Assistant
I apologize for the confusion. It seems like there is still an issue with how the class NN_model1 is defined or instantiated. Let's correct this step by step.
First, here is the corrected class definition, incorporating best practices of defining the layers and forward pass in PyTorch:
# Define the Neural Network Model
class NN_model1(nn.Module):
def __init__(self, num_features):
super(NN_model1, self).__init__()
self.output = nn.Linear(num_features, 2) # Define the linear layer with 2 output features
def forward(self, x):
x = self.output(x) # Pass the input through the linear layer
x = torch.logsigmoid(x) # Apply log sigmoid to the output of the linear layer
return x
Now, when instantiating the model with , you don't need to use a keyword argument. Here's how you create an instance of your neural network model:
User
TypeError: NN_model1.init() takes 1 positional argument but 2 were given
Assistant
Apologies for the continued confusion. It seems there is some persistent error in either the class definition or how we are instantiating it. Let's solve this with the most basic example step by step.
User
Assuming your data is already scaled and split, let’s convert it into PyTorch tensors
X_train_tensor = torch.tensor(X_train.astype(np.float32))
y_train_tensor = torch.tensor(y_train.values.astype(np.int64)) # Cross-entropy expects a long int for classes
Define the Neural Network Model
class NN_model1(nn.Module):
def init(self, num_features):
super(NN_model1, self).init()
self.output = nn.Linear(num_features, 2) # Define the linear layer with 2 output features
def forward(self, x):
x = self.output(x) # Pass the input through the linear layer
x = torch.logsigmoid(x) # Apply log sigmoid to the output of the linear layer
return x
num_features = X_train_tensor.shape[1] # Get the number of feature inputs
Instantiate the NN_model1 model
model = NN_model1(num_features) # No need to specify argument name as it is the only argument expected
Assistant
The issue seems to be with the __init__ method of your NN_model1 class. There's a common mistake in the method definition where __init__ and super().__init__() are written as init and super().init() without the underscores. They should be __init__ and super().__init__() with double underscores, which is the proper way to define constructors in Python classes.
Here is the corrected NN_model1 class definition with the appropriate double underscores:
# Make sure to use double underscores for init methods
class NN_model1(nn.Module):
def __init__(self, num_features): # Correct here by adding double underscores
super(NN_model1, self).__init__() # Correct here by adding double underscores
self.output = nn.Linear(num_features, 2)
def forward(self, x):
x = self.output(x) # Output from the linear layer
x = torch.logsigmoid(x) # Apply LogSigmoid activation
return x
User
AttributeError: module 'torch' has no attribute 'logsigmoid'
Assistant
The error is because torch.logsigmoid is not a correct function in the PyTorch API. The proper way to apply the log-sigmoid operation in PyTorch is to create an instance of the LogSigmoid class from torch.nn and use it in the forward method, or by using the functional API torch.nn.functional.
Let's fix the NN_model1 class by using the functional API torch.nn.functional.logsigmoid:
import torch.nn.functional as F
# Define the Neural Network Model
class NN_model1(nn.Module):
def __init__(self, num_features):
super(NN_model1, self).__init__()
self.output = nn.Linear(num_features, 2)
def forward(self, x):
x = self.output(x) # Output from the linear layer
x = F.logsigmoid(x) # Apply log sigmoid activation using the functional API
return x
Here's how to instantiate and use the model:
User
Now use your trained model (NN_model1) to make predictions on the test set.
A) Print out the precision, recall, and F1-score of the test set.
B) Print out the model execution time (both training and test time) in milliseconds. Please keep two decimal places.
C) Plot ROC curve and report the area under the ROC curve for the test data set.
Assistant
User
Change the neural network (NN_model2) and add two hidden layers with 100 and 60 units, respectively. Use the LogSigmoid non-linearity for the hidden layers. Leave all the other parameters the same as for Question 3a. Again train for 8000 iterations and plot the loss as a function of the iteration.
Assistant
User
Now use your trained model in Question 3c (NN_model2) to make predictions on the test set.
A) Print out the precision, recall, and F1-score of the test set.
B) Print out the model execution time (both training and test time) in milliseconds. Please keep two decimal places.
C) Plot ROC curve and report the area under the ROC curve for the test data set.
Assistant
# Encode the output classes
label_encoder = LabelEncoder()
data['Label'] = label_encoder.fit_transform(data['Label'])
# Separate inputs and outputs
features = data.drop('Label', axis=1)
target = data['Label']
C) Split the data into equals-sized training and test sets ensuring the balanced distribution of labels.
D) How many observations do you have in your training set?
You can find the number of observations in the training set using the shape attribute.
num_observations_train = X_train.shape[0]
print(f"Number of observations in the training set: {num_observations_train}")
E) How many observations for each class in your training set?
You can use the value_counts method to get the number of observations for each class.
observations_per_class_train = y_train.value_counts()
print(f"Observations per class in the training set:\n{observations_per_class_train}")
F) Z-standarize the input features of the training and test sets.
# Initialize a standard scaler
scaler = StandardScaler()
# Fitting the scaler only on training data
X_train_scaled = scaler.fit_transform(X_train)
# Applying the transformation to the test data
X_test_scaled = scaler.transform(X_test)
# Note: In this example, I'm assuming that 'X_train' and 'X_test' are in a DataFrame format.
Remember to replace the 'Dataset.csv' placeholder with the correct path to the dataset file you have. After executing the code above, you will have completed the requested tasks.
B) Print out the precision, recall, and F1-score of the test set
Please be aware that the model's performance and execution time can vary depending on the hardware specifications of your computer, the size of the dataset, and particularities of the data itself.
To build a simple neural network using PyTorch with the constraints above, follow the steps outlined below. Note that we assume that the features and target variables (X_train_scaled, X_test_scaled, y_train, and y_test) have already been defined and processed according to previous code snippets.
import torch.nn as nn
import torch.optim as optim
# Assuming your data is already scaled and split, let's convert it into PyTorch tensors
X_train_tensor = torch.tensor(X_train_scaled.astype(np.float32))
y_train_tensor = torch.tensor(y_train.values.astype(np.int64)) # Cross-entropy expects a long int for classes
# Define the Neural Network Model
class NN_model1(nn.Module):
def __init__(self, num_features):
super(NN_model1, self).__init__()
self.output = nn.Linear(num_features, 2) # Output layer with two units for binary classification
def forward(self, x):
x = nn.LogSigmoid()(self.output(x)) # Output non-linearity
return x
num_features = X_train_tensor.shape[1]
model = NN_model1(num_features=num_features)
# Define Cross-Entropy Loss
criterion = nn.CrossEntropyLoss()
# Define the Stochastic Gradient Descent Optimizer
optimizer = optim.SGD(model.parameters(), lr=0.01)
# Train the model
losses = [] # to record loss per iteration
num_iterations = 8000
for iteration in range(num_iterations):
# Reset gradients
optimizer.zero_grad()
# Forward pass
outputs = model(X_train_tensor)
# Calculate loss
loss = criterion(outputs, y_train_tensor)
# Backward pass and update
loss.backward()
optimizer.step()
# Record loss
losses.append(loss.item())
# Optionally print the loss
print(f"Iter {iteration + 1}/{num_iterations}, Loss: {loss.item():.4f}")
# Plot the loss versus iterations
plt.plot(range(1, num_iterations + 1), losses, label='Loss vs Iterations')
plt.xlabel('Iterations')
plt.ylabel('Loss')
plt.legend()
plt.show()
To ensure the code runs successfully, make sure to execute this code block after the code blocks in which you've prepared your data (standardized inputs and outputs, converted to tensors). The neural network defined above is simple and consists of only the input and the output layer, without any hidden layers.
Please replace the loss printing part by uncommenting the line if you want to see how the loss changes during the training at each iteration.
Note that the PyTorch neural network expects the inputs to be float32 numpy arrays and the class labels to be int64. Additionally, the number of iterations here is set at 8000, which you can adjust based on your needs and convergence behavior.
Additionally, it might be better to instantiate the LogSigmoid only once in the __init__ method rather than re-instantiating it every time the forward method is called:
# Define the Neural Network Model
class NN_model1(nn.Module):
def __init__(self, num_features):
super(NN_model1, self).__init__()
self.output = nn.Linear(num_features, 2) # Output layer with two units for binary classification
self.logsigmoid = nn.LogSigmoid()
def forward(self, x):
x = self.output(x)
x = self.logsigmoid(x) # Output non-linearity
return x
With this correction, the neural network class NN_model1 now correctly takes the num_features argument when instantiated, which is used to define the number of input features for the linear layer. The rest of the code remains unchanged, and you should be able to run the network training loop without encountering the TypeError.
super()
__init__
NN_model1
# Define the Neural Network Model
class NN_model1(nn.Module):
def __init__(self, num_features):
super(NN_model1, self).__init__() # Make sure to call the superclass __init__ method
self.output = nn.Linear(num_features, 2) # Define the linear layer with 2 output features
self.logsigmoid = nn.LogSigmoid() # Instantiate LogSigmoid to use in forward pass
def forward(self, x):
x = self.output(x) # Pass the input through the linear layer
x = self.logsigmoid(x) # Apply log sigmoid to the output of the linear layer
return x
# Get the number of features from the training data
num_features = X_train_tensor.shape[1]
# Instantiate the NN_model1 with the appropriate number of input features
model = NN_model1(num_features=num_features) # Pass the number of features when instantiating the model
# ... rest of the code continues as before
Now with this corrected code, make sure that this class definition of NN_model1 is the one being used and the instantiation is done with num_features=num_features as an argument. If there was any previous NN_model1 definition in the notebook or script, please make sure to replace it with the one provided above. After doing so, you should run the cell containing the class definition again before you proceed to train the model.
NN_model1
num_features
num_features = X_train_tensor.shape[1] # Get the number of feature inputs
# Instantiate the NN_model1 model
model = NN_model1(num_features) # No need to specify argument name as it is the only argument expected
With the corrected code, try running your neural network training process again. You should define and instantiate the NN_model1 class with this corrected code to avoid the TypeError.
Remember, after making changes to your class, make sure to re-run the cell with the class definition in your Jupyter notebook (or re-execute the script if you're running a Python script), so the updated class is used.
Please try this out, and it should resolve the error you're encountering when instantiating the NN_model1 class.
Try this as your neural network module:
# Define Neural Network Module
class NN_model1(nn.Module):
def __init__(self, input_size):
super(NN_model1, self).__init__()
self.fc = nn.Linear(input_size, 2) # Only one layer with two output units
def forward(self, x):
x = self.fc(x)
return torch.logsigmoid(x) # LogSigmoid activation at the end
With correct instantiation:
# Assuming data is already scaled and in tensors X_train_tensor, y_train_tensor
input_size = X_train_tensor.shape[1] # Number of input features
# Create the model instance
model = NN_model1(input_size)
In the above definition, I have corrected the syntax and naming conventions. Ensure that this definition is the only one for NN_model1 in your environment (there might be older versions causing confusion). To instantiate the model, pass the single argument input_size directly since it matches the number of input features we are setting in the __init__ of our NN_model1 class.
Now, for the training part, use the following code as before:
# Define Cross-Entropy Loss
criterion = nn.CrossEntropyLoss()
# Define Stochastic Gradient Descent Optimizer
optimizer = optim.SGD(model.parameters(), lr=0.01)
# Convert labels to type 'long' as required by CrossEntropyLoss
y_train_tensor = y_train_tensor.long()
# Track the loss
losses = []
# Training loop
for iteration in range(8000):
# Forward pass
outputs = model(X_train_tensor)
loss = criterion(outputs, y_train_tensor)
# Backward pass and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Record loss
losses.append(loss.item())
# Plot loss curve
plt.figure()
plt.plot(losses, label='Training Loss')
plt.xlabel('Iterations')
plt.ylabel('Loss')
plt.legend()
plt.show()
Before running the training loop code, ensure all the previous cells (like the one with class definition and tensor conversion) are adjusted and run correctly to reflect these changes. The model class definition should be replaced entirely with the new code, and the instantiation should also follow the new method. If you encounter further issues, consider restarting your interpreter (Jupyter Kernel, etc.) to clear any previous definitions from the namespace before re-running the code.
losses = [] # to record loss per iteration
num_iterations = 8000
for iteration in range(num_iterations):
# Reset gradients
optimizer.zero_grad()
# Forward pass
outputs = model(X_train_tensor)
# Calculate loss
loss = criterion(outputs, y_train_tensor)
# Backward pass and update
loss.backward()
optimizer.step()
# Record loss
losses.append(loss.item())
# Optionally print the loss
print(f"Iter {iteration + 1}/{num_iterations}, Loss: {loss.item():.4f}")
It is still giving an TypeError: NN_model1.init() takes 1 positional argument but 2 were given
With this corrected class definition, you should now be able to instantiate your model without receiving the TypeError:
num_features = X_train_tensor.shape[1] # Number of input features
# Instantiate the model
model = NN_model1(num_features)
Make sure to replace the entire NN_model1 class in your code with the above corrected class. And again, ensure that you re-run the cell that contains the class definition if you're working in a Jupyter Notebook to reflect the changes. Then you may proceed with the training and the rest of your code as provided.
This should resolve the TypeError you're encountering, allowing you to proceed with model instantiation and training.
# Assuming data is already in tensors `X_train_tensor` and `y_train_tensor`
# Define the model
num_features = X_train_tensor.shape[1] # Remember, number of columns is the number of features
model = NN_model1(num_features)
# Rest of your code for defining the criterion, optimizer and training loop stays the same
Remember to run the class definition for NN_model1 again after making these changes. The functional API F.logsigmoid is now used properly and should not throw the AttributeError.
To use the trained model NN_model1 to make predictions on the test set and evaluate its performance, you'll first need to convert the test data into PyTorch tensors if you haven't done so already, then apply the model to get the predictions. After that, you can calculate the precision, recall, and F1-score, and plot the ROC curve.
Please note, ensure your model is trained before performing these steps.
Here is how you do it:
A) Evaluate the trained model on the test set
Convert the test data to PyTorch tensors:
X_test_tensor = torch.tensor(X_test.astype(np.float32))
y_test_tensor = torch.tensor(y_test.values.astype(np.int64)) # Cross-entropy expects a long int for classes
Make predictions:
# The model outputs log probabilities, so we take the exponent to get probabilities
# and then use these probabilities to predict the class with the highest probability
model.eval() # Set the model to evaluation mode
with torch.no_grad(): # No need to track the gradients
outputs = model(X_test_tensor)
probabilities = torch.exp(outputs) # Apply exp to get the probabilities from log probabilities
predicted_classes = torch.max(probabilities, 1)[1] # Get the index of the max probability
Calculate precision, recall, and F1-score:
from sklearn.metrics import precision_score, recall_score, f1_score
# Move tensors to CPU and convert to numpy arrays for use with sklearn metrics
y_pred_np = predicted_classes.cpu().numpy()
y_true_np = y_test_tensor.cpu().numpy()
precision = precision_score(y_true_np, y_pred_np)
recall = recall_score(y_true_np, y_pred_np)
f1 = f1_score(y_true_np, y_pred_np)
print(f"Precision: {precision:.2f}")
print(f"Recall: {recall:.2f}")
print(f"F1-score: {f1:.2f}")
B) Record and print out the model execution time
If timing was not recorded previously, you can simulate prediction with timing as follows (assuming you already have the trained model):
import time
start_time = time.time()
# Your code for predictions
end_time = time.time()
execution_time = (end_time - start_time) * 1000 # Convert to milliseconds
print(f"Execution time: {execution_time:.2f} ms")
C) Plot ROC curve and report the area under the curve
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
# Get probability scores for the positive class (class 1)
y_scores_np = probabilities[:, 1].cpu().numpy()
fpr, tpr, thresholds = roc_curve(y_true_np, y_scores_np)
roc_auc = auc(fpr, tpr)
plt.figure()
plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (AUC = {roc_auc:.2f})')
plt.plot([0, 1], [0, 1], color='navy', linestyle='--', lw=2)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic')
plt.legend(loc='lower right')
plt.show()
print(f"Area under the ROC curve: {roc_auc:.2f}")
This code assumes you have the test set data already loaded into X_test and y_test. Be sure to adjust the data conversion to tensors and the scoring part accordingly if your data has a different format or naming.
To modify the existing neural network (NN_model1) to include two hidden layers with 100 and 60 units respectively, and to use the LogSigmoid non-linearity, here's the full code you can use:
# Define Neural Network Module with two hidden layers
class NN_model2(nn.Module):
def __init__(self, input_size):
super(NN_model2, self).__init__()
self.hidden1 = nn.Linear(input_size, 100) # First hidden layer with 100 units
self.hidden2 = nn.Linear(100, 60) # Second hidden layer with 60 units
self.output = nn.Linear(60, 2) # Output layer with 2 units for binary classification
def forward(self, x):
x = torch.logsigmoid(self.hidden1(x)) # LogSigmoid activation for first hidden layer
x = torch.logsigmoid(self.hidden2(x)) # LogSigmoid activation for second hidden layer
x = self.output(x) # Output layer, no activation here
return x
# Assuming data is already in tensors `X_train_tensor` and `y_train_tensor`
input_size = X_train_tensor.shape[1]
model = NN_model2(input_size)
# Cross-Entropy Loss
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# Train the model
model.train() # Set the model to training mode
losses = [] # List to store loss per iteration
num_iterations = 8000
for iteration in range(num_iterations):
optimizer.zero_grad() # Zero the gradients
outputs = model(X_train_tensor) # Forward pass
loss = criterion(outputs, y_train_tensor) # Calculate the loss
loss.backward() # Backward pass
optimizer.step() # Update weights
# Record and print loss
losses.append(loss.item())
if (iteration + 1) % 1000 == 0: # Print every 1000 iterations
print(f"Iter {iteration + 1}/{num_iterations}, Loss: {loss.item():.4f}")
# Plotting Loss vs Iterations
plt.figure(figsize=(10,6))
plt.plot(losses, label="Training Loss")
plt.title("Loss vs. Iterations")
plt.xlabel("Iterations")
plt.ylabel("Loss")
plt.legend()
plt.show()
Make sure to convert your test and train datasets to tensors if you haven't done so already. You should use the same splits from the previous question, only the network architecture has changed. The training loop here is similar to the one used for NN_model1, but this time for the NN_model2 class with two hidden layers added.
Remember to re-initialize your model before running a new training loop if you have already trained NN_model1; otherwise, your model will have the old architecture still. The loss should decrease as the model learns from the training data, and you'll be able to visualize this decrease in the plot generated by the last few lines of code.
Now that the enhanced model NN_model2 with two hidden layers has been defined and trained for 8000 iterations, let's evaluate its performance on the test set. Let's start by making predictions using this model:
A) Make predictions and calculate precision, recall, and F1-score
# Convert test data into PyTorch tensors if you haven't already
X_test_tensor = torch.tensor(X_test.astype(np.float32))
y_test_tensor = torch.tensor(y_test.values.astype(np.int64))
# Make predictions with the model
model.eval() # Set the model to evaluation mode
with torch.no_grad():
outputs = model(X_test_tensor)
probabilities = torch.exp(outputs)
predicted_classes = torch.max(probabilities, 1)[1]
# Calculate metrics using sklearn
precision = precision_score(y_test_tensor, predicted_classes)
recall = recall_score(y_test_tensor, predicted_classes)
f1 = f1_score(y_test_tensor, predicted_classes)
print(f"Precision: {precision:.2f}")
print(f"Recall: {recall:.2f}")
print(f"F1-score: {f1:.2f}")
B) Measure and print out the model execution time
To get the execution time for training and testing (prediction), you would ideally have to wrap the training loop and the prediction code with the timing code and record the time taken for both.
However, assuming you have the time for the training phase already recorded from the 8000 iterations, let's get the execution time for the prediction phase:
start_time = time.time()
# The predictions code block, which is above
end_time = time.time()
prediction_time = (end_time - start_time) * 1000 # Convert to milliseconds
print(f"Prediction Execution Time: {prediction_time:.2f} ms")
C) Plot the ROC curve and calculate the area under the curve
# Before plotting, make sure your model is in evaluation mode and prediction code is done.
# Getting probabilities for class 1 (positive class)
# and moving them to the CPU and converting to numpy for sklearn
y_scores = probabilities[:, 1].cpu().numpy()
fpr, tpr, _ = roc_curve(y_test_tensor, y_scores)
roc_auc = auc(fpr, tpr)
plt.figure()
plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (area = {roc_auc:.2f})')
plt.plot([0, 1], [0, 1], color='navy', linestyle='--', lw=2)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.show()
print(f"Area under the ROC Curve (AUC): {roc_auc:.2f}")
This code will evaluate the model's performance on the test set, calculate the necessary statistics, and plot the ROC curve. The precision, recall, and F1-score will give you an insight into how well the model is doing on the test data, and the ROC curve along with the AUC (Area Under Curve) will provide an aggregated measure of performance across all classification thresholds.