将图例名称添加到matplotlib中的SVM图中

时间:2017-09-13 10:21:47

标签: python pandas matplotlib jupyter-notebook

我通过在Jupyter笔记本中使用matplotlib和mlxtend从Iris数据集创建了一个SVM图。我试图在图的图例上获得Species名称,而不是0,1和2.到目前为止,我的代码是:

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)

并在此图中得出结果:enter image description here

我找不到如何用物种名称(Iris-setosa,Iris-versicolor和Iris-virginica)替换0,1和2。

我通过以下方式创建了pandas DataFrame:

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 个答案:

答案 0 :(得分:2)

function customerMailCheck(){
            $mail = $this->input->post('email');
            $result = $this->db->get_where('privilege_customer', array('email' => $mail));
            return $result->result();
}

enter image description here

答案 1 :(得分:2)

另一个借助于当前绘图轴的手柄和标签,即

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()

示例输出:

enter image description here

答案 2 :(得分:0)

在@Dark答案之后,这是完整的代码以及突出显示的支持向量。

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