gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:07:26 27 4
gpt4 key购买 nike

接收

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/

27 4 0