Support Vector Machine using Python

In the previous article, we studied the K-Means Clustering. One thing that I believe is that if we can correlate anything with us or our lives, there are greater chances of understanding the concept. So I will try to explain everything by relating it to humans.

What is a Support Vector Machine?

Support vector machines (SVMs, also supporting vector networks) in machine learning are supervised learning models with associated learning algorithms that analyze data used for classification and regression analysis. Provided a set of training instances, each classified as belonging to one or the other of two groups, a training algorithm SVM generates a template that sells new cases for one or the other group, which renders it a non-probabilistic linear binary classifier.
A model from SVM describes the examples as points in space and is distributed to separate the examples of the different groups through a very broad void. There are then projected new instances in the same area and a range dependent on the portion of the distance in which they fall is predicted.
A hyperplane or a number of hyperplanes in a small or infinite space may be created by the support- computer and can be used for the graduation or reversal or other tasks such as the identification of outliers. The hyperplanes with the largest distance from the closest training data point of any class (so-called functional margin) intuitively achieve a good separation, as the wider the margin, the lower the generalization error of the classification system.
Note:
When data are unlisted, supervised education is not available and there is a need for an unsupervised learning approach that attempts to find a natural grouping of data and then map new data to the groups that are formed.

Key Terms

  1. Kernel

    • A kernel refers to a feature that converts the data into a wide space for solving the problem.
    • A linear or non-linear kernel function may be used. Kernel methods are a type of pattern analysis algorithm.
    • The kernel's primary role is to accept data as input and convert it into the appropriate output types.
    • In statistics, the mapping feature "core" measures the values of two-dominal data in a three-dimensional spatial format and describes them.
  2. Regularization

    • The regularization function is also named the C function in the sklearn library of python, which guides the help vector machine to optimally define each training date it wants to prevent.
    • Such a supporting vector machine example will auto-optimization if large numbers of the C parameter are used if all training data points are correctly segregated and classification is collected the hyperplanes margin that is smaller.
    • To order to obtain very tiny numbers, the algorithm can often consider that the hyperplane is a larger range and certain data points may be misclassified by the hyperplane.
  3. Gamma

    • This tuning function reiterates the length of the effect of a single data display. The low values are 'far' and the higher values are 'near' to the aircraft.
    • In measurement for a separation line, the data points with low gamma are called and are far from the possible hyper-plane separation line.
    • In comparison, the high range is used in the measurement of the hyper-plane separation line which applies to the points that are similar to the expected hyper-plane line.
  4. Margin

    • The gap is last but not least. It's also a significant tuning parameter & an integral function of a vector holder classification system.
    • The margin is the division of the line closest to the data points of the segment. In a support vector algorithm, it is necessary to have a good and proper margin. When the difference between the two data groups is greater, a strong gap is called.
    • To a strong range, the corresponding data points stay in class and thus do not move over to another level.
    • Also, the class data points will have a reasonable margin preferably at the same distance from either side of the separator panel.
  5. Hyperplane

    • A hyperplane is a linear, n-1 dimensional subset of this space, which splits the space into two divided parts in an n-dimensional Euclidean space.
    • For two dimensions the hyperplane is a separating line.
    • For three dimensions a plane with two dimensions divides the 3d space into two parts and thus acts as a hyperplane.
    • Thus for a space of n dimensions, we have a hyperplane of n-1 dimensions separating it into two parts.

Types of SVM

  1. Classification SVM type 1 (also known as C-SVM classification)
  2. Classification SVM type 2 (also known as nu-SVM classification)
  3. Regression SVM type 1 (also known as epsilon-SVM regression)
  4. Regression SVM type 2 (also known as nu-SVM regression)

Types of kernels

  1. Linear kernel
  2. Polynomial kernel
  3. Radial basis function kernel (RBF)/ Gaussian Kernel
  4. Sigmoid Kernel
  5. Nonlinear Kernel

Advantages/Features of SVM

  1. It is really effective in a higher dimension.
  2. Effective when the number of features is more than training examples.
  3. Best algorithm when classes are separable
  4. The hyperplane is affected by only the support vectors thus outliers have less impact.
  5. SVM is suited for extreme case binary classification.

Disadvantages/Shortcomings of SVM

  1. For the larger dataset, it requires a large amount of time to process.
  2. It does not perform well in case of overlapped classes.
  3. Selecting, appropriately hyperparameters of the SVM that will allow for sufficient generalization performance.
  4. Selecting the appropriate kernel function can be tricky.

Real-World Applications of SVM

  1. Face detection
    SVM classifies parts of the image as a face and non-face and creates a square boundary around the face.

  2. Text and hypertext categorization
    SVMs allow Text and hypertext categorization for both inductive and transductive models. They use training data to classify documents into different categories. It categorizes on the basis of the score generated and then compares with the threshold value.

  3. Classification of images
    Use of SVMs provides better search accuracy for image classification. It provides better accuracy in comparison to the traditional query-based searching techniques.

  4. Bioinformatics
    It includes protein classification and cancer classification. We use SVM for identifying the classification of genes, patients on the basis of genes and other biological problems.

  5. Protein fold and remote homology detection
    Apply SVM algorithms for protein remote homology detection.

  6. Handwriting recognition
    We use SVMs to recognize handwritten characters used widely.

  7. Generalized predictive control(GPC)
    Use SVM based GPC to control chaotic dynamics with useful parameters.

SVM using Example

Like in other ML algorithms we find the best fit, in SVM we try to find a hyperplane with the maximum margin or distance, hence it is also a type of "maximum-margin" classification.
Let us try to understand SVM with the help of a mathematical example, for this example,
Data Points Class
(-2, 4) -1
(4,1) -1
(1,6) 1
(2,4) 1
(6,2) 1
Now before I go on further I want you to first know:

1. Hinge loss

In machine learning, the hinge loss is a loss function used for training classifiers. The hinge loss is used for "maximum-margin" classification, most notably for support vector machines (SVMs).
The equation is given as:
hinge1
where c is the loss function, x the sample, y is the true label, f(x) the predicted label.
You see a plus at the end, it means that the hinge error can never be negative, mathematically I can be expressed as:
hinge2

2. Regularizer

The regularizer balances between margin maximization and loss. The regularizer controls the trade-off between achieving a low training error and a low testing error that is the ability to generalize your classifier to unseen data. As a regularizing parameter we choose 1/epochs, so this parameter will decrease, as the number of epochs increases.
Regularixer, λ = 1/epoch

3. Weight Vector

The SVM algorithm chooses a particular weight vector, that which gives rise to the “maximum margin” of separation
Now coming back to the math of SVM, generation of the hyperplane we can have 2 scenarios
1. Misclassification, i.e. the point is not classified correctly
2. Correct Classification
In the case of misclassification, we use the following to update the weights:
hinge3
and in case of correct classification, we use the following to update the weights:
hinge4
where,
  • η is the learning rate
  • λ is the regularizer
After doing the calculations, I came up with the following prediction function:
f(x) = (x, (1.56, 3.17))- 11.12
i.e f(x) = 1.56*x + 3.17*y -11.12
where,
  • (1.56, 3.17) is the weight vector
  • 11.12 is the bias term
Note: I will not be going into depth on how I got this, you can do the calculations by yourself or you can use sklearn to do it for you.
Now let us check the accuracy of the prediction function so calculated
1. -2*1.56 + 4*3.17 - 11.12
= -1.56
taking the sign out, we get -1, which is the correct class
2. 4*1.56 + 1*3.17 - 11.12
= -1.72
taking the sign out, we get -1, which is the correct class
3. 1*1.56 + 6*3.17 - 11.12
= 9.46
taking the sign out, we get +1, which is the correct class
4. 2*1.56 + 4*3.17 - 11.12
= 4.68
taking the sign out, we get +1, which is the correct class
5. 6*1.56 + 2*3.17 - 11.12
= 4.58
taking the sign out, we get +1, which is the correct class
So until now, we tested the hyperplane equation on the training data. Now its time to give some never seen before data to the model
Test Data = (3, 5), (-2, 3)
1. 3*1.56 + 5*3.17 - 11.12
= 9.41
Taking the sign out, we get +1, which is the correct class
2. -2*1.56 + 3*3.17 - 11.12
= -4.73
Taking the sign out, we get -1, which is the correct class

Python Implementation of SVM

1. Using Functions

Let us now take a look at how can we implement SVM from scratch. In the following example, we will take dummy data. I have taken the code reference from the repository.
  1. # importing some basic libraries
  2. %matplotlib inline
  3. import matplotlib.pyplot as plt
  4. from matplotlib import style
  5. style.use('ggplot')
  6. import numpy as np
  7. class SVM(object):
  8. def __init__(self,visualization=True):
  9. self.visualization = visualization
  10. self.colors = {1:'r',-1:'b'}
  11. if self.visualization:
  12. self.fig = plt.figure()
  13. self.ax = self.fig.add_subplot(1,1,1)
  14. def fit(self,data):
  15. #train with data
  16. self.data = data
  17. # { |\w\|:{w,b}}
  18. opt_dict = {}
  19. transforms = [[1,1],[-1,1],[-1,-1],[1,-1]]
  20. all_data = np.array([])
  21. for yi in self.data:
  22. all_data = np.append(all_data,self.data[yi])
  23. self.max_feature_value = max(all_data)
  24. self.min_feature_value = min(all_data)
  25. all_data = None
  26. #with smaller steps our margins and db will be more precise
  27. step_sizes = [self.max_feature_value * 0.1,
  28. self.max_feature_value * 0.01,
  29. #point of expense
  30. self.max_feature_value * 0.001,]
  31. #extremly expensise
  32. b_range_multiple = 5
  33. #we dont need to take as small step as w
  34. b_multiple = 5
  35. latest_optimum = self.max_feature_value*10
  36. """
  37. objective is to satisfy yi(x.w)+b>=1 for all training dataset such that ||w|| is minimum
  38. for this we will start with random w, and try to satisfy it with making b bigger and bigger
  39. """
  40. #making step smaller and smaller to get precise value
  41. for step in step_sizes:
  42. w = np.array([latest_optimum,latest_optimum])
  43. #we can do this because convex
  44. optimized = False
  45. while not optimized:
  46. for b in np.arange(-1*self.max_feature_value*b_range_multiple,
  47. self.max_feature_value*b_range_multiple,
  48. step*b_multiple):
  49. for transformation in transforms:
  50. w_t = w*transformation
  51. found_option = True
  52. #weakest link in SVM fundamentally
  53. #SMO attempts to fix this a bit
  54. # ti(xi.w+b) >=1
  55. for i in self.data:
  56. for xi in self.data[i]:
  57. yi=i
  58. if not yi*(np.dot(w_t,xi)+b)>=1:
  59. found_option=False
  60. if found_option:
  61. """
  62. all points in dataset satisfy y(w.x)+b>=1 for this cuurent w_t, b
  63. then put w,b in dict with ||w|| as key
  64. """
  65. opt_dict[np.linalg.norm(w_t)]=[w_t,b]
  66. #after w[0] or w[1]<0 then values of w starts repeating itself because of transformation
  67. #Think about it, it is easy
  68. #print(w,len(opt_dict)) Try printing to understand
  69. if w[0]<0:
  70. optimized=True
  71. print("optimized a step")
  72. else:
  73. w = w-step
  74. # sorting ||w|| to put the smallest ||w|| at poition 0
  75. norms = sorted([n for n in opt_dict])
  76. #optimal values of w,b
  77. opt_choice = opt_dict[norms[0]]
  78. self.w=opt_choice[0]
  79. self.b=opt_choice[1]
  80. #start with new latest_optimum (initial values for w)
  81. latest_optimum = opt_choice[0][0]+step*2
  82. def predict(self,features):
  83. #sign(x.w+b)
  84. classification = np.sign(np.dot(np.array(features),self.w)+self.b)
  85. if classification!=0 and self.visualization:
  86. self.ax.scatter(features[0],features[1],s=200,marker='*',c=self.colors[classification])
  87. return (classification,np.dot(np.array(features),self.w)+self.b)
  88. def visualize(self):
  89. [[self.ax.scatter(x[0],x[1],s=100,c=self.colors[i]) for x in data_dict[i]] for i in data_dict]
  90. # hyperplane = x.w+b (actually its a line)
  91. # v = x0.w0+x1.w1+b -> x1 = (v-w[0].x[0]-b)/w1
  92. #psv = 1 psv line -> x.w+b = 1a small value of b we will increase it later
  93. #nsv = -1 nsv line -> x.w+b = -1
  94. # dec = 0 db line -> x.w+b = 0
  95. def hyperplane(x,w,b,v):
  96. #returns a x2 value on line when given x1
  97. return (-w[0]*x-b+v)/w[1]
  98. hyp_x_min= self.min_feature_value*0.9
  99. hyp_x_max = self.max_feature_value*1.1
  100. # (w.x+b)=1
  101. # positive support vector hyperplane
  102. pav1 = hyperplane(hyp_x_min,self.w,self.b,1)
  103. pav2 = hyperplane(hyp_x_max,self.w,self.b,1)
  104. self.ax.plot([hyp_x_min,hyp_x_max],[pav1,pav2],'k')
  105. # (w.x+b)=-1
  106. # negative support vector hyperplane
  107. nav1 = hyperplane(hyp_x_min,self.w,self.b,-1)
  108. nav2 = hyperplane(hyp_x_max,self.w,self.b,-1)
  109. self.ax.plot([hyp_x_min,hyp_x_max],[nav1,nav2],'k')
  110. # (w.x+b)=0
  111. # db support vector hyperplane
  112. db1 = hyperplane(hyp_x_min,self.w,self.b,0)
  113. db2 = hyperplane(hyp_x_max,self.w,self.b,0)
  114. self.ax.plot([hyp_x_min,hyp_x_max],[db1,db2],'y--')
  115. #defining a basic data
  116. data_dict = {-1:np.array([[1,7],[2,8],[3,8]]),1:np.array([[5,1],[6,-1],[7,3]])}
  117. svm = SVM() # Linear Kernel
  118. svm.fit(data=data_dict)
  119. svm.visualize()
OUTPUT
svm_scratch
  1. svm.predict([3,8])
OUTPUT
(-1.0, -1.000000000000098)

2. Using Sklearn

Let us now take a look at how can we implement SVM using sklearn. In the following example, I have used Social Network data, please find it attached. I have taken the code reference from the repository.
  1. # Importing the libraries
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import pandas as pd
  5. # Importing the datasets
  6. datasets = pd.read_csv('Social_Network_Ads.csv')
  7. X = datasets.iloc[:, [2,3]].values
  8. Y = datasets.iloc[:, 4].values
  9. # Splitting the dataset into the Training set and Test set
  10. from sklearn.model_selection import train_test_split
  11. X_Train, X_Test, Y_Train, Y_Test = train_test_split(X, Y, test_size = 0.25, random_state = 0)
  12. # Feature Scaling
  13. from sklearn.preprocessing import StandardScaler
  14. sc_X = StandardScaler()
  15. X_Train = sc_X.fit_transform(X_Train)
  16. X_Test = sc_X.transform(X_Test)
  17. # Fitting the classifier into the Training set
  18. from sklearn.svm import SVC
  19. classifier = SVC(kernel = 'linear', random_state = 0)
  20. classifier.fit(X_Train, Y_Train)
  21. # Predicting the test set results
  22. Y_Pred = classifier.predict(X_Test)
  23. # Making the Confusion Matrix
  24. from sklearn.metrics import confusion_matrix
  25. cm = confusion_matrix(Y_Test, Y_Pred)
  26. # Visualising the Training set results
  27. from matplotlib.colors import ListedColormap
  28. X_Set, Y_Set = X_Train, Y_Train
  29. X1, X2 = np.meshgrid(np.arange(start = X_Set[:, 0].min() - 1, stop = X_Set[:, 0].max() + 1, step = 0.01),
  30. np.arange(start = X_Set[:, 1].min() - 1, stop = X_Set[:, 1].max() + 1, step = 0.01))
  31. plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
  32. alpha = 0.75, cmap = ListedColormap(('red', 'green')))
  33. plt.xlim(X1.min(), X1.max())
  34. plt.ylim(X2.min(), X2.max())
  35. for i, j in enumerate(np.unique(Y_Set)):
  36. plt.scatter(X_Set[Y_Set == j, 0], X_Set[Y_Set == j, 1],
  37. c = ListedColormap(('red', 'green'))(i), label = j)
  38. plt.title('Support Vector Machine (Training set)')
  39. plt.xlabel('Age')
  40. plt.ylabel('Estimated Salary')
  41. plt.legend()
  42. plt.show()
  43. # Visualising the Test set results
  44. from matplotlib.colors import ListedColormap
  45. X_Set, Y_Set = X_Test, Y_Test
  46. X1, X2 = np.meshgrid(np.arange(start = X_Set[:, 0].min() - 1, stop = X_Set[:, 0].max() + 1, step = 0.01),
  47. np.arange(start = X_Set[:, 1].min() - 1, stop = X_Set[:, 1].max() + 1, step = 0.01))
  48. plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
  49. alpha = 0.75, cmap = ListedColormap(('red', 'green')))
  50. plt.xlim(X1.min(), X1.max())
  51. plt.ylim(X2.min(), X2.max())
  52. for i, j in enumerate(np.unique(Y_Set)):
  53. plt.scatter(X_Set[Y_Set == j, 0], X_Set[Y_Set == j, 1],
  54. c = ListedColormap(('red', 'green'))(i), label = j)
  55. plt.title('Linear Support Vector Machine (Test set)')
  56. plt.xlabel('Age')
  57. plt.ylabel('Estimated Salary')
  58. plt.legend()
  59. plt.show()
  60. from sklearn.svm import SVC
  61. classifier = SVC(kernel = 'rbf', random_state = 0)
  62. classifier.fit(X_Train, Y_Train)
  63. # Predicting the test set results
  64. Y_Pred = classifier.predict(X_Test)
  65. # Making the Confusion Matrix
  66. from sklearn.metrics import confusion_matrix
  67. cm = confusion_matrix(Y_Test, Y_Pred)
  68. # Visualising the Test set results
  69. from matplotlib.colors import ListedColormap
  70. X_Set, Y_Set = X_Test, Y_Test
  71. X1, X2 = np.meshgrid(np.arange(start = X_Set[:, 0].min() - 1, stop = X_Set[:, 0].max() + 1, step = 0.01),
  72. np.arange(start = X_Set[:, 1].min() - 1, stop = X_Set[:, 1].max() + 1, step = 0.01))
  73. plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
  74. alpha = 0.75, cmap = ListedColormap(('red', 'green')))
  75. plt.xlim(X1.min(), X1.max())
  76. plt.ylim(X2.min(), X2.max())
  77. for i, j in enumerate(np.unique(Y_Set)):
  78. plt.scatter(X_Set[Y_Set == j, 0], X_Set[Y_Set == j, 1],
  79. c = ListedColormap(('red', 'green'))(i), label = j)
  80. plt.title('Radial Basis Function (RBF) Support Vector Machine (Test set)')
  81. plt.xlabel('Age')
  82. plt.ylabel('Estimated Salary')
  83. plt.legend()
  84. plt.show()
OUTPUT
svm_input
svm_linear_output
svm_rbf_output

3. Using Tensorflow

Let us now take a look at how can we implement SVM using TensorFlow. In the following example, I am using the IRIS dataset. I have taken the code reference from the repository.
Note: tf.disable_v2_behaviour() is used to use the Tensorflow 1 functionalities, as i have Tensorflow 2 installed on my PC.
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import tensorflow.compat.v1 as tf
  4. tf.disable_v2_behavior()
  5. from sklearn import datasets
  6. from tensorflow.python.framework import ops
  7. ops.reset_default_graph()
  8. # Set random seeds
  9. np.random.seed(7)
  10. tf.set_random_seed(7)
  11. # Create graph
  12. sess = tf.Session()
  13. # Load the data
  14. # iris.data = [(Sepal Length, Sepal Width, Petal Length, Petal Width)]
  15. iris = datasets.load_iris()
  16. x_vals = np.array([[x[0], x[3]] for x in iris.data])
  17. y_vals = np.array([1 if y == 0 else -1 for y in iris.target])
  18. # Split data into train/test sets
  19. train_indices = np.random.choice(len(x_vals),
  20. int(round(len(x_vals)*0.9)),
  21. replace=False)
  22. test_indices = np.array(list(set(range(len(x_vals))) - set(train_indices)))
  23. x_vals_train = x_vals[train_indices]
  24. x_vals_test = x_vals[test_indices]
  25. y_vals_train = y_vals[train_indices]
  26. y_vals_test = y_vals[test_indices]
  27. # Declare batch size
  28. batch_size = 135
  29. # Initialize placeholders
  30. x_data = tf.placeholder(shape=[None, 2], dtype=tf.float32)
  31. y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
  32. # Create variables for linear regression
  33. A = tf.Variable(tf.random_normal(shape=[2, 1]))
  34. b = tf.Variable(tf.random_normal(shape=[1, 1]))
  35. # Declare model operations
  36. model_output = tf.subtract(tf.matmul(x_data, A), b)
  37. # Declare vector L2 'norm' function squared
  38. l2_norm = tf.reduce_sum(tf.square(A))
  39. # Declare loss function
  40. # Loss = max(0, 1-pred*actual) + alpha * L2_norm(A)^2
  41. # L2 regularization parameter, alpha
  42. alpha = tf.constant([0.01])
  43. # Margin term in loss
  44. classification_term = tf.reduce_mean(tf.maximum(0., tf.subtract(1., tf.multiply(model_output, y_target))))
  45. # Put terms together
  46. loss = tf.add(classification_term, tf.multiply(alpha, l2_norm))
  47. # Declare prediction function
  48. prediction = tf.sign(model_output)
  49. accuracy = tf.reduce_mean(tf.cast(tf.equal(prediction, y_target), tf.float32))
  50. # Declare optimizer
  51. my_opt = tf.train.GradientDescentOptimizer(0.01)
  52. train_step = my_opt.minimize(loss)
  53. # Initialize variables
  54. init = tf.global_variables_initializer()
  55. sess.run(init)
  56. # Training loop
  57. loss_vec = []
  58. train_accuracy = []
  59. test_accuracy = []
  60. for i in range(500):
  61. rand_index = np.random.choice(len(x_vals_train), size=batch_size)
  62. rand_x = x_vals_train[rand_index]
  63. rand_y = np.transpose([y_vals_train[rand_index]])
  64. sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
  65. temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})
  66. loss_vec.append(temp_loss)
  67. train_acc_temp = sess.run(accuracy, feed_dict={
  68. x_data: x_vals_train,
  69. y_target: np.transpose([y_vals_train])})
  70. train_accuracy.append(train_acc_temp)
  71. test_acc_temp = sess.run(accuracy, feed_dict={
  72. x_data: x_vals_test,
  73. y_target: np.transpose([y_vals_test])})
  74. test_accuracy.append(test_acc_temp)
  75. if (i + 1) % 100 == 0:
  76. print('Step #{} A = {}, b = {}'.format(
  77. str(i+1),
  78. str(sess.run(A)),
  79. str(sess.run(b))
  80. ))
  81. print('Loss = ' + str(temp_loss))
  82. # Extract coefficients
  83. [[a1], [a2]] = sess.run(A)
  84. [[b]] = sess.run(b)
  85. slope = -a2/a1
  86. y_intercept = b/a1
  87. # Extract x1 and x2 vals
  88. x1_vals = [d[1] for d in x_vals]
  89. # Get best fit line
  90. best_fit = []
  91. for i in x1_vals:
  92. best_fit.append(slope*i+y_intercept)
  93. # Separate I. setosa
  94. setosa_x = [d[1] for i, d in enumerate(x_vals) if y_vals[i] == 1]
  95. setosa_y = [d[0] for i, d in enumerate(x_vals) if y_vals[i] == 1]
  96. not_setosa_x = [d[1] for i, d in enumerate(x_vals) if y_vals[i] == -1]
  97. not_setosa_y = [d[0] for i, d in enumerate(x_vals) if y_vals[i] == -1]
  98. # Plot data and line
  99. plt.plot(setosa_x, setosa_y, 'o', label='I. setosa')
  100. plt.plot(not_setosa_x, not_setosa_y, 'x', label='Non-setosa')
  101. plt.plot(x1_vals, best_fit, 'r-', label='Linear Separator', linewidth=3)
  102. plt.ylim([0, 10])
  103. plt.legend(loc='lower right')
  104. plt.title('Sepal Length vs Petal Width')
  105. plt.xlabel('Petal Width')
  106. plt.ylabel('Sepal Length')
  107. plt.show()
  108. # Plot train/test accuracies
  109. plt.plot(train_accuracy, 'k-', label='Training Accuracy')
  110. plt.plot(test_accuracy, 'r--', label='Test Accuracy')
  111. plt.title('Train and Test Set Accuracies')
  112. plt.xlabel('Generation')
  113. plt.ylabel('Accuracy')
  114. plt.legend(loc='lower right')
  115. plt.show()
  116. # Plot loss over time
  117. plt.plot(loss_vec, 'k-')
  118. plt.title('Loss per Generation')
  119. plt.xlabel('Generation')
  120. plt.ylabel('Loss')
  121. plt.show()
OUTPUT
Step #100 A = [[-0.4810509 ] [ 0.05859518]], b = [[-1.8697345]] Loss = [0.64420575]
Step #200 A = [[-0.4076391 ] [-0.25413615]], b = [[-1.9181045]] Loss = [0.45963168]
Step #300 A = [[-0.34309638] [-0.55148035]], b = [[-1.9694378]] Loss = [0.34777495]
Step #400 A = [[-0.28505743] [-0.83066034]], b = [[-2.023808]] Loss = [0.25850892]
Step #500 A = [[-0.22314341] [-1.096483 ]], b = [[-2.0792139]] Loss = [0.2473848]
tensorflow_input
svm_train_test_tensorflow
svm_loss_tensorflow

Conclusion

In this article, we studied support vector machine, key terms of SVM, types of SVM, types of SVM kernels, advantages and disadvantages of SVM, real-world applications of SVM, SVM explanation using an example, and python implementation of the SVM algorithm using functions, sklearn, and TensorFlow. Hope you were able to understand everything. For any doubts, please comment on your query.
Congratulations!!! You have climbed your next step in becoming a successful ML Engineer.