如何建立神经网络模型以在python中对数据进行分类

时间:2020-09-02 04:48:56

标签: python tensorflow machine-learning keras neural-network

我正在尝试建立一个模型来对一些数据进行分类(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).

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:-1)

实际上,如果您将使用train_test_split从同一帧中拆分数据,则应该不会出现此错误。请再次检查数据。另外,请确保在stratify中使用train_test_split选项。