2017-04-04 8 views
2

SVM分類子のグラフをプロットする必要があります。matplotlibを使用してカテゴリ値の等高線図をプロットする

plt.contour(xx, yy, Z)

ここxxyyが機能しているとZがラベルである:これは私がプロットに使用していたコードです。これらのラベルは文字列内にあります。コードを実行するとエラーが発生します

ValueError: could not convert string to float: dog 

このグラフをプロットするにはどうすればよいですか?

+0

だから、* "犬" * * "猫" *と* "牛" *より高いか低い輪郭レベルですべきですか?問題はSVM分類子とは関係がないので、簡単に問題の[mcve]を提供できます。 – ImportanceOfBeingErnest

答えて

2

"dog"は数値ではないので、直接描画することはできません。あなたが必要とするのは、カテゴリ値と数値の間のマッピングです。この辞書を使ってdicitionary、

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() 

enter image description here

+0

情報をありがとう、本当に役立ちます。 – user2434040

+0

これであなたの質問に答えるなら、[accepting](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)と考えてください。そうでない場合は、質問に詳細を記入するか、具体的に質問してください。 「ありがとう」と書くのではなく、評判が15になると投票がカウントされます(アップ投票してください)。 – ImportanceOfBeingErnest

+0

dxとdyの目的は何ですか? – bmillare

関連する問題