<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;"># -*- coding: utf-8 -*-
"""SVM Algorithm.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1oir7FRHsc9qIcLCaP8ALZ39ZaOh2PC0c
"""

# Import necessary libraries for data handling, preprocessing, modeling, and visualization
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, accuracy_score
import matplotlib.pyplot as plt
from google.colab import files

# Upload data file from local system
uploaded = files.upload()

# Extract uploaded file name and read the dataset
file_name = list(uploaded.keys())[0]  # Adjust based on the uploaded file name
data = pd.read_csv(file_name)

# Encode categorical variables into numerical values
label_encoders = {}
for column in data.columns:
    if data[column].dtype == 'object':
        le = LabelEncoder()
        data[column] = le.fit_transform(data[column])
        label_encoders[column] = le

# Separate features (X) and target variable (y)
X = data.drop('CLASS', axis=1)
y = data['CLASS']

# Normalize features (important for SVM)
scaler = StandardScaler()
X = scaler.fit_transform(X)

# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Create and train the SVM model with a linear kernel
svm_model = SVC(kernel='linear')  # Kernel and other parameters can be adjusted
svm_model.fit(X_train, y_train)

# Predict on the test set with the trained model
y_pred_test = svm_model.predict(X_test)

# Calculate and display accuracy on the test set
test_accuracy = accuracy_score(y_test, y_pred_test)
print(f"Test Accuracy: {test_accuracy}")

# Generate and export the confusion matrix to Excel
test_cm = confusion_matrix(y_test, y_pred_test)
cm_df = pd.DataFrame(test_cm, index=svm_model.classes_, columns=svm_model.classes_)
cm_df.to_excel('confusion_matrix_svm.xlsx')

# Plot the confusion matrix
fig, ax = plt.subplots(figsize=(10, 10))
ConfusionMatrixDisplay(test_cm, display_labels=svm_model.classes_).plot(ax=ax)
ax.set_title("Test Set Confusion Matrix (SVM)")
plt.show()

# Analysis of performance metrics from the confusion matrix

# Extract TP, FP, FN, and TN from the confusion matrix
TP = test_cm[1, 1]
TN = test_cm[0, 0]
FP = test_cm[0, 1]
FN = test_cm[1, 0]

# Calculate Recall, Precision, Accuracy, and Specificity
recall = TP / (TP + FN)
print(f"Recall: {recall}")
precision = TP / (TP + FP)
print(f"Precision: {precision}")
accuracy = (TP + TN) / (TP + TN + FP + FN)
print(f"Accuracy: {accuracy}")
specificity = TN / (TN + FP)
print(f"Specificity: {specificity}")

# Create a DataFrame to display calculated metrics
metrics_df = pd.DataFrame({
    "Metric": ["TP", "FP", "TN", "FN", "Recall", "Precision", "Accuracy", "Specificity"],
    "Value": [TP, FP, TN, FN, recall, precision, accuracy, specificity]
})

print(metrics_df)</pre></body></html>