我必须绘制SVM分类器的图。这是我使用的剧情代码:使用matplotlib绘制分类值的等高线图
plt.contour(xx, yy, Z)
这里xx
和yy
是功能和Z
是标签。这些标签是在字符串中。当我运行代码时,出现错误
ValueError: could not convert string to float: dog
如何绘制此图?
我必须绘制SVM分类器的图。这是我使用的剧情代码:使用matplotlib绘制分类值的等高线图
plt.contour(xx, yy, Z)
这里xx
和yy
是功能和Z
是标签。这些标签是在字符串中。当我运行代码时,出现错误
ValueError: could not convert string to float: dog
如何绘制此图?
因为“狗”不是数字值,所以不能直接绘制它。您需要的是分类值与数值之间的映射,例如使用dicitionary,
an = {"cow":1,"no animal":0,"chicken":2,"cat":3, "fox":4}
使用此字典你然后可以使用contourf或imshow绘制数的0和4之间的阵列。两者之间的差异可以在下面看到。 Imshow更好地保留了catergories,因为它绘制了像素而不是在它们之间进行插值。由于类别很少可以插入(猫和狐狸之间的意思是什么?),它可能更接近于这里所需要的。
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()
感谢您的信息,真的有帮助。 – user2434040
所以如果这回答你的问题,考虑[接受](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)它。如果没有,请随时提供问题的更多细节或更具体地询问。您可以[upvote](http://stackoverflow.com/help/privileges/vote-up)(不要写“谢谢”)(只要您有15点声望,就会计算投票数)。 – ImportanceOfBeingErnest
dx和dy的目的是什么? – bmillare
所以要把* “狗” *在比* “猫” *和* “牛” *更高或更低的轮廓的水平?因为我认为这个问题与SVM分类器没有任何关系,所以你可以很容易地提供这个问题的[mcve]。 – ImportanceOfBeingErnest