0% found this document useful (0 votes)
34 views8 pages

Python SVM Implementation Guide

SVM_Implementation
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views8 pages

Python SVM Implementation Guide

SVM_Implementation
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Implementation of Support Vector Machine

Now we will implement the SVM algorithm using Python. Here we will use
the same dataset user_data, which we have used in Logistic regression
and KNN classification.

o Data Pre-processing step

Till the Data pre-processing step, the code will remain the same. Below is
the code:

1. #Data Pre-processing Step


2. # importing libraries
3. import numpy as nm
4. import [Link] as mtp
5. import pandas as pd
6.
7. #importing datasets
8. data_set= pd.read_csv('user_data.csv')
9.
10. #Extracting Independent and dependent Variable
11. x= data_set.iloc[:, [2,3]].values
12. y= data_set.iloc[:, 4].values
13.
14. # Splitting the dataset into training and test set.
15. from sklearn.model_selection import train_test_split
16. x_train, x_test, y_train, y_test= train_test_split(x, y, test_size= 0.25, r
andom_state=0)
17. #feature Scaling
18. from [Link] import StandardScaler
19. st_x= StandardScaler()
20. x_train= st_x.fit_transform(x_train)
21. x_test= st_x.transform(x_test)

After executing the above code, we will pre-process the data. The code will
give the dataset as:
The scaled output for the test set will be:
Fitting the SVM classifier to the training set:

Now the training set will be fitted to the SVM classifier. To create the SVM
classifier, we will import SVC class from [Link] library. Below is the
code for it:

1. from [Link] import SVC # "Support vector classifier"


2. classifier = SVC(kernel='linear', random_state=0)
3. [Link](x_train, y_train)

In the above code, we have used kernel='linear', as here we are creating


SVM for linearly separable data. However, we can change it for non-linear
data. And then we fitted the classifier to the training dataset(x_train,
y_train)

Output:

Out[8]:
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3, gamma='auto_deprecated',
kernel='linear', max_iter=-1, probability=False, random_state=0,
shrinking=True, tol=0.001, verbose=False)

The model performance can be altered by changing the value


of C(Regularization factor), gamma, and kernel.

o Predicting the test set result:


Now, we will predict the output for test set. For this, we will create a
new vector y_pred. Below is the code for it:

1. #Predicting the test set result


2. y_pred= [Link](x_test)

After getting the y_pred vector, we can compare the result


of y_pred and y_test to check the difference between the actual value and
predicted value.

Output: Below is the output for the prediction of the test set:
o Creating the confusion matrix:
Now we will see the performance of the SVM classifier that how many
incorrect predictions are there as compared to the Logistic regression
classifier. To create the confusion matrix, we need to import
the confusion_matrix function of the sklearn library. After importing
the function, we will call it using a new variable cm. The function
takes two parameters, mainly y_true( the actual values)
and y_pred (the targeted value return by the classifier). Below is the
code for it:

1. #Creating the Confusion matrix


2. from [Link] import confusion_matrix
3. cm= confusion_matrix(y_test, y_pred)

Output:
As we can see in the above output image, there are 66+24= 90 correct
predictions and 8+2= 10 correct predictions. Therefore we can say that our
SVM model improved as compared to the Logistic regression model.

o Visualizing the training set result:


Now we will visualize the training set result, below is the code for it:

1. from [Link] import ListedColormap


2. x_set, y_set = x_train, y_train
3. x1, x2 = [Link]([Link](start = x_set[:, 0].min() -
1, stop = x_set[:, 0].max() + 1, step =0.01),
4. [Link](start = x_set[:, 1].min() -
1, stop = x_set[:, 1].max() + 1, step = 0.01))
5. [Link](x1, x2, [Link]([Link]([[Link](), [Link]()])
.T).reshape([Link]),
6. alpha = 0.75, cmap = ListedColormap(('red', 'green')))
7. [Link]([Link](), [Link]())
8. [Link]([Link](), [Link]())
9. for i, j in enumerate([Link](y_set)):
10. [Link](x_set[y_set == j, 0], x_set[y_set == j, 1],
11. c = ListedColormap(('red', 'green'))(i), label = j)
12. [Link]('SVM classifier (Training set)')
13. [Link]('Age')
14. [Link]('Estimated Salary')
15. [Link]()
16. [Link]()

Output:

By executing the above code, we will get the output as:

As we can see, the above output is appearing similar to the Logistic


regression output. In the output, we got the straight line as hyperplane
because we have used a linear kernel in the classifier. And we have also
discussed above that for the 2d space, the hyperplane in SVM is a straight
line.

o Visualizing the test set result:

1. #Visulaizing the test set result


2. from [Link] import ListedColormap
3. x_set, y_set = x_test, y_test
4. x1, x2 = [Link]([Link](start = x_set[:, 0].min() -
1, stop = x_set[:, 0].max() + 1, step =0.01),
5. [Link](start = x_set[:, 1].min() -
1, stop = x_set[:, 1].max() + 1, step = 0.01))
6. [Link](x1, x2, [Link]([Link]([[Link](), [Link]()])
.T).reshape([Link]),
7. alpha = 0.75, cmap = ListedColormap(('red','green' )))
8. [Link]([Link](), [Link]())
9. [Link]([Link](), [Link]())
10. for i, j in enumerate([Link](y_set)):
11. [Link](x_set[y_set == j, 0], x_set[y_set == j, 1],
12. c = ListedColormap(('red', 'green'))(i), label = j)
13. [Link]('SVM classifier (Test set)')
14. [Link]('Age')
15. [Link]('Estimated Salary')
16. [Link]()
17. [Link]()

Output:

By executing the above code, we will get the output as:

As we can see in the above output image, the SVM classifier has divided
the users into two regions (Purchased or Not purchased). Users who
purchased the SUV are in the red region with the red scatter points. And
users who did not purchase the SUV are in the green region with green
scatter points. The hyperplane has divided the two classes into Purchased
and not purchased variable.

Common questions

Powered by AI

A confusion matrix is used to evaluate the performance of an SVM model by comparing actual vs. predicted class labels for the test set. It summarizes correct and incorrect predictions. In the provided example, the SVM model produced 90 correct and 10 incorrect predictions, showing improved accuracy compared to the logistic regression model, although the logistic regression results are not detailed here .

Changing SVM parameters such as C, gamma, and the kernel can significantly impact model performance. The parameter C adjusts the trade-off between achieving a low training error and a low testing error, influencing overfitting. Gamma defines the influence of a single training example, affecting the shape of the decision boundary. Different kernels (linear, polynomial, RBF) allow SVMs to model datasets with different distributions, improving accuracy for non-linear data .

A non-linear kernel is preferred when the data is not linearly separable, meaning that a straight line cannot effectively separate the classes in the feature space. Non-linear kernels like the polynomial or RBF enable the classifier to identify complex boundaries by mapping input data into higher-dimensional spaces where linear separability might be achievable .

The SVM classifier handles datasets with multiple features by finding a hyperplane in a high-dimensional space. Each feature is a dimension, and SVM optimizes the hyperplane's orientation and position for effective class separation. Considerations include feature scaling, as SVM is sensitive to input scales, and computational complexity, since SVM may struggle with very large feature sets, necessitating techniques like dimensionality reduction .

The SVM classifier can visualize decision boundaries by first training on a dataset, then using mesh grid techniques to predict class labels across a plane. In real-world problems, after fitting the classifier, functions like contourf project the decision boundary over scatter plots of actual data points, enabling interpretation of how different feature combinations relate to class decisions. This method is practical in domains like finance or bioinformatics for visualizing classification outcomes and decision regions .

Using a linear kernel in an SVM classifier results in a hyperplane that is a straight line when visualized in 2D space. This indicates that the classifier assumes the data is linearly separable. In the given example, the linear kernel causes the SVM to create a decision boundary that divides the space into regions corresponding to different classes, reflecting a binary classification framework .

Data pre-processing prepares the dataset for the SVM algorithm by cleaning and transforming it into a suitable format. Main steps involved include importing necessary libraries, loading the dataset, extracting independent and dependent variables, splitting the dataset into training and test sets, and scaling the features to standardize the data range. These steps are critical for ensuring the algorithm's efficiency and effectiveness .

Visualizing the decision boundary of an SVM classifier involves creating a mesh grid of feature values and then using contour plots to display the decision boundary. The code snippets show this process, using the contour function to plot predictions overlaid on the actual class scatter. For both training and test datasets, matplotlib is used to create the visualization, with colors depicting different classes in the decision space .

The SVM regularization factor, denoted as C, controls the trade-off between maximizing the margin and minimizing the classification error. A large C value prioritizes a low training error, potentially causing overfitting by fitting to noise, whereas a small C results in a wider margin that can better generalize to test data by allowing more misclassifications on the training data. This balance affects the model's ability to generalize effectively .

Feature scaling is crucial in the SVM algorithm because it ensures that all features contribute equally to the result, preventing features with larger ranges from dominating the analysis. In the provided dataset, feature scaling is implemented using the StandardScaler class from sklearn.preprocessing. The training and test data are transformed to have mean 0 and variance 1, which is achieved by calling fit_transform on the training data and then transform on the test data .

You might also like