【问题标题】:TypeError for predict_proba(np.array(test))predict_proba 的类型错误(np.array(测试))
【发布时间】:2018-03-25 17:10:48
【问题描述】:
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 中,可以打印为:

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)。 这个怎么办?

【问题讨论】:

  • 以后请添加一些可重现的代码。

标签: python python-3.x numpy scikit-learn typeerror


【解决方案1】:

我想出了另一个解决方案:

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 访问 test_prediction 中的索引来实现

但@Vivek_Kumar 指定的解决方案似乎更正确和有效。

【讨论】:

    【解决方案2】:

    您也可以使用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')
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      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))
      

      然后你可以连接它们:

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

      这样您就不需要使用导致错误的 for 循环。

      【讨论】:

      • 在实际程序中我的浮点值没有工作 TypeError: 'numpy.float64' object is not callable
      【解决方案4】:

      range中使用数组的问题

      在这种情况下,您应该使用数组长度range(len(test_prediction))

      你也可以简化你的代码:

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

      enumerate 将数组转换为元组列表(索引、项)

      key=operator.itemgetter(1) - max 函数将按第二个值比较类型

      【讨论】:

      • 在实际程序 TypeError 中我的浮点值不起作用:(“'numpy.float64' 对象不可调用”,'发生在索引 0')
      猜你喜欢
      • 2013-11-26
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 2019-02-07
      • 2016-04-06
      • 1970-01-01
      相关资源
      最近更新 更多