machine-learning - Keras多标签分类 'to_categorical'错误

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

接收

IndexError: index 3 is out of bounds for axis 1 with size 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)

最佳答案

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

Y = Y - 1

关于machine-learning - Keras多标签分类 'to_categorical'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48397103/

相关文章:

machine-learning - Scikit 学习支持向量机的多类分类

r - 代码的并行版本需要更长的时间来运行

python - 在 keras.preprocessing.text 中使用 Tokenizer 时内存不足

algorithm - 通过机器学习检测地址

python - 使用 PyBrain 进行神经网络训练不会收敛

python - 使用 TensorFlow 数据集进行验证集

python - Tensorflow 2 坐标分类器

python - 如何将以下顺序模型转换为keras中的函数模型

python - 预测发生时准确性较差

python - 如何使用神经网络预测峰值(最好在 python 中使用 neurolab 或 pybrain)