代码之家  ›  专栏  ›  技术社区  ›  Adelov

np_utils.to_categorical方法给了我一个错误

  •  0
  • Adelov  · 技术社区  · 7 年前

    np_utils.to_分类Keras方法给它一个包含3个类[1,1,1,…,2,2,2,…3,3,3]的[962]元素向量时,给了我一个错误。

    使用的代码:

    from keras.utils import np_utils
    Y_train = np_utils.to_categorical(testY, 3)
    

    我得到这个错误:

    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    <ipython-input-24-9b7d3117ff6a> in <module>()
          1 print(trainY[720])
    ----> 2 Y_train = np_utils.to_categorical(testY, 3)
          3 print(Y_train[100])
    
    /usr/local/lib/python3.6/dist-packages/keras/utils/np_utils.py in to_categorical(y, num_classes, dtype)
         32     n = y.shape[0]
         33     categorical = np.zeros((n, num_classes), dtype=dtype)
    ---> 34     categorical[np.arange(n), y] = 1
         35     output_shape = input_shape + (num_classes,)
         36     categorical = np.reshape(categorical, output_shape)
    
    IndexError: index 3 is out of bounds for axis 1 with size 3
    
    0 回复  |  直到 7 年前
        1
  •  1
  •   S.Mohsen sh    7 年前

    如中所述 method documentation :

    论据

    y: class vector to be converted into a matrix (integers from 0 to num_classes).
    num_classes: total number of classes.
    

    所以当你通过 num_classes=3 它期望y的元素 {0, 1, 2} . 您只需将数据转换为这种基于零的格式:

    Y_test = np_utils.to_categorical(testY - 1, 3)
    
        2
  •  1
  •   Bitto    6 年前

    请试试这个,对我有用-

    y_train=keras.utils.to_分类(y_train,num_classes,dtype='float32')

    y_test=keras.utils.to_分类(y_test,num_classes,dtype='float32')

    推荐文章