-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvm_classifier.py
More file actions
49 lines (42 loc) · 1.67 KB
/
svm_classifier.py
File metadata and controls
49 lines (42 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Filename: svm_classifier.py
# Description: SVM-based classifier for a given dataset
# Author: Haider Marouf
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
def load_data(path):
"""Loads dataset from a CSV file."""
return pd.read_csv(path)
def preprocess_data(df, label_column):
"""Splits features and labels."""
X = df.drop(columns=[label_column])
y = df[label_column]
return train_test_split(X, y, test_size=0.2, random_state=42)
def train_svm(X_train, y_train, kernel='linear', C=1.0):
"""Trains an SVM model."""
model = SVC(kernel=kernel, C=C)
model.fit(X_train, y_train)
return model
def evaluate_model(model, X_test, y_test):
"""Evaluates the model and prints metrics."""
predictions = model.predict(X_test)
print(confusion_matrix(y_test, predictions))
print(classification_report(y_test, predictions))
return predictions
def plot_confusion_matrix(y_true, y_pred):
cm = confusion_matrix(y_true, y_pred)
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues")
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.title("Confusion Matrix")
plt.show()
if __name__ == "__main__":
df = load_data("your_dataset.csv") # replace with your dataset
X_train, X_test, y_train, y_test = preprocess_data(df, label_column="your_target") # replace with your target
model = train_svm(X_train, y_train, kernel='rbf', C=1.0)
predictions = evaluate_model(model, X_test, y_test)
plot_confusion_matrix(y_test, predictions)