<jupyter_start><jupyter_text>`This notebook is an Illustration to create a Support Vector Machine with Sklearn using Python 🐍`For more information, check out the [SVM](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html).  **Setup**Let's setup the imports:<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

import seaborn as sns
from matplotlib.colors import ListedColormap

from sklearn.svm import SVC
from sklearn.svm import LinearSVC
from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler

from sklearn.metrics import accuracy_score, classification_report, confusion_matrix 


# custom color maps
cm_dark = ListedColormap(['#ff6060', '#8282ff','#ffaa00','#fff244','#4df9b9','#76e8fc','#3ad628'])
cm_bright = ListedColormap(['#ffafaf', '#c6c6ff','#ffaa00','#ffe2a8','#bfffe7','#c9f7ff','#9eff93'])<jupyter_output><empty_output><jupyter_text>**Datatset**Let's load the Mobile Price Classification dataset which is uploaded on my Google Drive.<jupyter_code>!gdown --id 17wpxB4XilNQ54Yf7aYrpK6vTrvE7f5Gh 
!gdown --id 1hxdj2JGckweySFIJluiCztjAndsNLfGG<jupyter_output>Downloading...
From: https://drive.google.com/uc?id=17wpxB4XilNQ54Yf7aYrpK6vTrvE7f5Gh
To: /content/train.csv
100% 122k/122k [00:00<00:00, 48.2MB/s]
Downloading...
From: https://drive.google.com/uc?id=1hxdj2JGckweySFIJluiCztjAndsNLfGG
To: /content/test.csv
100% 63.9k/63.9k [00:00<00:00, 72.1MB/s]<jupyter_text>Let's read the CVS files:<jupyter_code>df = pd.read_csv("/content/train.csv")
test = pd.read_csv("/content/test.csv")<jupyter_output><empty_output><jupyter_text>First few rows in the DataFrame:<jupyter_code>df.head()<jupyter_output><empty_output><jupyter_text>Let's see if we have any null values:<jupyter_code>df.shape
df.isnull().sum()<jupyter_output><empty_output><jupyter_text>Now in the data set there is no need to create dummy variables or handle missing data as data set doesn't have any missing data. Let's see the columns present in our dataFrame:<jupyter_code>df.columns<jupyter_output><empty_output><jupyter_text>Let's set our variables for training from our dataFrame into numpy arrays:<jupyter_code>y_t = np.array(df['price_range']) 
x_t = df
x_t = df.drop(['price_range'], axis=1)
x_t = np.array(x_t)  
print("shape of x :"+str(x_t.shape))
print("shape of y :"+str(y_t.shape))<jupyter_output>shape of x :(2000, 20)
shape of y :(2000,)<jupyter_text>Let's scale our numpy variables using sklearn's MinMaxScalar:Reference: [MinMaxScalar](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html)<jupyter_code>scaler = MinMaxScaler() 
x_t = scaler.fit_transform(x_t)  
X_train,X_test,Y_train,Y_test = train_test_split(x_t, y_t, test_size=.20, random_state=42)
print("shape of X Train :"+str(X_train.shape))
print("shape of X Test :"+str(X_test.shape))
print("shape of Y Train :"+str(Y_train.shape))
print("shape of Y Test :"+str(Y_test.shape))
# plotting the decision boundries for the data 
#converting the data to array for plotting.
x = np.array(df.iloc[:,[0,13]])
y = np.array(df['price_range'])
print("Shape of x:"+str(x.shape))
print("Shape of y:"+str(y.shape))
x = scaler.fit_transform(x)
plt.scatter(x[:,0], x[:,1], c = y, cmap = cm_dark, s=15, label = y) 
plt.title("Scatter Plot", fontweight='bold')
plt.show();<jupyter_output><empty_output><jupyter_text>Let's split our variables into train and test sets:  Support Vector Machine with Linear Kernel<jupyter_code>for c_values in [1, 2, 3, 5,10, 20, 40, 60, 80, 100, 150, 200]:
  clf = SVC(kernel='linear', C = c_values).fit(X_train, Y_train) 
  scoretrain = clf.score(X_train, Y_train)
  scoretest = clf.score(X_test, Y_test) 
  print("Linear SVC of C: {}, Training Score: {:2f}, Testing Score: {:2f}\n".format(c_values, scoretrain, scoretest)) 
y_pred = clf.predict(X_test)  
cm = confusion_matrix(y_pred, Y_test) 
fig, ax = plt.subplots(figsize=(8,5))
sns.heatmap(cm, annot = True, cmap = 'YlGnBu', fmt='g'); 
plt.title('Confusion matrix', fontweight='bold')
plt.ylabel('Actual label', fontweight='bold')
plt.xlabel('Predicted label', fontweight='bold'); 
h =0.02
C_param = 1
clf1 = SVC(kernel = 'linear', C = C_param)
clf1.fit(x, y)

# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
x_min, x_max = x[:, 0].min()-.20, x[:, 0].max()+.20
y_min, y_max = x[:, 1].min()-.20, x[:, 1].max()+.20
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = clf1.predict(np.c_[xx.ravel(), yy.ravel()])   # ravel to flatten the into 1D and c_ to concatenate 

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cm_bright)

# Plot also the training points
plt.scatter(x[:, 0], x[:, 1], c=y, cmap=cm_dark, edgecolor='k', s=20)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("SVM Linear Classification (kernal = linear, C = '%s')"% (C_param))

plt.show()<jupyter_output><empty_output><jupyter_text>Linear Support Vector Machine<jupyter_code># Linear Support vector machine with only C Parameter 
for this_C in [1,3,5,10,40,60,80,100]:
    clf2 = LinearSVC(C=this_C, max_iter=50000).fit(X_train,Y_train)
    scoretrain2 = clf2.score(X_train,Y_train)
    scoretest2  = clf2.score(X_test,Y_test) 
    print("Linear SVM value of C:{}, training score :{:2f} , Test Score: {:2f} \n".format(this_C,scoretrain2,scoretest2))
y_pred = clf2.predict(X_test)  
cm = confusion_matrix(y_pred, Y_test) 
fig, ax = plt.subplots(figsize=(8,5))
sns.heatmap(cm, annot = True, cmap = 'YlGnBu', fmt='g'); 
plt.title('Confusion matrix', fontweight='bold')
plt.ylabel('Actual label', fontweight='bold')
plt.xlabel('Predicted label', fontweight='bold');<jupyter_output><empty_output><jupyter_text>Apparently we got better scores with SVC where we defined the kernal as linear than with just LinearSVCThe LinearSVC class is based on the liblinear library, which Uses a coordinate descent optimization algorithm for linear SVMs.1. It does not support the kernel trick, but it scales almost linearly with the number of training instances and the number of features: its training time complexity is roughly O(m × n).The SVC class is based on the libsvm library, which implements the Sequential minimal optimization (SMO) algorithm for kernelized support vector machines (SVMs), supporting classification and regression, that supports the kernel trick.1. The training time complexity is usually between O(m2 × n) and O(m3 × n).2. LinearSVC is much faster than SVC(kernel="linear")3. In this case, we got better scores in SVC than LinearSVC      Support Vector Machine with Gaussian Kernel<jupyter_code># SMV with RBF KERNAL AND ONLY C PARAMETER 

for this_C in [1,5,10,25,50,100]:
    clf3 = SVC(kernel='rbf',C=this_C).fit(X_train,Y_train)
    clf3train = clf3.score(X_train,Y_train)
    clf3test  = clf3.score(X_test,Y_test)
    print("SVM for Non Linear \n C:{} Training Score : {:2f} Test Score : {:2f}\n".format(this_C,clf3train,clf3test)) 
y_pred = clf3.predict(X_test)  
cm = confusion_matrix(y_pred, Y_test) 
fig, ax = plt.subplots(figsize=(8,5))
sns.heatmap(cm, annot = True, cmap = 'YlGnBu', fmt='g'); 
plt.title('Confusion matrix', fontweight='bold')
plt.ylabel('Actual label', fontweight='bold')
plt.xlabel('Predicted label', fontweight='bold');  
h = .02  # step size in the mesh
C_param = 1 # No of neighbours
# we create an instance of Neighbours Classifier and fit the data.
clf4 = SVC(kernel='rbf',C=C_param)
clf4.fit(x, y)

# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
x_min, x_max = x[:, 0].min(), x[:, 0].max()
y_min, y_max = x[:, 1].min(), x[:, 1].max()
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = clf4.predict(np.c_[xx.ravel(), yy.ravel()])   # ravel to flatten the into 1D and c_ to concatenate 

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cm_bright)
# Plot also the training points
plt.scatter(x[:, 0], x[:, 1], c=y, cmap=cm_dark, edgecolor='k', s=20)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("SVM Non Linear Classification (kernal = RBF, C = '%s')"% (C_param), fontweight='bold')

plt.show();
# SVM WITH RBF KERNAL, C AND GAMMA HYPERPARAMTER 
for this_gamma in [.1,.5,.10,.25,.50,1]:
    for this_C in [1,5,7,10,15,25,50]:
        clf5 = SVC(kernel='rbf',C=this_C,gamma=this_gamma).fit(X_train,Y_train)
        clf5train = clf5.score(X_train,Y_train)
        clf5test  = clf5.score(X_test,Y_test)
        print("SVM for Non Linear \n Gamma: {} C:{} Training Score : {:2f} Test Score : {:2f}\n".format(this_gamma,this_C,clf5train,clf5test)) 
y_pred = clf5.predict(X_test)  
cm = confusion_matrix(y_pred, Y_test) 
fig, ax = plt.subplots(figsize=(8,5))
sns.heatmap(cm, annot = True, cmap = 'YlGnBu', fmt='g'); 
plt.title('Confusion matrix', fontweight='bold')
plt.ylabel('Actual label', fontweight='bold')
plt.xlabel('Predicted label', fontweight='bold');  
h = .02  # step size in the mesh
C_param = 1 # No of neighbours
gamma_value = 0.1
# we create an instance of Neighbours Classifier and fit the data.
clf6 = SVC(kernel='rbf',C=C_param, gamma=gamma_value)
clf6.fit(x, y)

# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
x_min, x_max = x[:, 0].min(), x[:, 0].max()
y_min, y_max = x[:, 1].min(), x[:, 1].max()
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = clf6.predict(np.c_[xx.ravel(), yy.ravel()])   # ravel to flatten the into 1D and c_ to concatenate 

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cm_bright)
# Plot also the training points
plt.scatter(x[:, 0], x[:, 1], c=y, cmap=cm_dark, edgecolor='k', s=20)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("SVM Non Linear Classification (kernal = RBF, Gamma = {}, C = {})".format(gamma_value, C_param), fontweight='bold')

plt.show();<jupyter_output><empty_output><jupyter_text>THE GRIDSEARCH !!!!Let's do something interesting,you can pass all the expected values of the hyperparameters and it'll return the best value which fits the model.<jupyter_code># grid search method 
param_grid = {'C': [1, 2, 3, 5, 7, 10, 15, 20, 25, 50, 100, 120, 150],
              'gamma': [.1, .2, .5,.10,.25,.50,1]}
GS = GridSearchCV(SVC(kernel='rbf'),param_grid,cv=5) 
GS.fit(X_train, Y_train)
print("the parameters {} are the best.".format(GS.best_params_))
print("the best score is {:.2f}.".format(GS.best_score_))<jupyter_output>the parameters {'C': 7, 'gamma': 0.1} are the best.
the best score is 0.90.<jupyter_text>Support Vector Regressor<jupyter_code>svr = SVR(kernel='linear', C=1, epsilon=.01).fit(X_train, Y_train)
print("{:.2f} is the accuracy of the SV Regressor".format(svr.score(X_train,Y_train)))<jupyter_output>0.92 is the accuracy of the SV Regressor<jupyter_text>- SVM supports linear and nonlinear regression.- SVM Regression tries to fit as many instances as possible on the decision boundary while limiting margin violations.- The width of the decision boundary is controlled by a hyperparameter ϵ.<jupyter_code># Kernalized SVM machine, by default kernel = 'rgf'
svr2 = SVR(degree=2,C=100,epsilon=.01).fit(X_train,Y_train)
print("{:.2f} is the accuracy of the SV Regressor".format(svr2.score(X_train, Y_train)))<jupyter_output>1.00 is the accuracy of the SV Regressor
{'fraction_non_alphanumeric': 0.14928706407833706, 'fraction_numerical': 0.030493042432571723, 'mean_word_length': 5.656946826758148, 'pattern_counts': {'":': 0, '<': 54, '<?xml version=': 0, '>': 52, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '404457', 'license': 'Apache-2.0', 'n_tokens_mistral': 4720, 'n_tokens_neox': 4436, 'n_words': 1166, 'path': 'Support_Vector_Machine.ipynb', 'repo_name': 'nakshatrasinghh/Machine-Learning', 'size': '11642'}