首页 文章

Keras多标签分类'to_categorical'错误

提问于
浏览
1

接收

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 回答

  • 1

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

    Y = Y - 1
    

相关问题