2017-04-04 3 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)을 고려하십시오. 그렇지 않은 경우 질문에 대한 자세한 내용을 제공하거나보다 구체적으로 질문하십시오. "고맙다"라고 쓰지 말고 그냥 명성을 ​​얻으면 투표는 계산 될 것입니다. (http://stackoverflow.com/help/privileges/vote-up) – ImportanceOfBeingErnest

+0

dx와 dy의 목적은 무엇입니까? – bmillare