<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/radial-kernel-support-vector-classifier/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datascienceplus.com/radial-kernel-support-vector-classifier/"> R Programming – DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Support vector machines are a famous and a very strong classification technique which does not uses any sort of probabilistic model like any other classifier but simply generates <b>hyperplanes</b> or simply putting lines ,to separate and classify the data in some feature space into different regions. </p>
<p>Support Vector Classifiers are majorly used for solving a binary classification problems where we only have 2 class labels say \(Y=[−1,1]\) and a bunch of predictors \(X_i\).And what SVM does is that it generates hyperplanes which in simple terms are just straight lines or planes or are non-linear curves,and these lines are used to separate the data or divide the data into 2 categories or more depending on the type of classification problem.</p>
<p>Another important concept in SVM is of <b>maximal margin classifiers</b>.What it means is that amongst a set of separating hyperplanes SVM aims at finding the one which maximizes the margin \(M\).This simply means that we want to maximize the gap or the distance between the 2 classes from the decision boundary(separating plane).This concept of separating data linearly into 2 different classes using a linear separator or a straight linear line is called <b>linear separability</b>.</p>
<p>The term support vectors in SVM are the data points or training examples which are used to define or maximizing the margin.The support vectors are the points which are close to the decision boundary or on the wrong side of the boundary.</p>
<p>But it is often encountered that linear separators and linear decision boundaries fail because of the non linear interactions in the data and the non linear dependence between the features in feature space.</p>
<p>In this tutorial I am going to talk about generating non linear decision boundaries which is able to separate non linear data using radial kernel support vector classifier.<br>
So how do we separate non linear data?</p>
<p>The trick here is by doing <b>feature expansion</b>.So the way we solve this problem is by doing a non linear transformation on the features \(X_i\) and converting them to a higher dimentional space(say 2-D to 3-D space) called a feature space.Now by this transformation we are able to separate non linear data using a non linear decision boundary.<br>
One famous and most general way of adding non linearities in a model to capture non linear interactions is by simply using higher degree terms such as square and cubic polynomial terms.</p>
<p>$$y_i = \beta_0+ \beta_1X_1 + \beta_2X_1^2+ \beta_3X_2 + \beta_4X_2^2 + \beta_5X_2^3…. = 0 $$</p>
<p>Above equation is the equation of the non linear hyperplane which is generated if we use higher degree polynomial<br>
terms to fit to the data to get a non linear decision boundary.<br>
What we are actually doing is that we are fitting a SVM is an <i>enlarged space</i>.We enlarge the space of features by fitting non linear functions in predictors \(X_i\). But the problem with polynomials are that in higher dimention i.e when having lots of predictors it gets wild and generally overfits at higher degrees of polynomial.</p>
<p>Hence there is another elegant way of adding non linearities in SVM is by the use of <b>Kernel trick</b>.</p>
<h3>Kernel function</h3>
<p>Kernel function is a function of form–<br>
$$K(x,y) = (1 + \sum_{j=1}^{p} x_{ij} y_{ij})^d $$ , where d is the degree of polynomial.</p>
<p>Now the type of Kernel function we are going to use here is a <b>Radial kernel</b>.It is of form-<br>
$$K(x,y) = exp(-\gamma \sum_{j=1}^{p}(x_{ij} – y_{ij})^2 )$$ , and \(\gamma\) here is a tuning parameter which accounts for the smoothness of the decision boundary and controls the variance of the model.</p>
<p>If \(\gamma\) is very large then we get quiet fluctuating and wiggly decision boundaries which accounts for high variance and overfitting.<br>
If \(\gamma\) is small,the decision line or boundary is smoother and has low variance.</p>
<h3>Implementation in R</h3>
<p>I will use the ‘e1071’ package to implement Radial SVM in R.</p>
<pre>
require(e1071)
require(ElemStatLearn)#package containing the dataset

#Loading the data
attach(mixture.example) #is just a simulated mixture data with 200 rows and 2 classes
names(mixture.example)
<em>## [1] &quot;x&quot; &quot;y&quot; &quot;xnew&quot; &quot;prob&quot; &quot;marginal&quot; &quot;px1&quot; ## [7] &quot;px2&quot; &quot;means&quot;
</em>
</pre>
<p>The following data is also 2-D , so lets plot it.The 2 different colored points represent the different classes.</p>
<pre>
plot(x,col=y+3)
</pre>
<p><a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/08/download.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/08/download-490x350.png?w=450&ssl=1" alt="" class="wp-image-8018" data-recalc-dims="1"></a></p>
<pre>
#converting data to a data frame
data&lt;-data.frame(y=factor(y),x)
head(data)
<em>## y X1 X2
## 1 0 2.52609297 0.3210504
## 2 0 0.36695447 0.0314621
## 3 0 0.76821908 0.7174862
## 4 0 0.69343568 0.7771940
## 5 0 -0.01983662 0.8672537
## 6 0 2.19654493 -1.0230141
</em>
</pre>
<p>Now let’s fit a Radial kernel using <code>svm()</code> function.</p>
<pre>
Radialsvm=svm(factor(y) ~ .,data=data,kernel=&quot;radial&quot;,cost=5,scale=F)
Radialsvm
<em>## ## Call:
## svm(formula = factor(y) ~ ., data = data, kernel = &quot;radial&quot;, ## cost = 5, scale = F)
## ## ## Parameters:
## SVM-Type: C-classification ## SVM-Kernel: radial ## cost: 5 ## gamma: 0.5 ## ## Number of Support Vectors: 103
</em>
</pre>
<p>The output of the model is a non linear decision boundary and the values of the tuning parameters \(C,\gamma\) and the number of support vectors too.</p>
<p>Let’s generate a Confusion matrix to check the model’s performance.</p>
<pre>
#Confusion matrix to ckeck the accuracy
table(predicted=Radialsvm$fitted,actual=data$y)
<em>## actual
## predicted 0 1
## 0 76 10
## 1 24 90
</em>
</pre>
<p>let’s calculate the mis-classification rate–</p>
<pre>
#misclassification Rate
mean(Radialsvm$fitted!=data$y)*100 #17% wrong predictions
<em>## [1] 17%
</em>
</pre>
<p>Now let’s create a grid and make prediction on those grid values and also generate a plot with the decision boundary.</p>
<pre>
xgrid=expand.grid(X1=px1,X2=px2) #generating grid points

ygrid=predict(Radialsvm,newdata = xgrid) #ygird consisting of predicted Response values

#lets plot the non linear decision boundary
plot(xgrid,col=as.numeric(ygrid),pch=20,cex=0.3)
points(x,col=y+1,pch=19) 
#we can see that the decision boundary is non linear
</pre>
<p><a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/08/download-1.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/08/download-1-490x350.png?w=450&ssl=1" alt="" class="wp-image-8019" data-recalc-dims="1"></a></p>
<p>Now we can also improve the above plot,by actually including the decision boundary using the contour() function.<br>
Now the code below is a little bit confusing , so i urge the readers to use the help documentation of the below used functions-</p>
<pre>
func = predict(Radialsvm,xgrid,decision.values = TRUE)
func=attributes(func)$decision #to pull out all the attributes and use decision attr

#let's again plot the decision boundary 
plot(xgrid,col=as.numeric(ygrid),pch=20,cex=0.3)
points(x,col=y+1,pch=19)
?coutour #to search more on using this function
contour(px1,px2,matrix(func,69,99),level=0,add=TRUE,lwd=3) #adds the non linear decision boundary
contour(px1,px2,matrix(prob,69,99),level=0.5,add=T,col=&quot;blue&quot;,lwd=3)#this is the true decision boundary i.e Bayes decision boundary
legend(&quot;topright&quot;,c(&quot;True Decision Boundary&quot;,&quot;Fitted Decision Boundary&quot;),lwd=3,col=c(&quot;blue&quot;,&quot;black&quot;))
</pre>
<p>Gives output :</p>
<p><a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/08/download-2.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/08/download-2-490x350.png?w=450&ssl=1" alt="" class="wp-image-8021" data-recalc-dims="1"></a></p>
<p>The above plot shows us the tradeoffs between the true bayes decision boundary and the fitted decision boundary generated by the radial kernel by learning from data. Both look quiet similar and seems that SVM has done a good functional approximation of the actual true underlying function.</p>
<h3>Conclusion</h3>
<p>Radial kernel support vector machine is a good approch when the data is not linearly separable.The idea behind generating non linear decision boundaries is that we need to do some non linear transformations on the features X\(_i\) which transforms them to a higher dimentional space.We do this non linear transformation using the Kernel trick.Now the performance of SVM are influenced by the values of the tuning parameters.Now there are 2 Tuning parameters in the SVM i.e the regularization parameter \(C\) and \(\gamma\).We can implement cross validation to find the best values of both these tuning parameters which affect our classifier’s \(C(X)\) performance.Another way of finding the best value for these hyper-parameters are by using certain optimization techniques such as <b>Bayesian Optimization</b>.</p>
<p>Hope you guys liked the article and make sure to like and share it with your peers.<br>
I am sure that it is motivating enough to get you started with generating your own support vector classifier and use it’s amazing power to generate non linear decision boundaries and learn non-linear interactions from data.</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a rel="nofollow" href="https://datascienceplus.com/random-forests-in-r/" title="Permanent Link toRandom Forests in R" target="_blank">Random Forests in R</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/network-analysis-of-game-of-thrones/" title="Permanent Link toNetwork analysis of Game of Thrones" target="_blank">Network analysis of Game of Thrones</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/structural-changes-in-global-warming/" title="Permanent Link toStructural Changes in Global Warming" target="_blank">Structural Changes in Global Warming</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/deep-learning-with-r/" title="Permanent Link toDeep Learning with R" target="_blank">Deep Learning with R</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/unsupervised-learning-and-text-mining-of-emotion-terms-using-r/" title="Permanent Link toUnsupervised Learning and Text Mining of Emotion Terms Using R" target="_blank">Unsupervised Learning and Text Mining of Emotion Terms Using R</a></li>
</ol></strong>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datascienceplus.com/radial-kernel-support-vector-classifier/"> R Programming – DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/vKJtQjFii_Y" height="1"></a></div>