Keras多标签分类"to_categorical"错误 [英] Keras Multi-Label Classification 'to_categorical' Error

查看:374
本文介绍了Keras多标签分类"to_categorical"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

接收

IndexError:索引3超出了尺寸1为3的轴1的边界

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

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

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)

推荐答案

好吧,问题在于wine标签来自范围[1, 3],而to_categorical则索引了来自0的类.当将3标记为to_categorical将该索引视为实际的第4类时,这会产生错误-这与您提供的类数不一致.最简单的解决方法是枚举标签,以0开头:

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

这篇关于Keras多标签分类"to_categorical"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆