Keras多标签分类'to_categorical'错误

时间:2018-01-23 08:23:17

标签: machine-learning neural-network keras multilabel-classification

接收

  

IndexError:索引3超出了轴1的大小为3的范围

尝试在输出向量上使用Keras to_categorical创建单热编码时。 Y.shape = (178,1)。请帮忙(:

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 个答案:

答案 0 :(得分:1)

嗯,问题在于wine标签来自[1, 3]的范围to_categorical0索引类。标记3时会出现错误,因为to_categorical将此索引视为实际的第4类 - 与您提供的类数不一致。最简单的解决方法是枚举从0开始的标签:

Y = Y - 1