索引错误:索引 1 超出轴 0 的范围,大小为 1 - NumPy Python

时间:2021-02-13 11:12:07

标签: python arrays numpy for-loop indexing

 for (i,j) in zip(Y_test,Y_pred_test):   
        if np.logical_and((Y_test[i]==1),(Y_pred_test[j]==1)):
            TP += 1                           
        elif np.logical_and((Y_test[i]==1),(Y_pred_test[j] == 0)):
            FN += 1                          
        elif np.logical_and((Y_test[i]==0),(Y_pred_test[j]==1)):
            FP += 1                           
        elif np.logical_and((Y_test[i]==0),(Y_pred_test[j]==0)):
            TN += 1 

Python - NumPy 问题:

我需要帮助。我的代码在这个特定部分不断出现错误。错误指出“IndexError:索引 1 超出轴 0 的范围,大小为 1”
我目前正在撰写如何计算 TP、FP、TN、FN、准确度、精确度、召回率和 F-1 分数。

Y_test 数据包含:

[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1
  1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
  1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]]

Y_pred_test 数据包含:

[[0. 0. 0. 0. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 0. 1. 1. 0. 0. 0. 0. 0. 1. 0. 0.
  1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1.
  1. 0. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
  1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
  1. 1. 1. 1. 1.]]
   

1 个答案:

答案 0 :(得分:0)

由于 Y_testY_pred_test 是二维数组,for 循环中的 i 和 j 都是一维数组。 Y_test[i] 使用 i 中的值作为索引来访问 Y_test 中的行。第 0 行存在,但第 1 行不会导致错误消息。

import numpy as np
Y_test = np.array( [[ 0, 0, 0, 1, 1, 1, 1 ]] ) # Easy to see test data
Y_pred_test = np.array( [[ 0., 1., 1., 0., 0., 1. ]] ) 

for (i,j) in zip(Y_test,Y_pred_test):
     print(i,'\n', j) 

# [0 0 0 1 1 1 1]  # i in the loop 
# [0. 1. 1. 0. 0. 1.]   # j in the loop
相关问题