首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用matplotlib绘制分类值的等高线图

使用matplotlib绘制分类值的等高线图
EN

Stack Overflow用户
提问于 2017-04-04 18:58:47
回答 1查看 1.5K关注 0票数 4

我必须为SVM分类器绘制一张图。这是我用来绘制的代码:

plt.contour(xx, yy, Z)

这里,xxyy是特性,Z是标签。这些标签是字符串形式的。当我运行代码时,我得到以下错误

代码语言:javascript
复制
ValueError: could not convert string to float: dog  

如何绘制此图?

EN

回答 1

Stack Overflow用户

发布于 2017-04-05 00:30:50

因为"dog“不是数值,所以您不能直接绘制它。你需要的是分类值和数值之间的映射,例如使用字典,

代码语言:javascript
复制
an = {"cow":1,"no animal":0,"chicken":2,"cat":3, "fox":4}

使用这个字典,您可以使用contourf或imshow绘制介于0和4之间的数字数组。两者之间的差异可以在下面观察到。Imshow更好地保留了类别,因为它会绘制像素,而不是在像素之间进行插值。由于类别很少被插入(猫和狐狸之间的平均值是什么?),它可能更接近这里所需的内容。

代码语言:javascript
复制
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()

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43205289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档