【问题标题】:Keras Multi-Label Classification 'to_categorical' ErrorKeras 多标签分类“to_categorical”错误
【发布时间】:2018-07-02 00:00:33
【问题描述】:

接收

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

尝试在输出向量上使用 Keras to_categorical 创建 one-hot 编码时。 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)

【问题讨论】:

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


    【解决方案1】:

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

    Y = Y - 1
    

    【讨论】:

    • 谢谢。这解决了它,但是我的网络准确性在训练时并没有在测试集上提高。知道为什么吗?
    • 嗯 - 有很多可能的原因。我会尝试从使网络向输入更窄而不是变得更宽。
    • 高达 98%,添加了另外几个隐藏层并缩小了网络。再次感谢。
    • @JohnFisher 因为答案解决了您的问题,请接受它(答案会占用受访者的宝贵时间) - 请参阅What should I do when someone answers my question?
    • @MarcinMożejko 我知道你早就回答了这个问题,但我有一个类似的问题:我的标签是 [1, 2, 3, 4, 6, 7, 9, 10] (只是一个例子,我有 25 个类)我应该怎么做才能使标签适合 to_categorical?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2018-08-04
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 2019-01-06
    相关资源
    最近更新 更多