InvalidArgumentError: Can not squeeze dim[2], expected a dimension of 1, got 10

864 views Asked by At

I am doing Covid19 facemask detection project and when I train my image dataset I find a error which I can't understand. So, please help me to solve this problem. the error is given below.

Epoch 1/20
Traceback (most recent call last):
  File "Mask_detection.py", line 108, in <module>
    epochs=Epoch)
  File "C:\Users\ABDEALIVORA\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 108, in _method_wrapper
    return method(self, *args, **kwargs)
  File "C:\Users\ABDEALIVORA\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1098, in fit
    tmp_logs = train_function(iterator)
  File "C:\Users\ABDEALIVORA\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 780, in __call__
    result = self._call(*args, **kwds)
  File "C:\Users\ABDEALIVORA\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\def_function.py", line 840, in _call
    return self._stateless_fn(*args, **kwds)
  File "C:\Users\ABDEALIVORA\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 2829, in __call__
    return graph_function._filtered_call(args, kwargs)  # pylint: disable=protected-access
  File "C:\Users\ABDEALIVORA\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 1848, in _filtered_call
    cancellation_manager=cancellation_manager)
  File "C:\Users\ABDEALIVORA\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 1924, in _call_flat
    ctx, args, cancellation_manager=cancellation_manager))
  File "C:\Users\ABDEALIVORA\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\function.py", line 550, in call
    ctx=ctx)
  File "C:\Users\ABDEALIVORA\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\eager\execute.py", line 60, in quick_execute
    inputs, attrs, num_outputs)
tensorflow.python.framework.errors_impl.InvalidArgumentError:  Can not squeeze dim[2], expected a dimension of 1, got 10
         [[node categorical_crossentropy/remove_squeezable_dimensions/Squeeze (defined at Mask_detection.py:108) ]] [Op:__inference_train_function_889]

Function call stack:
train_function

2020-09-28 12:37:31.761507: W tensorflow/core/kernels/data/generator_dataset_op.cc:103] Error occurred when finalizing GeneratorDataset iterator: Failed precondition: Python interpreter s
tate is not initialized. The process may be terminated.
         [[{{node PyFunc}}]]

I provide my python code that helps you to understand the problem. My system is without GPU so this error is related with GPU.

DIRECTORY = 'images'
Categories = ["With_mask","Without_mask"]
batch_size= 10
num_class = 10
Epoch= 20
data = []
label =[]
for category in Categories:
    path = os.path.join(DIRECTORY,category)
    for img in os.listdir(path):
        img_path = os.path.join(path,img)
        image = load_img(img_path,target_size =(64,64))
        image = img_to_array(image)
        image = preprocess_input(image)
        data.append(image)
        label.append(category)

lb = LabelBinarizer()
label = lb.fit_transform(label)
label = to_categorical(label)
data =  numpy.asarray(data,dtype = 'float32')
label = numpy.array(label)
print("////")
x_train,x_test,y_train,y_test = train_test_split(data,label,stratify=label,test_size=0.2,random_state=3)
y_train = utils.to_categorical(y_train, num_class)
y_test = utils.to_categorical(y_test, num_class)
mask_model = Sequential()
mask_model.add(Conv2D(32,kernel_size=(3,3),activation= 'linear',padding ="same",input_shape=(64,64,3)))
mask_model.add(LeakyReLU(alpha = 0.3))
mask_model.add(Conv2D(32,kernel_size=(3,3),activation= 'linear',padding ="same",input_shape=(64,64,3)))
mask_model.add(LeakyReLU(alpha=0.3))
mask_model.add(MaxPooling2D(pool_size =(2,2)))
mask_model.add(Conv2D(32,kernel_size=(3,3),activation= 'linear',padding ="same",input_shape=(64,64,3)))
mask_model.add(LeakyReLU(alpha=0.3))
mask_model.add(MaxPooling2D(pool_size =(2,2)))
mask_model.add(Flatten())
mask_model.add(Dense(128,activation = "linear"))
mask_model.add(LeakyReLU(alpha=0.3))
mask_model.add(Dense(10,activation= "softmax"))
mask_model.compile(optimizer ='adam',loss = 'categorical_crossentropy',metrics =['accuracy'] )
mask_model.summary()
datagen = ImageDataGenerator(
    featurewise_center=True,
    featurewise_std_normalization=True,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True)
datagen.fit(x_train)
mask_model.fit(datagen.flow(x_train,y_train,batch_size=10),
               steps_per_epoch=len(x_train),
               validation_data=(x_test, y_test),
               validation_steps=len(x_test) // batch_size,
               workers=0,
               epochs=Epoch)
print("//")
for e in range(Epoch):
    print('Epoch', e)
    batches = 0
    for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=32):
        mask_model.fit(x_batch, y_batch)
        batches += 1
        if batches >= len(x_train) / 32:
            break
mask_model.save("Mask_model/mask_model.h5")
0

There are 0 answers