Keras Multi-Label Classification 'to_categorical' Error

旧巷老猫 提交于 2019-12-11 11:48:53

问题


Receiving

IndexError: index 3 is out of bounds for axis 1 with size 3

when trying to create one-hot encoding using Keras to_categorical on output vectors. Y.shape = (178,1). Please help (:

import keras
from keras.models import Sequential
from keras.layers import Dense
import numpy as np

# number of wine classes
classifications = 3

# load dataset
dataset = np.loadtxt('wine.csv', delimiter=",")
X = dataset[:,1:14]
Y = dataset[:,0:1]

# convert output values to one-hot
Y = keras.utils.to_categorical(Y, classifications)

# creating model
model = Sequential()
model.add(Dense(10, input_dim=13, activation='relu'))
model.add(Dense(15, activation='relu'))
model.add(Dense(20, activation='relu'))
model.add(Dense(classifications, activation='softmax'))

# compile and fit model
model.compile(loss="categorical_crossentropy", optimizer="adam", 
metrics=['accuracy'])

model.fit(X, Y, batch_size=10, epochs=10)

回答1:


Well, the problem lies in the fact that wine labels are from range [1, 3] and to_categorical indexes classes from 0. This makes an error when labeling 3 as to_categorical treats this index as an actual 4th class - what is inconsistent with the number of classes you provided. The easiest fix is to enumerate labels to start from 0 by:

Y = Y - 1


来源:https://stackoverflow.com/questions/48397103/keras-multi-label-classification-to-categorical-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!