为什么在使用sparse_categorical_crossentrpy时仍会收到“接收到的标签值6超出有效范围[0,1)”的消息?

时间:2019-07-12 18:59:21

标签: python tensorflow keras deep-learning classification

因此,我正在尝试使用7个面部表情来进行情感分类。我知道,要使用整数标签而不是0和1,需要使用sparse_categorical_crossentropy,并需要将外层激活作为softmax进行,但无法正常工作。

我正在使用https://www.kaggle.com/ashishpatel26/facial-expression-recognitionferchallenge此处的数据集

CODE

import pandas as pd
import numpy as np
from PIL import Image
import random
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.optimizers import RMSprop
from keras.layers import Conv1D, MaxPooling1D
from keras.layers import Activation, Dropout, Flatten, Dense

emotion = {0 : 'Angry', 1 : 'Disgust',2 : 'Fear',3 : 'Happy',
           4 : 'Sad',5 : 'Surprise',6 : 'Neutral'}
df=pd.read_csv('fer.csv')
faces=df.values[0:500,1]
faces=faces.tolist()
emos=df.values[0:500,0]

for i in range(len(faces)):
    faces[i]=[int(x) for x in faces[i].split()]
    emos[i]=int(emos[i])

faces=np.array(faces)
faces=np.expand_dims(faces, axis=2)

model = Sequential()

model.add(Conv1D(16, 3, padding='same', input_shape=(2304,1), activation='relu'))
model.add(Conv1D(16, 3, padding='same', activation='relu'))
model.add(MaxPooling1D(pool_size=2))

model.add(Conv1D(32, 3, padding='same', activation='relu'))
model.add(Conv1D(32, 3, padding='same', activation='relu'))
model.add(MaxPooling1D(pool_size=2))

model.add(Conv1D(64, 3, padding='same', activation='relu'))
model.add(Conv1D(64, 3, padding='same', activation='relu'))
model.add(MaxPooling1D(pool_size=2))

model.add(Conv1D(128, 3, padding='same', activation='relu'))
model.add(Conv1D(256, 3, padding='same', activation='relu'))
model.add(MaxPooling1D(pool_size=2))

model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(1, activation='softmax'))

model.compile(loss='sparse_categorical_crossentropy',
            optimizer='adam',
            metrics=['accuracy'])

model.fit(faces,emos,epochs=10,batch_size=8)
model.save_weights('model.h5')

错误

W tensorflow/core/framework/op_kernel.cc:1401] OP_REQUIRES failed at sparse_xent_op.cc:90 : Invalid argument: Received a label value of 6 which is outside the valid range of [0, 1).  Label values: 6 0 2 4 6 0 0 3
Traceback (most recent call last):
  File "FEClassifier.py", line 56, in <module>
    model.fit(faces,emos,epochs=10,batch_size=8)
  File "C:\Users\nrj10\Anaconda3\lib\site-packages\keras\engine\training.py", line 1039, in fit
    validation_steps=validation_steps)
  File "C:\Users\nrj10\Anaconda3\lib\site-packages\keras\engine\training_arrays.py", line 199, in fit_loop
    outs = f(ins_batch)
  File "C:\Users\nrj10\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 2715, in __call__
    return self._call(inputs)
  File "C:\Users\nrj10\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 2675, in _call
    fetched = self._callable_fn(*array_vals)
  File "C:\Users\nrj10\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 1439, in __call__
    run_metadata_ptr)
  File "C:\Users\nrj10\Anaconda3\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 528, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Received a label value of 6 which is outside the valid range of [0, 1).  Label values: 6 0 2 4 6 0 0 3
         [[{{node loss/dense_3_loss/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]]

2 个答案:

答案 0 :(得分:1)

如果您有N个类别(N> 2),则无论您是否使用稀疏标签,最后一层都需要N个神经元:

model.add(Dense(7, activation='softmax'))

别忘了稀疏标签只是为了方便起见,您的模型仍然需要为每个类生成分数

答案 1 :(得分:0)

最后一层应该有类或类别的数量。

在这种情况下,因为有 7 个类

emotion = {0 : 'Angry', 1 : 'Disgust',2 : 'Fear',3 : 'Happy',
       4 : 'Sad',5 : 'Surprise',6 : 'Neutral'}

最后一层应该改变

model.add(Dense(1, activation='softmax'))

到这里

model.add(Dense(7, activation='softmax'))