use*_*040 5 matplotlib contour
我必须为 SVM 分类器绘制一个图表。这是我用来绘制的代码:
plt.contour(xx, yy, Z)
这里xx
和yy
是功能,Z
是标签。这些标签位于字符串中。当我运行代码时出现错误
ValueError: could not convert string to float: dog
Run Code Online (Sandbox Code Playgroud)
我怎样才能绘制这个图表?
由于“dog”不是数值,因此无法直接绘制它。您需要的是分类值和数值之间的映射,例如使用字典,
an = {"cow":1,"no animal":0,"chicken":2,"cat":3, "fox":4}
Run Code Online (Sandbox Code Playgroud)
使用此字典,您可以使用contourf 或imshow 绘制0 到4 之间的数字数组。两者之间的差异可以从下面观察到。Imshow 更好地保留了类别,因为它绘制像素而不是在它们之间进行插值。由于类别很少可以插值(猫和狐狸之间的意思是什么?),它可能更接近这里所需要的。
import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (6,2.8)
animals = [['no animal', 'no animal', 'no animal', 'chicken', 'chicken'],
['no animal', 'no animal', 'cow', 'no animal', 'chicken'],
['no animal', 'cow', 'cat', 'cat', 'no animal'],
['no animal', 'cow', 'fox', 'cat', 'no animal'],
['cow', 'cow', 'fox', 'chicken', 'no animal'],
['no animal','cow', 'chicken', 'chicken', 'no animal'],
['no animal', 'no animal', 'chicken', 'cat', 'chicken'],
['no animal', 'no animal', 'no animal', 'cat', 'no animal']]
y = np.linspace(-4,4, 8)
x = np.linspace(-3,3, 5)
X,Y = np.meshgrid(x,y)
an = {"cow":1,"no animal":0,"chicken":2,"cat":3, "fox":4}
aninv = { val: key for key, val in an.items() }
f = lambda x: an[x]
fv = np.vectorize(f)
Z = fv(animals)
fig, (ax, ax2) = plt.subplots(ncols=2)
ax.set_title("contourf"); ax2.set_title("imshow")
im = ax.contourf(X,Y,Z, levels=[-0.5,0.5,1.5,2.5,3.5,4.5] )
cbar = fig.colorbar(im, ax=ax)
cbar.set_ticks([0,1,2,3,4])
cbar.set_ticklabels([aninv[t] for t in [0,1,2,3,4]])
im2 = ax2.imshow(Z, extent=[x.min(), x.max(), y.min(), y.max() ], origin="lower" )
cbar2 = fig.colorbar(im2, ax=ax2 )
cbar2.set_ticks([0,1,2,3,4])
cbar2.set_ticklabels([aninv[t] for t in [0,1,2,3,4]])
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2184 次 |
最近记录: |