2017-10-13 175 views
1
model = LogisticRegression() 
model = model.fit(X, y) 
test_data = [1,2,3,4,5,6,7,8,9,10,11,12,13] 
test_prediction = model.predict_proba(np.array(test_data)) 
max = -1.0 
res = 0 
for i in range(test_prediction): 
    if test_prediction[i]>max: 
     max = test_prediction[i] 
     res = i 
if res==0: 
    print('A') 
elif res==1: 
    print('B') 
else: 
    print('C') 

使用上面的python代碼,我必須預測3個可能的結果(A,B,C)的概率。 的概率保存在test_prediction,它可以打印爲:TypeError for predict_proba(np.array(test))

Output: [[ 0.82882588 0.08641236 0.08476175]] 

但剩下的部分給出了一個錯誤:

for i in range(test_prediction): 
TypeError: only integer scalar arrays can be converted to a scalar index 

我想找到的最大概率,然後顯示作爲事件可能發生的最多(A/B/C)。 如何解決這個問題?

+0

將來請添加一些可重現的代碼。 –

回答

1

您也可以使用numpy.argmax這將直接爲您提供最大值的索引。

import numpy as np 

#test_prediction is most probably np array only 
pred = np.array(test_prediction) 

classes_val = np.argmax(pred, axis=1) 
for res in class_val: 
    if res==0: 
     print('A') 
    elif res==1: 
     print('B') 
    else: 
    print('C') 
+0

謝謝你解決了我的問題 – Enzy

0

你可以做這樣的事情:

predict_prob_df = pd.DataFrame(model.predict_proba(test_data)) 
max_prob = predict_prob_df.apply(max,axis = 1) 
predicted_output = pd.DataFrame(model.predict(test_data)) 

然後你可以Concat的他們:

final_frame = pd.concat([max_prob,predicted_output],axis = 1) 

這樣,您就不必使用for循環,這是造成錯誤。

+0

在實際程序中沒有工作我的浮點值的因爲 TypeError:'numpy.float64'對象不可調用 – Enzy

0

range(len(test_prediction))

你也可以簡化你的代碼在range

使用數組在這種情況下,你應該使用數組的長度問題:

import operator 
#... 
enum_predict = enumerate(test_prediction) 
res = max(enum_predict, key=operator.itemgetter(1))[0] 

enumerate轉換陣元組的列表(index,item)

key=operator.itemgetter(1) - max函數將比較seco的類型nd值

+0

在實際程序中沒有工作我的浮點值的因爲 TypeError :(「'numpy.float64'對象是不可調用「,'發生在索引0') – Enzy

0

我想出了另一種解決方案:

for i in range(3): 
    if np.take(test_prediction, i) > max: 
     max = np.take(test_prediction, i) 
     res = i 
if res==0: 
..... 

這通過使用np.take

但通過@Vivek_Kumar指定的解決方案似乎更正確,更高效的訪問中test_prediction索引工作。

相關問題