首页 > 解决方案 > 如何构建神经网络模型以在 python 中对数据进行分类

问题描述

我正在尝试建立一个模型来分类一些数据(4个类)。
这是我尝试过的:

from keras.models import Sequential
from keras.layers import Dense


# dividing X, y into train and test data
X_train, X_test, y_train, y_test = train_test_split(X_data, y_target, random_state=0)

# define the keras model
model = Sequential()
model.add(Dense(64, input_dim=9, activation='relu'))
model.add(Dense(4, activation='softmax')) 
# compile model
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# fit the model on the dataset
train_history = model.fit(X_train, y_train, epochs=100, batch_size=20, verbose=0, validation_data=(X_test, y_test))
# evaluate the keras model
_, accuracy = model.evaluate(X_data, y_target, verbose=0)
print('Accuracy: %.3f' % (accuracy*100))

我收到此错误:

Received a label value of 4 which is outside the valid range of [0, 4).

有人可以帮我理解我的模型有什么问题吗?

标签: pythontensorflowmachine-learningkerasneural-network

解决方案


感谢@furas,我通过将标签从熊猫更改[1 2 3 4]为解决了我的问题:[0 1 2 3]df["label"] = df["label"] - 1


推荐阅读