2016-11-23 94 views
3

我寫了下面的代碼:Sklearn預測多路輸出

from sklearn import tree 

# Dataset & labels 
# Using metric units 
# features = [height, weight, style] 
styles = ['modern', 'classic'] 
features = [[1.65, 65, 1], 
      [1.55, 50, 1], 
      [1.76, 64, 0], 
      [1.68, 77, 0] ] 
labels = ['Yellow dress', 'Red dress', 'Blue dress', 'Green dress'] 

# Decision Tree 
clf = tree.DecisionTreeClassifier() 
clf = clf.fit(features, labels) 

# Returns the dress 
height = input('Height: ') 
weight = input('Weight: ') 
style = input('Modern [0] or Classic [1]: ') 
print(clf.predict([[height,weight,style]])) 

此代碼接收用戶的身高和體重,然後返回禮服能更好地滿足她。有沒有辦法返回多個選項?例如,返回兩件或更多禮服。

UPDATE

from sklearn import tree 
import numpy as np 

# Dataset & labels 
# features = [height, weight, style] 
# styles = ['modern', 'classic'] 
features = [[1.65, 65, 1], 
      [1.55, 50, 1], 
      [1.76, 64, 1], 
      [1.72, 68, 0], 
      [1.73, 68, 0], 
      [1.68, 77, 0]] 
labels = ['Yellow dress', 
      'Red dress', 
      'Blue dress', 
      'Green dress', 
      'Purple dress', 
      'Orange dress'] 

# Decision Tree 
clf = tree.DecisionTreeClassifier() 
clf = clf.fit(features, labels) 

# Returns the dress 
height = input('Height: ') 
weight = input('Weight: ') 
style = input('Modern [0] or Classic [1]: ') 

print(clf.predict_proba([[height,weight,style]])) 

如果用戶是1.72米和68千克,我想同時顯示綠色和紫色的衣服。這個例子只是返回100%的綠色禮服。

+0

什麼時候會返回一個以上?你的意思是把它們按照最有可能的順序歸還? – erip

回答

5

是的,你可以。其實你可以做的是,你可以得到每個類的概率。有一個函數.predict_proba()在某些分類器中實現。

請參閱here,sklearn的文檔。

它會返回每個班級的樣本成員資格的概率。

然後,您可以例如返回與兩個,三個最高概率相關聯的標籤。

+0

這種方法只是選擇完全符合條件的選項。例如:如果我的身高是1.72米,體重是68公斤,我想要展示1.73米和68公斤的連衣裙和1.72和68公斤的連衣裙。 – bodruk

2

predict()只返回類概率較高。如果你使用 predict_proba()來代替它,它會返回一個數組,每個類的概率爲,所以你可以選擇超過某個閾值的數組。

Here是該方法的文檔。

你可以做這樣的事情吧:

probs = clf.predict_proba([[height, weight, style]]) 
threshold = 0.25 # change this accordingly 
for index, prob in enumerate(probs[0]): 
    if prob > threshold: 
     print(styles[index]) 
+1

你的門檻不是很好選擇。如果'threshold = 0.5',它將只返回一個標籤。概率總和等於1,沒有其他標籤可能有大於0.5的概率... – MMF

+1

是的,你是對的。我只是選擇了一個隨機數字而沒有進一步考慮它。 –