2017-10-13 130 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索引工作。