【问题标题】:Plotting a contour plot of categorical values using matplotlib使用 matplotlib 绘制分类值的等高线图
【发布时间】:2017-08-17 23:54:00
【问题描述】:

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

plt.contour(xx, yy, Z)

这里xx 和yy 是特征,Z 是标签。这些标签在字符串中。当我运行代码时,我得到了错误

ValueError: could not convert string to float: dog  

如何绘制此图?

【问题讨论】:

  • 所以 "dog" 应该比 "cat" 和 "cow" 处于更高或更低的等高线水平?由于我认为该问题与 SVM 分类器无关,因此您可以轻松提供该问题的 minimal reproducible example。

标签: matplotlib contour


【解决方案1】:

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

an = {"cow":1,"no animal":0,"chicken":2,"cat":3, "fox":4}

使用此字典,您可以使用 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()

【讨论】:

  • 如果这回答了您的问题,请考虑accepting。如果没有,请随时在问题中提供更多详细信息或更具体地询问。而不是写“谢谢”,你可以只写upvote(一旦你有 15 个声望,投票就会被计算在内)。
  • dx 和 dy 的作用是什么?
  • @bmillare 好吧,发现了,这在此代码中没有任何用途;-) 人们可以使用沿轴的值之间的差异来获取图像的实际范围(即每个值一个像素)。但是我在这里没有使用它,所以我完全忽略了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
  • 2022-01-05
  • 1970-01-01
  • 2023-03-18
  • 2017-07-12
  • 2018-02-27
  • 1970-01-01
相关资源
最近更新 更多