@@ -20,17 +20,21 @@ def forward(self, x):
20
20
return x
21
21
22
22
def train_model (X_train , y_train , X_test , y_test , epochs ):
23
+ # Check for GPU availability
24
+ device = torch .device ('cuda' if torch .cuda .is_available () else 'cpu' )
25
+ print (f'Training on device: { device } ' )
26
+
23
27
# Convert data to NumPy arrays
24
28
X_train_np = X_train .to_numpy ()
25
29
y_train_np = y_train .to_numpy ()
26
30
X_test_np = X_test .to_numpy ()
27
31
y_test_np = y_test .to_numpy ()
28
32
29
- # Convert data to PyTorch tensors
30
- X_train_tensor = torch .tensor (X_train_np , dtype = torch .float32 )
31
- y_train_tensor = torch .tensor (y_train_np , dtype = torch .long )
32
- X_test_tensor = torch .tensor (X_test_np , dtype = torch .float32 )
33
- y_test_tensor = torch .tensor (y_test_np , dtype = torch .long )
33
+ # Convert data to PyTorch tensors and move to device
34
+ X_train_tensor = torch .tensor (X_train_np , dtype = torch .float32 ). to ( device )
35
+ y_train_tensor = torch .tensor (y_train_np , dtype = torch .long ). to ( device )
36
+ X_test_tensor = torch .tensor (X_test_np , dtype = torch .float32 ). to ( device )
37
+ y_test_tensor = torch .tensor (y_test_np , dtype = torch .long ). to ( device )
34
38
35
39
# Create DataLoader
36
40
train_dataset = torch .utils .data .TensorDataset (X_train_tensor , y_train_tensor )
@@ -40,7 +44,7 @@ def train_model(X_train, y_train, X_test, y_test, epochs):
40
44
num_classes = len (y_train .unique ())
41
45
42
46
# Initialize the model, loss function, and optimizer
43
- model = Net (X_train .shape [1 ], num_classes )
47
+ model = Net (X_train .shape [1 ], num_classes ). to ( device )
44
48
criterion = nn .CrossEntropyLoss ()
45
49
optimizer = optim .Adam (model .parameters (), lr = 0.001 )
46
50
@@ -73,7 +77,7 @@ def train_model(X_train, y_train, X_test, y_test, epochs):
73
77
with torch .no_grad ():
74
78
test_outputs = model (X_test_tensor )
75
79
_ , test_predicted = torch .max (test_outputs , 1 )
76
- test_accuracy = accuracy_score (y_test_tensor , test_predicted ) * 100
80
+ test_accuracy = accuracy_score (y_test_tensor . cpu () , test_predicted . cpu () ) * 100
77
81
test_accuracies .append (test_accuracy )
78
82
79
83
print (f'Epoch { epoch + 1 } /{ epochs } , Loss: { loss .item ()} , Training Accuracy: { train_accuracy :.2f} %, Test Accuracy: { test_accuracy :.2f} %' )
@@ -87,6 +91,7 @@ def train_model(X_train, y_train, X_test, y_test, epochs):
87
91
plt .title ('Training and Test Accuracy over Epochs' )
88
92
plt .legend ()
89
93
plt .grid (True )
94
+ plt .savefig ('nids/training_test_accuracy.png' ) # Save the plot as a PNG file
90
95
plt .show ()
91
96
92
97
return model , num_classes
0 commit comments