Having trouble with CNN prediction












0















I am using Convolutional Neural Networking for vehicle identification, my first time. Currently, I am working with just 2 classes(bike and car). Training set: 420 car images and 825 bike images. Test set: 44 car images and 110 bike images Car and Bike images are in different format(bmp,jpg). In single prediction, I am always getting 'bike'. I have tried using the Sigmoid function in the output layer. Then I get only 'car'. My code is like following: ``



from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense,Dropout



classifier = Sequential()


classifier.add(Conv2D(32, (3, 3), input_shape = (128, 128, 3), activation = 'relu'))


classifier.add(MaxPooling2D(pool_size = (3, 3)))

# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (3, 3)))

# Step 3 - Flattening
classifier.add(Flatten())

# Step 4 - Full connection
classifier.add(Dropout(0.3))
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))

# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# Part 2 - Fitting the CNN to the images

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
rotation_range= 3,
fill_mode = 'nearest',
horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
rotation_range= 3,
fill_mode = 'nearest',
horizontal_flip = True)

training_set = train_datagen.flow_from_directory('dataset/training_set',
target_size = (128, 128),
batch_size = 10,
class_mode = 'binary')

test_set = test_datagen.flow_from_directory('dataset/test_set',
target_size = (128, 128),
batch_size = 10,
class_mode = 'binary')

classifier.fit_generator(training_set,
steps_per_epoch = 1092//10,
epochs = 3,
validation_data = test_set,
validation_steps = 20)

classifier.save("car_bike.h5")


And I wanted to test a single image like the following:



test_image = image.load_img('dataset/single_prediction/download (3).jpg', target_size = (128, 128))
test_image = image.img_to_array(test_image)
test_image *= (1/255.0)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
if result[0][0] == 1:
prediction = 'bike'
else:
prediction = 'car'

print(" {}".format(prediction))









share|improve this question



























    0















    I am using Convolutional Neural Networking for vehicle identification, my first time. Currently, I am working with just 2 classes(bike and car). Training set: 420 car images and 825 bike images. Test set: 44 car images and 110 bike images Car and Bike images are in different format(bmp,jpg). In single prediction, I am always getting 'bike'. I have tried using the Sigmoid function in the output layer. Then I get only 'car'. My code is like following: ``



    from keras.models import Sequential
    from keras.layers import Conv2D
    from keras.layers import MaxPooling2D
    from keras.layers import Flatten
    from keras.layers import Dense,Dropout



    classifier = Sequential()


    classifier.add(Conv2D(32, (3, 3), input_shape = (128, 128, 3), activation = 'relu'))


    classifier.add(MaxPooling2D(pool_size = (3, 3)))

    # Adding a second convolutional layer
    classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
    classifier.add(MaxPooling2D(pool_size = (3, 3)))

    # Step 3 - Flattening
    classifier.add(Flatten())

    # Step 4 - Full connection
    classifier.add(Dropout(0.3))
    classifier.add(Dense(units = 128, activation = 'relu'))
    classifier.add(Dense(units = 1, activation = 'sigmoid'))

    # Compiling the CNN
    classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

    # Part 2 - Fitting the CNN to the images

    from keras.preprocessing.image import ImageDataGenerator

    train_datagen = ImageDataGenerator(rescale = 1./255,
    shear_range = 0.2,
    zoom_range = 0.2,
    rotation_range= 3,
    fill_mode = 'nearest',
    horizontal_flip = True)

    test_datagen = ImageDataGenerator(rescale = 1./255,
    shear_range = 0.2,
    zoom_range = 0.2,
    rotation_range= 3,
    fill_mode = 'nearest',
    horizontal_flip = True)

    training_set = train_datagen.flow_from_directory('dataset/training_set',
    target_size = (128, 128),
    batch_size = 10,
    class_mode = 'binary')

    test_set = test_datagen.flow_from_directory('dataset/test_set',
    target_size = (128, 128),
    batch_size = 10,
    class_mode = 'binary')

    classifier.fit_generator(training_set,
    steps_per_epoch = 1092//10,
    epochs = 3,
    validation_data = test_set,
    validation_steps = 20)

    classifier.save("car_bike.h5")


    And I wanted to test a single image like the following:



    test_image = image.load_img('dataset/single_prediction/download (3).jpg', target_size = (128, 128))
    test_image = image.img_to_array(test_image)
    test_image *= (1/255.0)
    test_image = np.expand_dims(test_image, axis = 0)
    result = classifier.predict(test_image)
    if result[0][0] == 1:
    prediction = 'bike'
    else:
    prediction = 'car'

    print(" {}".format(prediction))









    share|improve this question

























      0












      0








      0








      I am using Convolutional Neural Networking for vehicle identification, my first time. Currently, I am working with just 2 classes(bike and car). Training set: 420 car images and 825 bike images. Test set: 44 car images and 110 bike images Car and Bike images are in different format(bmp,jpg). In single prediction, I am always getting 'bike'. I have tried using the Sigmoid function in the output layer. Then I get only 'car'. My code is like following: ``



      from keras.models import Sequential
      from keras.layers import Conv2D
      from keras.layers import MaxPooling2D
      from keras.layers import Flatten
      from keras.layers import Dense,Dropout



      classifier = Sequential()


      classifier.add(Conv2D(32, (3, 3), input_shape = (128, 128, 3), activation = 'relu'))


      classifier.add(MaxPooling2D(pool_size = (3, 3)))

      # Adding a second convolutional layer
      classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
      classifier.add(MaxPooling2D(pool_size = (3, 3)))

      # Step 3 - Flattening
      classifier.add(Flatten())

      # Step 4 - Full connection
      classifier.add(Dropout(0.3))
      classifier.add(Dense(units = 128, activation = 'relu'))
      classifier.add(Dense(units = 1, activation = 'sigmoid'))

      # Compiling the CNN
      classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

      # Part 2 - Fitting the CNN to the images

      from keras.preprocessing.image import ImageDataGenerator

      train_datagen = ImageDataGenerator(rescale = 1./255,
      shear_range = 0.2,
      zoom_range = 0.2,
      rotation_range= 3,
      fill_mode = 'nearest',
      horizontal_flip = True)

      test_datagen = ImageDataGenerator(rescale = 1./255,
      shear_range = 0.2,
      zoom_range = 0.2,
      rotation_range= 3,
      fill_mode = 'nearest',
      horizontal_flip = True)

      training_set = train_datagen.flow_from_directory('dataset/training_set',
      target_size = (128, 128),
      batch_size = 10,
      class_mode = 'binary')

      test_set = test_datagen.flow_from_directory('dataset/test_set',
      target_size = (128, 128),
      batch_size = 10,
      class_mode = 'binary')

      classifier.fit_generator(training_set,
      steps_per_epoch = 1092//10,
      epochs = 3,
      validation_data = test_set,
      validation_steps = 20)

      classifier.save("car_bike.h5")


      And I wanted to test a single image like the following:



      test_image = image.load_img('dataset/single_prediction/download (3).jpg', target_size = (128, 128))
      test_image = image.img_to_array(test_image)
      test_image *= (1/255.0)
      test_image = np.expand_dims(test_image, axis = 0)
      result = classifier.predict(test_image)
      if result[0][0] == 1:
      prediction = 'bike'
      else:
      prediction = 'car'

      print(" {}".format(prediction))









      share|improve this question














      I am using Convolutional Neural Networking for vehicle identification, my first time. Currently, I am working with just 2 classes(bike and car). Training set: 420 car images and 825 bike images. Test set: 44 car images and 110 bike images Car and Bike images are in different format(bmp,jpg). In single prediction, I am always getting 'bike'. I have tried using the Sigmoid function in the output layer. Then I get only 'car'. My code is like following: ``



      from keras.models import Sequential
      from keras.layers import Conv2D
      from keras.layers import MaxPooling2D
      from keras.layers import Flatten
      from keras.layers import Dense,Dropout



      classifier = Sequential()


      classifier.add(Conv2D(32, (3, 3), input_shape = (128, 128, 3), activation = 'relu'))


      classifier.add(MaxPooling2D(pool_size = (3, 3)))

      # Adding a second convolutional layer
      classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
      classifier.add(MaxPooling2D(pool_size = (3, 3)))

      # Step 3 - Flattening
      classifier.add(Flatten())

      # Step 4 - Full connection
      classifier.add(Dropout(0.3))
      classifier.add(Dense(units = 128, activation = 'relu'))
      classifier.add(Dense(units = 1, activation = 'sigmoid'))

      # Compiling the CNN
      classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

      # Part 2 - Fitting the CNN to the images

      from keras.preprocessing.image import ImageDataGenerator

      train_datagen = ImageDataGenerator(rescale = 1./255,
      shear_range = 0.2,
      zoom_range = 0.2,
      rotation_range= 3,
      fill_mode = 'nearest',
      horizontal_flip = True)

      test_datagen = ImageDataGenerator(rescale = 1./255,
      shear_range = 0.2,
      zoom_range = 0.2,
      rotation_range= 3,
      fill_mode = 'nearest',
      horizontal_flip = True)

      training_set = train_datagen.flow_from_directory('dataset/training_set',
      target_size = (128, 128),
      batch_size = 10,
      class_mode = 'binary')

      test_set = test_datagen.flow_from_directory('dataset/test_set',
      target_size = (128, 128),
      batch_size = 10,
      class_mode = 'binary')

      classifier.fit_generator(training_set,
      steps_per_epoch = 1092//10,
      epochs = 3,
      validation_data = test_set,
      validation_steps = 20)

      classifier.save("car_bike.h5")


      And I wanted to test a single image like the following:



      test_image = image.load_img('dataset/single_prediction/download (3).jpg', target_size = (128, 128))
      test_image = image.img_to_array(test_image)
      test_image *= (1/255.0)
      test_image = np.expand_dims(test_image, axis = 0)
      result = classifier.predict(test_image)
      if result[0][0] == 1:
      prediction = 'bike'
      else:
      prediction = 'car'

      print(" {}".format(prediction))






      python keras deep-learning






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 '18 at 4:24









      Iftekhar JamilIftekhar Jamil

      1




      1
























          1 Answer
          1






          active

          oldest

          votes


















          0














          If you print your result matrix you'll see that it doesn't have only 1s and 0s but floats between these numbers. You may pick a threshold and set values that exceed it to 1 and everything else to 0.






          share|improve this answer


























          • thanks for your response. You are right I am getting float numbers in the result matrix. But its value is never close to 1. For 'car' I am getting around 0.0003 and for bike it is <1e-10. So even I set a threshold of 0.5 it's not going to be 1.

            – Iftekhar Jamil
            Nov 13 '18 at 6:16











          • np.argmax would only work for 'categorized_crossentropy' loss function, so forget about that since you use 'binary_crossentropy'. I suggest increasing number of epochs from 3 to 100 or more and seeing the results again. Also make sure you have equal or close number of samples for cars and bikes. -editing my answer to get rid of argmax part-

            – Mete Han Kahraman
            Nov 13 '18 at 8:34













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53273786%2fhaving-trouble-with-cnn-prediction%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          If you print your result matrix you'll see that it doesn't have only 1s and 0s but floats between these numbers. You may pick a threshold and set values that exceed it to 1 and everything else to 0.






          share|improve this answer


























          • thanks for your response. You are right I am getting float numbers in the result matrix. But its value is never close to 1. For 'car' I am getting around 0.0003 and for bike it is <1e-10. So even I set a threshold of 0.5 it's not going to be 1.

            – Iftekhar Jamil
            Nov 13 '18 at 6:16











          • np.argmax would only work for 'categorized_crossentropy' loss function, so forget about that since you use 'binary_crossentropy'. I suggest increasing number of epochs from 3 to 100 or more and seeing the results again. Also make sure you have equal or close number of samples for cars and bikes. -editing my answer to get rid of argmax part-

            – Mete Han Kahraman
            Nov 13 '18 at 8:34


















          0














          If you print your result matrix you'll see that it doesn't have only 1s and 0s but floats between these numbers. You may pick a threshold and set values that exceed it to 1 and everything else to 0.






          share|improve this answer


























          • thanks for your response. You are right I am getting float numbers in the result matrix. But its value is never close to 1. For 'car' I am getting around 0.0003 and for bike it is <1e-10. So even I set a threshold of 0.5 it's not going to be 1.

            – Iftekhar Jamil
            Nov 13 '18 at 6:16











          • np.argmax would only work for 'categorized_crossentropy' loss function, so forget about that since you use 'binary_crossentropy'. I suggest increasing number of epochs from 3 to 100 or more and seeing the results again. Also make sure you have equal or close number of samples for cars and bikes. -editing my answer to get rid of argmax part-

            – Mete Han Kahraman
            Nov 13 '18 at 8:34
















          0












          0








          0







          If you print your result matrix you'll see that it doesn't have only 1s and 0s but floats between these numbers. You may pick a threshold and set values that exceed it to 1 and everything else to 0.






          share|improve this answer















          If you print your result matrix you'll see that it doesn't have only 1s and 0s but floats between these numbers. You may pick a threshold and set values that exceed it to 1 and everything else to 0.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 13 '18 at 8:34

























          answered Nov 13 '18 at 5:33









          Mete Han KahramanMete Han Kahraman

          40017




          40017













          • thanks for your response. You are right I am getting float numbers in the result matrix. But its value is never close to 1. For 'car' I am getting around 0.0003 and for bike it is <1e-10. So even I set a threshold of 0.5 it's not going to be 1.

            – Iftekhar Jamil
            Nov 13 '18 at 6:16











          • np.argmax would only work for 'categorized_crossentropy' loss function, so forget about that since you use 'binary_crossentropy'. I suggest increasing number of epochs from 3 to 100 or more and seeing the results again. Also make sure you have equal or close number of samples for cars and bikes. -editing my answer to get rid of argmax part-

            – Mete Han Kahraman
            Nov 13 '18 at 8:34





















          • thanks for your response. You are right I am getting float numbers in the result matrix. But its value is never close to 1. For 'car' I am getting around 0.0003 and for bike it is <1e-10. So even I set a threshold of 0.5 it's not going to be 1.

            – Iftekhar Jamil
            Nov 13 '18 at 6:16











          • np.argmax would only work for 'categorized_crossentropy' loss function, so forget about that since you use 'binary_crossentropy'. I suggest increasing number of epochs from 3 to 100 or more and seeing the results again. Also make sure you have equal or close number of samples for cars and bikes. -editing my answer to get rid of argmax part-

            – Mete Han Kahraman
            Nov 13 '18 at 8:34



















          thanks for your response. You are right I am getting float numbers in the result matrix. But its value is never close to 1. For 'car' I am getting around 0.0003 and for bike it is <1e-10. So even I set a threshold of 0.5 it's not going to be 1.

          – Iftekhar Jamil
          Nov 13 '18 at 6:16





          thanks for your response. You are right I am getting float numbers in the result matrix. But its value is never close to 1. For 'car' I am getting around 0.0003 and for bike it is <1e-10. So even I set a threshold of 0.5 it's not going to be 1.

          – Iftekhar Jamil
          Nov 13 '18 at 6:16













          np.argmax would only work for 'categorized_crossentropy' loss function, so forget about that since you use 'binary_crossentropy'. I suggest increasing number of epochs from 3 to 100 or more and seeing the results again. Also make sure you have equal or close number of samples for cars and bikes. -editing my answer to get rid of argmax part-

          – Mete Han Kahraman
          Nov 13 '18 at 8:34







          np.argmax would only work for 'categorized_crossentropy' loss function, so forget about that since you use 'binary_crossentropy'. I suggest increasing number of epochs from 3 to 100 or more and seeing the results again. Also make sure you have equal or close number of samples for cars and bikes. -editing my answer to get rid of argmax part-

          – Mete Han Kahraman
          Nov 13 '18 at 8:34




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53273786%2fhaving-trouble-with-cnn-prediction%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          Xamarin.form Move up view when keyboard appear

          Post-Redirect-Get with Spring WebFlux and Thymeleaf

          Anylogic : not able to use stopDelay()