0
votes

I made a SVM plot from the Iris-dataset by using matplotlib and mlxtend in Jupyter notebook. I am trying to get the Species name on the legend of the plot instead of 0, 1 and 2. So far my code is :

from sklearn import svm
from mlxtend.plotting import plot_decision_regions

X = iris[['SepalLengthCm', 'SepalWidthCm']]
y = iris['SpecieID']

clf = svm.SVC(decision_function_shape = 'ovo')
clf.fit(X.values, y.values) 

# Plot Decision Region using mlxtend's awesome plotting function
plot_decision_regions(X=X.values, 
                      y=y.values,
                      clf=clf, 
                      legend=2)

# Update plot object with X/Y axis labels and Figure Title
plt.xlabel(X.columns[0], size=14)
plt.ylabel(X.columns[1], size=14)
plt.title('SVM Decision Region Boundary', size=16)

And results in this plot : enter image description here

I couldn't find how to replace 0,1 and 2 by the species names (Iris-setosa, Iris-versicolor and Iris-virginica).

I created the pandas DataFrame by :

import pandas as pd
iris = pd.read_csv("Iris.csv") # the iris dataset is now a Pandas DataFrame
iris = iris.assign(SepalRatio = iris['SepalLengthCm'] / iris['SepalWidthCm']).assign(PetalRatio = iris['PetalLengthCm'] / iris['PetalWidthCm']).assign(SepalMultiplied = iris['SepalLengthCm'] * iris['SepalWidthCm']).assign(PetalMultiplied = iris['PetalLengthCm'] * iris['PetalWidthCm'])
d = {"Iris-setosa" : 0, "Iris-versicolor": 1, "Iris-virginica": 2}
iris['SpecieID'] = iris['Species'].map(d).fillna(-1)
3

3 Answers

2
votes
plot_decision_regions(X=X, 
                      y=y,
                      clf=clf, 
                      legend=2)

plt.title('SVM Decision Region Boundary', size=16)
L = plt.legend()
L.get_texts()[0].set_text('A')
L.get_texts()[1].set_text('B')
L.get_texts()[2].set_text('C')

enter image description here

2
votes

Another one with the help of handles and labels of current plot axes i.e

handles, labels =  plt.gca().get_legend_handles_labels()
plt.legend(handles, list(map(d.get, [int(i) for i in labels])) , loc= 'upper left') #Map the values of current labels with dictionary and pass it as labels parameter. 
plt.show()

Sample output :

enter image description here

0
votes

Following the @Dark answer, here's a complete code along with the highlighted support vectors.

from mlxtend.plotting import plot_decision_regions
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.svm import SVC

# Loading some example data
iris = datasets.load_iris()
X = iris.data[:, [0, 2]]
y = iris.target

# In case if the original data categories name were present 
# then we replace them with numbers
d = {"Iris-setosa" : 0, "Iris-versicolor": 1, "Iris-virginica": 2} 

# Training a classifier
svm = SVC(C=0.5, kernel='linear')
svm.fit(X, y)


# Plotting decision regions
plt.figure(figsize=(8,6))
plot_decision_regions(X, y, clf=svm, legend=2, X_highlight=svm.support_vectors_)

# Adding legend 
handles, labels =  plt.gca().get_legend_handles_labels()
d_rev = {y:x for x,y in d.items()} # switching key-value pairs
plt.legend(handles, list(map(d_rev.get, [int(i) for i in d_rev])))

# Adding axes annotations
plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.title('SVM on Iris')
plt.show()

SVM decision boundaries in MLXTEND