本文介绍了python中的Matplotlib.colors.ListedColormap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def plot_decision_regions(X, y, classifier, resolution=0.02):
    # setup marker generator and color map
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])
    # plot the decision surface
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
        np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())
    # plot class samples
    for idx, cl in enumerate(np.unique(y)):
    plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],alpha=0.8, 
 c=cmap(idx),marker=markers[idx], label=cl)

我正在从python机器学习中进行机器学习的感知器训练,并找到了这段代码.在函数参数分类器中代表感知器,X是输入特征y是输出向量.我不明白ListedColormap的作用是什么?那meshgrid是做什么的呢?我是熊猫matplotlib库的新手,请向我解释此代码以及我们要在此代码中做什么?

I was going through perceptron training in machine learning from python machine learning and found this code.In function argument classifier represent perceptron and X is input features y is output vector.I Don't understand what does ListedColormap do ?In addition to that what does meshgrid do ? I am newbie to pandas matplotlib library kindly explain me this code and what we want to do in this code?

推荐答案

让我解释一下代码的每一行:

Let me explain every single line of the code:

x2_min,x2_max = X [:, 1] .min()-1,X [:, 1] .max()+ 1

x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1

这部分代码用于在图中创建我们的限制.为了使图形不那么笨拙和清晰,上限增加了1,下限减少了1,这有助于我们的分类模型在情况下不会碰到轴.

this part of the code deals in creating our limits in the graph. To make the graph less clumsy and clear,upper limit is increased by 1 and lower limit is decreased by 1.This helps our classification model not to touch the axes in case.

numpy中的

meshgrid方法使用坐标向量创建坐标矩阵.概括地说,这里形成一个矩形(网格),其长度为x1_max-x1_min,而宽度为x2_max-x2_min.

meshgrid method in numpy creates a co-ordinate matrix using co-ordinate vectors.here, to generalize, a rectangular(mesh) is formed whose length is x1_max-x1_min and breadth is x2_max-x2_min.

np.arange(开始,停止,步进):在此,设置开始和结束,并将分辨率作为步长.如果分辨率大于0.02(可能是2),则绘制的点对人眼是清晰可见的.为了创建一个更加平滑的区域,将分辨率设置为最低限度.

np.arange(start,stop,step): here, starting and endings are set and resolution is taken as step size. if resolution was larger than 0.02 (may be 2), the plotted points are clearly visible to human eye. inorder to create a completely smoother region, resolution is set to minimum necessary.

如果有坐标

(0,-2)(0,0)(0,1)

(0,-2) (0,0) (0,1)

(1,-2)(1,0)(1,1)

(1,-2) (1,0) (1,1)

然后meshgrid方法将其转换为2个3X3矩阵

then meshgrid method converts it to 2 3X3 matrices

xx2 = [-2 -2 -2] [0 0 0] [1 1 1](3X3矩阵)

xx2 = [-2 -2 -2][0 0 0] [1 1 1] (3X3 matrix)

继续下一步,

numpy的

.ravel()方法在此处创建一个展平的一维数组.如上例所示,

.ravel() method of numpy, creates a flattened 1D array here. as in the above example,

xx2.ravel()= [-2 -2 -2 0 0 0 1 1 1]

xx2.ravel() = [-2 -2 -2 0 0 0 1 1 1]

numpy.array()将两个向量连接成单个2 X 9数组:

numpy.array() concatenates both the vectors into a single 2 X 9 array:

这给出了

对于此矩阵,使用.T的

会找到转置.转置完成后,将返回9x2矩阵.其中每一行代表一个坐标对.重塑获得的矩阵.

for this matrix, using .T, transpose is found.when transpose is done, this returns a 9x2 matrix.in which each row represents a co-ordinate pair.this obtained matrix is reshaped.

plt.xlim(xx1.min(),xx1.max())

plt.xlim(xx1.min(), xx1.max())

plt.ylim(xx2.min(),xx2.max())

plt.ylim(xx2.min(), xx2.max())

contourf用于绘制轮廓图.在这里,Z在xx1 x xx2的空间中构成我们的分类器.并分配了地块限制.

contourf is used to plot contour plots. here, Z forms our classifier in the space of xx1 x xx2. and plot limits are assigned.

最后,

plt.scatter(x = X [y == cl,0],y = X [y == cl,1],alpha = 0.8,

plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],alpha=0.8,

c = cmap(idx),marker = markers [idx],label = cl)

c=cmap(idx),marker=markers[idx], label=cl)

在此部分中,绘制了可用的数据点.

in this part, available data points are plotted.

np.unique()返回唯一值的矩阵.如果您的模型有2个输出,即是"或否",则整个数据分为2类.

np.unique() returns a matrix of unique values. if your model has 2 outputs i.e. either yes or no, then whole data is classified into 2 categories.

enumerate()方法返回计数和值.例如:

enumerate() method returns count and value.for example:

对于计数,枚举(元素)中的elem

for count, elem in enumerate(elements)

...打印计数,元素

... print count, elem

...

0 foo

1巴

2巴兹

因此,在上面的代码中,idx对于所有带有"no"的点返回0或对于所有带有"yes"的点返回1.来自

so, in the above code , idx returns 0 for all points with "no" or 1 for all points with "yes".from

在执行循环时,将为属于特定类别的所有数据点分配相同的颜色,并在图表中进行绘制.

when loop is executed, then all data points belonging to a particular category are assigned same color and plotted in the graph.

标签会创建一个条,使我们能够了解特定颜色所指的值.

Label creates a bar which enables us to know what value a particular color refers to.

这是分类器通常可视化的方式.

This is how, classifiers are generally visualized.

这篇关于python中的Matplotlib.colors.ListedColormap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:39