簡體   English   中英

最近質心的決策邊界

[英]Decision boundaries for nearest centroid

我試圖為不同的分類器繪制決策邊界,包括nearestcentroid ,但是當我使用這個代碼時

if hasattr(clf, "decision_function"):
            Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
        else:
            Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]

我收到一條錯誤,說'NearestCentroid'對象沒有屬性'predict_proba' 我怎樣才能解決這個問題?

假設您的X有兩個特征,您可以生成一個meshgrid ,其中每個軸都與其中一個特征相關。

假設X是具有兩個特征的特征數組 - 形狀將是(N,2),其中N是樣本數 - 並且y是您的目標數組:

# first determine the min and max boundaries for generating the meshgrid
feat1_min, feat1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
feat2_min, feat2_max = X[:, 1].min() - 1, X[:, 1].max() + 1

現在生成meshgrid並沿網格進行預測:

xx, yy = np.meshgrid(np.arange(feat1_min, feat1_max , 0.02),
                     np.arange(feat2_min, feat2_max , 0.02))  # 0.02 is step size
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

現在制作情節:

Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap="autumn")
plt.scatter(X[:, 0], X[:, 1], c=y, cmap="autumn",
            edgecolor='k', s=10)
plt.show()

正如BearBrown指出的那樣,你只檢查“decison_function”是否是clf的一個屬性。 你永遠不會檢查“predict_proba”是否是clf的一個屬性

if hasattr(clf, "decision_function"):
    Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
elif hasattr(clf, "predict_proba"): # This condition ensures that you'll see that predict_proba is not an attribute of clf`enter code here`
    Z = clf.predict_proba(numpy.c_[xx.ravel(), yy.ravel()])[:, 1]
else: #This will show you your error again
    raise AttributeError("Neither 'decision_function' not 'predict_proba' found in clf")

在此之后,你應該檢查為什么你期望的不是clf的歸因

你可以制作自己的predict_proba

from sklearn.utils.extmath import softmax
from sklearn.metrics.pairwise import pairwise_distances

def predict_proba(self, X):
    distances = pairwise_distances(X, self.centroids_, metric=self.metric)
    probs = softmax(distances)
    return probs

clf = NearestCentroid()
clf.predict_proba = predict_proba.__get__(clf)
clf.fit(X_train, y_train)
clf.predict_proba(X_test)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM