Driver Drowsiness Detection System with OpenCV & Keras

Free Machine Learning courses with 130+ real-time projects Start Now!!

With this Python project, we will be making a drowsiness detection system. A countless number of people drive on the highway day and night. Taxi drivers, bus drivers, truck drivers and people traveling long-distance suffer from lack of sleep. Due to which it becomes very dangerous to drive when feeling sleepy.

The majority of accidents happen due to the drowsiness of the driver. So, to prevent these accidents we will build a system using Python, OpenCV, and Keras which will alert the driver when he feels sleepy.

DataFlair has also published other machine learning project ideas with source code. You can check them from this ml projects list:

  1. Fake News Detection Python Project
  2. Parkinson’s Disease Detection Python Project
  3. Color Detection Python Project
  4. Speech Emotion Recognition Python Project
  5. Breast Cancer Classification Python Project
  6. Age and Gender Detection Python Project
  7. Handwritten Digit Recognition Python Project
  8. Chatbot Python Project
  9. Drowsy Driver Safety Alert System Python Project
  10. Traffic Signs Recognition Python Project
  11. Image Caption Generator Python Project

Drowsy Driver Alert System

Intermediate Python Project - Driver Drowsiness Detection System

Drowsiness detection is a safety technology that can prevent accidents that are caused by drivers who fell asleep while driving.

The objective of this intermediate Python project is to build a drowsiness detection system that will detect that a person’s eyes are closed for a few seconds. This system will alert the driver when drowsiness is detected.

Driver Drowsiness Detection System

In this Python project, we will be using OpenCV for gathering the images from webcam and feed them into a Deep Learning model which will classify whether the person’s eyes are ‘Open’ or ‘Closed’. The approach we will be using for this Python project is as follows :

Step 1 – Take image as input from a camera.

Step 2 – Detect the face in the image and create a Region of Interest (ROI).

Step 3 – Detect the eyes from ROI and feed it to the classifier.

Step 4 – Classifier will categorize whether eyes are open or closed.

Step 5 – Calculate score to check whether the person is drowsy.

Driver Drowsiness Detection Dataset

The dataset used for this model is created by us. To create the dataset, we wrote a script that captures eyes from a camera and stores in our local disk. We separated them into their respective labels ‘Open’ or ‘Closed’. The data was manually cleaned by removing the unwanted images which were not necessary for building the model. The data comprises around 7000 images of people’s eyes under different lighting conditions. After training the model on our dataset, we have attached the final weights and model architecture file “models/cnnCat2.h5”.

Now, you can use this model to classify if a person’s eye is open or closed.

Alternatively, if you want to build and train your own model, you can download the dataset: Driver Drowsiness Dataset

The Model Architecture

The model we used is built with Keras using Convolutional Neural Networks (CNN). A convolutional neural network is a special type of deep neural network which performs extremely well for image classification purposes. A CNN basically consists of an input layer, an output layer and a hidden layer which can have multiple layers. A convolution operation is performed on these layers using a filter that performs 2D matrix multiplication on the layer and filter.

The CNN model architecture consists of the following layers:

  • Convolutional layer; 32 nodes, kernel size 3
  • Convolutional layer; 32 nodes, kernel size 3
  • Convolutional layer; 64 nodes, kernel size 3
  • Fully connected layer; 128 nodes

The final layer is also a fully connected layer with 2 nodes. A Relu activation function is used in all the layers except the output layer in which we used Softmax.

Project Prerequisites

The requirement for this Python project is a webcam through which we will capture images. You need to have Python (3.6 version recommended) installed on your system, then using pip, you can install the necessary packages.

  1. OpenCV – pip install opencv-python (face and eye detection).
  2. TensorFlow – pip install tensorflow (keras uses TensorFlow as backend).
  3. Keras – pip install keras (to build our classification model).
  4. Pygame – pip install pygame (to play alarm sound).

Steps for Performing Driver Drowsiness Detection

Download the driver drowsiness detection system project source code from the zip and extract the files in your system: Driver Drowsiness Project Code

The contents of the zip are:

Project File Structure - Intermediate Python Project

  • The “haar cascade files” folder consists of the xml files that are needed to detect objects from the image. In our case, we are detecting the face and eyes of the person.
  • The models folder contains our model file “cnnCat2.h5” which was trained on convolutional neural networks.
  • We have an audio clip “alarm.wav” which is played when the person is feeling drowsy.
  • “Model.py” file contains the program through which we built our classification model by training on our dataset. You could see the implementation of convolutional neural network in this file.
  • “Drowsiness detection.py” is the main file of our project. To start the detection procedure, we have to run this file.

Let’s now understand how our algorithm works step by step.

Step 1 – Take Image as Input from a Camera

With a webcam, we will take images as input. So to access the webcam, we made an infinite loop that will capture each frame. We use the method provided by OpenCV, cv2.VideoCapture(0) to access the camera and set the capture object (cap). cap.read() will read each frame and we store the image in a frame variable.

Step 2 – Detect Face in the Image and Create a Region of Interest (ROI)

To detect the face in the image, we need to first convert the image into grayscale as the OpenCV algorithm for object detection takes gray images in the input. We don’t need color information to detect the objects. We will be using haar cascade classifier to detect faces. This line is used to set our classifier face = cv2.CascadeClassifier(‘ path to our haar cascade xml file’). Then we perform the detection using faces = face.detectMultiScale(gray). It returns an array of detections with x,y coordinates, and height, the width of the boundary box of the object. Now we can iterate over the faces and draw boundary boxes for each face.

for (x,y,w,h) in faces: 
        cv2.rectangle(frame, (x,y), (x+w, y+h), (100,100,100), 1 )

Step 3 – Detect the eyes from ROI and feed it to the classifier

The same procedure to detect faces is used to detect eyes. First, we set the cascade classifier for eyes in leye and reye respectively then detect the eyes using left_eye = leye.detectMultiScale(gray). Now we need to extract only the eyes data from the full image. This can be achieved by extracting the boundary box of the eye and then we can pull out the eye image from the frame with this code.

l_eye = frame[ y : y+h, x : x+w ]

l_eye only contains the image data of the eye. This will be fed into our CNN classifier which will predict if eyes are open or closed. Similarly, we will be extracting the right eye into r_eye.

Step 4 – Classifier will Categorize whether Eyes are Open or Closed

We are using CNN classifier for predicting the eye status. To feed our image into the model, we need to perform certain operations because the model needs the correct dimensions to start with. First, we convert the color image into grayscale using r_eye = cv2.cvtColor(r_eye, cv2.COLOR_BGR2GRAY). Then, we resize the image to 24*24 pixels as our model was trained on 24*24 pixel images cv2.resize(r_eye, (24,24)). We normalize our data for better convergence r_eye = r_eye/255 (All values will be between 0-1). Expand the dimensions to feed into our classifier. We loaded our model using model = load_model(‘models/cnnCat2.h5’) . Now we predict each eye with our model
lpred = model.predict_classes(l_eye). If the value of lpred[0] = 1, it states that eyes are open, if value of lpred[0] = 0 then, it states that eyes are closed.

Step 5 – Calculate Score to Check whether Person is Drowsy

The score is basically a value we will use to determine how long the person has closed his eyes. So if both eyes are closed, we will keep on increasing score and when eyes are open, we decrease the score. We are drawing the result on the screen using cv2.putText() function which will display real time status of the person.

cv2.putText(frame, “Open”, (10, height-20), font, 1, (255,255,255), 1, cv2.LINE_AA )

A threshold is defined for example if score becomes greater than 15 that means the person’s eyes are closed for a long period of time. This is when we beep the alarm using sound.play()

The Source Code of our main file looks like this:

import cv2
import os
from keras.models import load_model
import numpy as np
from pygame import mixer
import time

mixer.init()
sound = mixer.Sound('alarm.wav')

face = cv2.CascadeClassifier('haar cascade files\haarcascade_frontalface_alt.xml')
leye = cv2.CascadeClassifier('haar cascade files\haarcascade_lefteye_2splits.xml')
reye = cv2.CascadeClassifier('haar cascade files\haarcascade_righteye_2splits.xml')

lbl=['Close','Open']

model = load_model('models/cnncat2.h5')
path = os.getcwd()
cap = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_COMPLEX_SMALL
count=0
score=0
thicc=2
rpred=[99]
lpred=[99]

while(True):
    ret, frame = cap.read()
    height,width = frame.shape[:2]

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = face.detectMultiScale(gray,minNeighbors=5,scaleFactor=1.1,minSize=(25,25))
    left_eye = leye.detectMultiScale(gray)
    right_eye = reye.detectMultiScale(gray)

    cv2.rectangle(frame, (0,height-50) , (200,height) , (0,0,0) , thickness=cv2.FILLED )

    for (x,y,w,h) in faces:
cv2.rectangle(frame, (x,y) , (x+w,y+h) , (100,100,100) , 1 )

    for (x,y,w,h) in right_eye:
        r_eye=frame[y:y+h,x:x+w]
        count=count+1
        r_eye = cv2.cvtColor(r_eye,cv2.COLOR_BGR2GRAY)
        r_eye = cv2.resize(r_eye,(24,24))
        r_eye= r_eye/255
        r_eye= r_eye.reshape(24,24,-1)
        r_eye = np.expand_dims(r_eye,axis=0)
        rpred = model.predict_classes(r_eye)
        if(rpred[0]==1):
            lbl='Open'
        if(rpred[0]==0):
            lbl='Closed'
        break

    for (x,y,w,h) in left_eye:
        l_eye=frame[y:y+h,x:x+w]
        count=count+1
        l_eye = cv2.cvtColor(l_eye,cv2.COLOR_BGR2GRAY)
        l_eye = cv2.resize(l_eye,(24,24))
        l_eye= l_eye/255
        l_eye=l_eye.reshape(24,24,-1)
        l_eye = np.expand_dims(l_eye,axis=0)
        lpred = model.predict_classes(l_eye)
        if(lpred[0]==1):
            lbl='Open'
        if(lpred[0]==0):
            lbl='Closed'
        break

    if(rpred[0]==0 and lpred[0]==0):
        score=score+1
        cv2.putText(frame,"Closed",(10,height-20), font, 1,(255,255,255),1,cv2.LINE_AA)
    # if(rpred[0]==1 or lpred[0]==1):
    else:
        score=score-1
        cv2.putText(frame,"Open",(10,height-20), font, 1,(255,255,255),1,cv2.LINE_AA)

    if(score<0):
        score=0
    cv2.putText(frame,'Score:'+str(score),(100,height-20), font, 1,(255,255,255),1,cv2.LINE_AA)
    if(score>15):
        #person is feeling sleepy so we beep the alarm
        cv2.imwrite(os.path.join(path,'image.jpg'),frame)
        try:
            sound.play()

        except: # isplaying = False
            pass
        if(thicc<16):
            thicc= thicc+2
        else:
            thicc=thicc-2
            if(thicc<2):
                thicc=2
        cv2.rectangle(frame,(0,0),(width,height),(0,0,255),thicc)
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

Driver Drowsiness Detection Execution

Let’s execute drive drowsiness detection system and see the working of our ml project. To start the project, you need to open a command prompt, go to the directory where our main file “drowsiness detection.py” exists. Run the script with this command.

python “drowsiness detection.py”

It may take a few seconds to open the webcam and start detection.

Example Screenshot:

running drowsiness program - python project with source code

Output Screenshot:

closed eye detection python project for beginners

Closed Eye Detection

Open Eyes Detection - python open source projects

Open Eyes Detection

sleep alert - python open source project

Sleep Alert

Summary

In this Python project, we have built a drowsy driver alert system that you can implement in numerous ways. We used OpenCV to detect faces and eyes using a haar cascade classifier and then we used a CNN model to predict the status.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

225 Responses

  1. Subbu says:

    What is the algorithm used in this project

    • Abhijith says:

      Convolutional neural network(CNN)

    • DataFlair says:

      In this project, we first get the image and convert it into a grayscale one. Then we use the CascadeClassifier() to get the region of the face. Then left eye and rigth eyes are detected. There are then given to the trained CNN model to detect if the eyes are closed ro opened. Hope the explanation is clear.

  2. Nikita says:

    What is the accuracy of this model?

  3. Rahul says:

    2021-06-10 22:44:21.326300: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library ‘cudart64_110.dll’; dlerror: cudart64_110.dll not found
    2021-06-10 22:44:21.326657: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
    Traceback (most recent call last):
    File “.\drowsiness detection.py”, line 3, in
    from keras.models import load_model
    File “C:\Users\Rahul\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\__init__.py”, line 20, in
    from . import initializers
    File “C:\Users\Rahul\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\initializers\__init__.py”, line 124, in
    populate_deserializable_objects()
    File “C:\Users\Rahul\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\initializers\__init__.py”, line 82, in populate_deserializable_objects
    generic_utils.populate_dict_with_module_objects(
    AttributeError: module ‘keras.utils.generic_utils’ has no attribute ‘populate_dict_with_module_objects’

    i have installed all the required packages but still getting this error.
    please provide solution

    • Shrutika says:

      I’ve got this same error. Kindly share the solution if you have found it.

    • DataFlair says:

      To solve this problem, you can upgrade tensorflow and keras version using ‘pip install –upgrade keras’ and ‘pip install tensorflow –upgrade –force-reinstall’. If even this results in the same error, you can replace the import line with from tensorflow.keras.model import Sequential. Hoping that one of these solves the issue.

      • Suraj says:

        Line 3, in modulefrom tenosrflow.kears.models
        Importerror: cannot import name ‘sequential’ from tensorflow.kears.models’

        Date&time:04/11/2021 11:19pm

  4. Jahangeer says:

    Can we Use 3.9.1 Version for this amazing project?

    • DataFlair says:

      Yes you can have the 3.9.1 version of Python.But make sure you also have the latest version of moodules like tensorflow. Hope I answered your query.

  5. sharvai says:

    Can we make a android application for his. this is for my final project so I need frontend too. I’m begginer in data science.

  6. Phani says:

    Cannot find reference ‘load_model’ in ‘models.py’

    • DataFlair says:

      It might be due to the usage of previous versions of keras. You can upgrade it using the command pip install -U keras. Hope this solves!

  7. Shrutika says:

    I’ve got this same error. Kindly share the solution if you have found it.

  8. Jeyachandran says:

    Hello sir,
    How to implement this project in real time.

  9. Deepu says:

    What is front end tool and back end tool?

    • DataFlair says:

      Front end tools are the softwares used to develop the part of the website that is seen by the user and using which the user interacts. Back end tools are used to adds functionality to the website and its widgets. It allows the wesite to operate.Hope this explanation is clear.

  10. Satyendra Singh says:

    what version of all the libraries did you used for this project

  11. pankaj says:

    Sir!! Please help! Getting this error. The Project runs & then shuts quickly!

    Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
    Skipping registering GPU devices…
    2021-11-08 00:12:48.787772: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2
    To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
    [ WARN:0] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace’::SourceReaderCB::~SourceReaderCB terminating async callback
    Traceback (most recent call last):
    File “C:/Users/Pankaj/PycharmProjects/Drowsiness detection/driver-drowsiness-detection-Project/my_drowsiness_detection.py”, line 71, in
    right_eye_pred = model.predict_classes(right_one)
    AttributeError: ‘Sequential’ object has no attribute ‘predict_classes’
    [ WARN:0] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace’::SourceReaderCB::~SourceReaderCB terminating async callback

  12. Om Satya says:

    Can you please help me with this i almost got everything right except this ig

    AttributeError: ‘NoneType’ object has no attribute ‘shape’

  13. Smm says:

    Path=os.getcwd()

    Typeerror:’module’ object is not callable

  14. Vignesh Loganathan says:

    Hi,

    Please use tensor flow & keras version 2.4.0 to overcome this error as predict_classes function is removed from tensor flow version 2.5.0 onwards

    Thanks

  15. carla says:

    Traceback (most recent call last):
    File “C:\python38\Drowsiness detection\drowsiness detection.py”, line 31, in
    ret, frame = cap.read()
    cv2.error: Unknown C++ exception from OpenCV code

  16. LAXMAN KUMAR PANDA says:

    Traceback (most recent call last):
    File “D:\project\Drowsiness detection (1)\Drowsiness detection\drowsiness detection.py”, line 3, in
    from keras.models import load_model
    File “C:\Users\91775\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\__init__.py”, line 21, in
    from tensorflow.python import tf2
    File “C:\Users\91775\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\__init__.py”, line 41, in
    from tensorflow.python.tools import module_util as _module_util
    File “C:\Users\91775\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\__init__.py”, line 40, in
    from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
    File “C:\Users\91775\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\pywrap_tensorflow.py”, line 28, in
    self_check.preload_check()
    File “C:\Users\91775\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\platform\self_check.py”, line 54, in preload_check
    raise ImportError(
    ImportError: Could not find the DLL(s) ‘msvcp140_1.dll’. TensorFlow requires that these DLLs be installed in a directory that is named in your %PATH% environment variable. You may install these DLLs by downloading “Microsoft C++ Redistributable for Visual Studio 2015, 2017 and 2019” for your platform from this URL: https://support.microsoft.com/help/2977003/the-latest-supported-visual-c-downloads

  17. Reza says:

    I’m having this problem:
    File “C:\Users\user\Desktop\MSc_Project\project\Drowsinessdetection\drowsinessdetection.py”, line 53, in
    rpred = model.predict_classes(r_eye)
    AttributeError: ‘Sequential’ object has no attribute ‘predict_classes’
    [ WARN:1] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace’::SourceReaderCB::~SourceReaderCB terminating async callback.

  18. Harshal Chaudhari says:

    how you calculated the score?

  19. Harshal Chaudhari says:

    how you calculated the score??

  20. Rayan says:

    Hello, im having this error and im late on my deadline
    Can someone please help?!

    Traceback (most recent call last):
    File “C:/Users/rayan/Desktop/Senior/Drowsiness detection/drowsiness detection.py”, line 29, in
    height,width = frame.shape[:2]
    AttributeError: ‘NoneType’ object has no attribute ‘shape’

  21. Smita says:

    I am seeing the below error –

    C:\Users\smmehta\Desktop\Drowsiness_Detection\Drowsiness detection>python drowsiness_detection.py
    2022-01-13 20:35:16.170086: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library ‘cudart64_110.dll’; dlerror: cudart64_110.dll not found
    2022-01-13 20:35:16.174018: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
    pygame 2.1.2 (SDL 2.0.18, Python 3.7.4)
    Hello from the pygame community. https://www.pygame.org/contribute.html
    2022-01-13 20:35:18.314747: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library ‘nvcuda.dll’; dlerror: nvcuda.dll not found
    2022-01-13 20:35:18.319057: W tensorflow/stream_executor/cuda/cuda_driver.cc:269] failed call to cuInit: UNKNOWN ERROR (303)
    2022-01-13 20:35:18.325806: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: 3INLSMMEHTA2
    2022-01-13 20:35:18.329478: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: 3INLSMMEHTA2
    2022-01-13 20:35:18.337176: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2
    To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
    Traceback (most recent call last):
    File “drowsiness_detection.py”, line 54, in
    if(rpred[0]==1):
    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

    Can someone please help ?

  22. Viraj says:

    How to use same thing for mouth of a person

  23. Praneet says:

    hello did u got solved ur error.pls tell me. i got error for this
    File “drowsiness_detection.py”, line 54, in
    if(rpred[0]==1):
    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

  24. Arya says:

    cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-8vfej43a\opencv\modules\highgui\src\window.cpp:679: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function ‘cvShowImage’

    How can I solve this error?

  25. Vidya says:

    Can u increase the code I want a capstone project

  26. Shivi says:

    Can u please provide me this complete project on urgent basis

  27. saravana says:

    nvalidArgumentError Traceback (most recent call last)
    Input In [1], in
    28 model = Sequential([
    29 Conv2D(32, kernel_size=(3, 3), activation=’relu’, input_shape=(24,24,1)),
    30 MaxPooling2D(pool_size=(1,1)),
    (…)
    50 Dense(2, activation=’softmax’)
    51 ])
    53 model.compile(optimizer=’adam’,loss=’categorical_crossentropy’,metrics=[‘accuracy’])
    —> 55 model.fit(train_batch,validation_data=valid_batch,epochs=15,steps_per_epoch=SPE ,validation_steps=VS)
    57 model.save(‘models/cnnCat2.h5’, overwrite=True)

    Sir i am getting invalid argument error in model.fit line, please help me to sort it out

  28. saravana says:

    InvalidArgumentError Traceback (most recent call last)
    Input In [1], in
    28 model = Sequential([
    29 Conv2D(32, kernel_size=(3, 3), activation=’relu’, input_shape=(24,24,1)),
    30 MaxPooling2D(pool_size=(1,1)),
    (…)
    50 Dense(2, activation=’softmax’)
    51 ])
    53 model.compile(optimizer=’adam’,loss=’categorical_crossentropy’,metrics=[‘accuracy’])
    —> 55 model.fit(train_batch,validation_data=valid_batch,epochs=15,steps_per_epoch=SPE ,validation_steps=VS)
    57 model.save(‘models/cnnCat2.h5’, overwrite=True)

    sir i am getting invalid argument error in model.fit , please help me out to sort out of this problem

  29. saravana says:

    InvalidArgumentError Traceback (most recent call last)
    Input In [1], in
    28 model = Sequential([
    29 Conv2D(32, kernel_size=(3, 3), activation=’relu’, input_shape=(24,24,1)),
    30 MaxPooling2D(pool_size=(1,1)),
    (…)
    50 Dense(2, activation=’softmax’)
    51 ])
    53 model.compile(optimizer=’adam’,loss=’categorical_crossentropy’,metrics=[‘accuracy’])
    —> 55 model.fit(train_batch,validation_data=valid_batch,epochs=15,steps_per_epoch=SPE ,validation_steps=VS)
    57 model.save(‘models/cnnCat2.h5’, overwrite=True)

    sir i am getting invalid argument error in model.fit, help me please

  30. vallimanalan says:

    InvalidArgumentError Traceback (most recent call last)
    Input In [1], in
    28 model = Sequential([
    29 Conv2D(32, kernel_size=(3, 3), activation=’relu’, input_shape=(24,24,1)),
    30 MaxPooling2D(pool_size=(1,1)),
    (…)
    50 Dense(2, activation=’softmax’)
    51 ])
    53 model.compile(optimizer=’adam’,loss=’categorical_crossentropy’,metrics=[‘accuracy’])
    —> 55 model.fit(train_batch,validation_data=valid_batch,epochs=15,steps_per_epoch=SPE ,validation_steps=VS)
    57 model.save(‘models/cnnCat2.h5’, overwrite=True)

    please help me to sort out the error

Leave a Reply

Your email address will not be published. Required fields are marked *