IN CIFAR 10 DATASET2019 Community Moderator ElectionAre pre-trained models vor CIFAR-10 / CIFAR-100 / SVHN available?Keras : problem in fitting modelAttention network over text datasetnumber of neurons for mnist dataset using mlp?Optimum way to train a keras nn by a datasetCan CNN be used with 3d datasetinput shape of dataset in CNNValue error in Merging two different models in kerasTensorflow Dataset API: ndim

Multi tool use
Multi tool use

tikz convert color string to hex value

How is it possible to have an ability score that is less than 3?

What does "Puller Prush Person" mean?

Arrow those variables!

Can a vampire attack twice with their claws using Multiattack?

LWC SFDX source push error TypeError: LWC1009: decl.moveTo is not a function

How to efficiently unroll a matrix by value with numpy?

Alternative to sending password over mail?

Maximum likelihood parameters deviate from posterior distributions

Why is Minecraft giving an OpenGL error?

I'm flying to France today and my passport expires in less than 2 months

How do I draw and define two right triangles next to each other?

How to format long polynomial?

What's the output of a record needle playing an out-of-speed record

How do I gain back my faith in my PhD degree?

Could an aircraft fly or hover using only jets of compressed air?

What are these boxed doors outside store fronts in New York?

Modeling an IP Address

"You are your self first supporter", a more proper way to say it

Important Resources for Dark Age Civilizations?

Do infinite dimensional systems make sense?

When a company launches a new product do they "come out" with a new product or do they "come up" with a new product?

Is it possible to run Internet Explorer on OS X El Capitan?

Which country benefited the most from UN Security Council vetoes?



IN CIFAR 10 DATASET



2019 Community Moderator ElectionAre pre-trained models vor CIFAR-10 / CIFAR-100 / SVHN available?Keras : problem in fitting modelAttention network over text datasetnumber of neurons for mnist dataset using mlp?Optimum way to train a keras nn by a datasetCan CNN be used with 3d datasetinput shape of dataset in CNNValue error in Merging two different models in kerasTensorflow Dataset API: ndim










1












$begingroup$


After building up the mlp using



## building a mlp model
model=Sequential()
model.add(Dense(25,input_shape=(10,),activation='relu'))
model.add(Dense(100,input_shape=(10,),activation='relu'))
model.add(Dense(150,input_shape=(16,),activation='relu'))
model.add(Dense(10,input_shape=(10,),activation='softmax'))

model.compile(loss='categorical_crossentropy',
optimizer='Adam',metrics=['accuracy'])


when i'm trying to fit the model using



model.fit(x_train, y_train, epochs=10,validation_data=(x_test,y_test))



i'm getting this error:



ValueError Traceback (most recent call last)
in
1 # Training the MLP on the 2D data
----> 2 model.fit(x_train, y_train, epochs=10,validation_data=(x_test,y_test))



~anacondalibsite-packageskerasenginetraining.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
950 sample_weight=sample_weight,
951 class_weight=class_weight,
--> 952 batch_size=batch_size)
953 # Prepare validation data.
954 do_validation = False



~anacondalibsite-packageskerasenginetraining.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
749 feed_input_shapes,
750 check_batch_axis=False, # Don't enforce the batch size.
--> 751 exception_prefix='input')
752
753 if y is not None:



~anacondalibsite-packageskerasenginetraining_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
136 ': expected ' + names[i] + ' to have shape ' +
137 str(shape) + ' but got array with shape ' +
--> 138 str(data_shape))
139 return data
140



ValueError: Error when checking input: expected dense_29_input to have shape (10,) but got array with shape (3072,)



can anyone please tell me what mistake am i doing










share|improve this question











$endgroup$




bumped to the homepage by Community 5 hours ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.



















    1












    $begingroup$


    After building up the mlp using



    ## building a mlp model
    model=Sequential()
    model.add(Dense(25,input_shape=(10,),activation='relu'))
    model.add(Dense(100,input_shape=(10,),activation='relu'))
    model.add(Dense(150,input_shape=(16,),activation='relu'))
    model.add(Dense(10,input_shape=(10,),activation='softmax'))

    model.compile(loss='categorical_crossentropy',
    optimizer='Adam',metrics=['accuracy'])


    when i'm trying to fit the model using



    model.fit(x_train, y_train, epochs=10,validation_data=(x_test,y_test))



    i'm getting this error:



    ValueError Traceback (most recent call last)
    in
    1 # Training the MLP on the 2D data
    ----> 2 model.fit(x_train, y_train, epochs=10,validation_data=(x_test,y_test))



    ~anacondalibsite-packageskerasenginetraining.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
    950 sample_weight=sample_weight,
    951 class_weight=class_weight,
    --> 952 batch_size=batch_size)
    953 # Prepare validation data.
    954 do_validation = False



    ~anacondalibsite-packageskerasenginetraining.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
    749 feed_input_shapes,
    750 check_batch_axis=False, # Don't enforce the batch size.
    --> 751 exception_prefix='input')
    752
    753 if y is not None:



    ~anacondalibsite-packageskerasenginetraining_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    136 ': expected ' + names[i] + ' to have shape ' +
    137 str(shape) + ' but got array with shape ' +
    --> 138 str(data_shape))
    139 return data
    140



    ValueError: Error when checking input: expected dense_29_input to have shape (10,) but got array with shape (3072,)



    can anyone please tell me what mistake am i doing










    share|improve this question











    $endgroup$




    bumped to the homepage by Community 5 hours ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

















      1












      1








      1





      $begingroup$


      After building up the mlp using



      ## building a mlp model
      model=Sequential()
      model.add(Dense(25,input_shape=(10,),activation='relu'))
      model.add(Dense(100,input_shape=(10,),activation='relu'))
      model.add(Dense(150,input_shape=(16,),activation='relu'))
      model.add(Dense(10,input_shape=(10,),activation='softmax'))

      model.compile(loss='categorical_crossentropy',
      optimizer='Adam',metrics=['accuracy'])


      when i'm trying to fit the model using



      model.fit(x_train, y_train, epochs=10,validation_data=(x_test,y_test))



      i'm getting this error:



      ValueError Traceback (most recent call last)
      in
      1 # Training the MLP on the 2D data
      ----> 2 model.fit(x_train, y_train, epochs=10,validation_data=(x_test,y_test))



      ~anacondalibsite-packageskerasenginetraining.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
      950 sample_weight=sample_weight,
      951 class_weight=class_weight,
      --> 952 batch_size=batch_size)
      953 # Prepare validation data.
      954 do_validation = False



      ~anacondalibsite-packageskerasenginetraining.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
      749 feed_input_shapes,
      750 check_batch_axis=False, # Don't enforce the batch size.
      --> 751 exception_prefix='input')
      752
      753 if y is not None:



      ~anacondalibsite-packageskerasenginetraining_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
      136 ': expected ' + names[i] + ' to have shape ' +
      137 str(shape) + ' but got array with shape ' +
      --> 138 str(data_shape))
      139 return data
      140



      ValueError: Error when checking input: expected dense_29_input to have shape (10,) but got array with shape (3072,)



      can anyone please tell me what mistake am i doing










      share|improve this question











      $endgroup$




      After building up the mlp using



      ## building a mlp model
      model=Sequential()
      model.add(Dense(25,input_shape=(10,),activation='relu'))
      model.add(Dense(100,input_shape=(10,),activation='relu'))
      model.add(Dense(150,input_shape=(16,),activation='relu'))
      model.add(Dense(10,input_shape=(10,),activation='softmax'))

      model.compile(loss='categorical_crossentropy',
      optimizer='Adam',metrics=['accuracy'])


      when i'm trying to fit the model using



      model.fit(x_train, y_train, epochs=10,validation_data=(x_test,y_test))



      i'm getting this error:



      ValueError Traceback (most recent call last)
      in
      1 # Training the MLP on the 2D data
      ----> 2 model.fit(x_train, y_train, epochs=10,validation_data=(x_test,y_test))



      ~anacondalibsite-packageskerasenginetraining.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
      950 sample_weight=sample_weight,
      951 class_weight=class_weight,
      --> 952 batch_size=batch_size)
      953 # Prepare validation data.
      954 do_validation = False



      ~anacondalibsite-packageskerasenginetraining.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
      749 feed_input_shapes,
      750 check_batch_axis=False, # Don't enforce the batch size.
      --> 751 exception_prefix='input')
      752
      753 if y is not None:



      ~anacondalibsite-packageskerasenginetraining_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
      136 ': expected ' + names[i] + ' to have shape ' +
      137 str(shape) + ' but got array with shape ' +
      --> 138 str(data_shape))
      139 return data
      140



      ValueError: Error when checking input: expected dense_29_input to have shape (10,) but got array with shape (3072,)



      can anyone please tell me what mistake am i doing







      keras mlp






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 6 at 23:46









      JahKnows

      5,227727




      5,227727










      asked Mar 6 at 21:52









      saketh ramchandanisaketh ramchandani

      61




      61





      bumped to the homepage by Community 5 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community 5 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.






















          1 Answer
          1






          active

          oldest

          votes


















          0












          $begingroup$

          The problem here is the input_shape argument you are using, firstly that is the wrong shape and you should only provide an input shape for your first layer.



          For example



          Let's import the CIFAR 10 data from Keras



          from __future__ import print_function
          import keras
          from keras.datasets import cifar10
          from keras.preprocessing.image import ImageDataGenerator
          from keras.models import Sequential
          from keras.layers import Dense, Dropout, Activation, Flatten
          from keras.layers import Conv2D, MaxPooling2D
          import os

          num_classes = 10

          # The data, split between train and test sets:
          (x_train, y_train), (x_test, y_test) = cifar10.load_data()
          print('x_train shape:', x_train.shape)
          print(x_train.shape[0], 'train samples')
          print(x_test.shape[0], 'test samples')

          # Convert class vectors to binary class matrices.
          y_train = keras.utils.to_categorical(y_train, num_classes)
          y_test = keras.utils.to_categorical(y_test, num_classes)

          input_shape = x_train.shape[1:]
          print('input_shape: ', input_shape)



          x_train shape: (50000, 32, 32, 3)

          50000 train samples

          10000 test samples

          input_shape: (32, 32, 3)




          Now we can define our model. Note that I only use the input_shape in the first layer and furthermore, if you want to use a Dense layer as your first layer then you should flatten your inputs first.



          model=Sequential()
          model.add(Flatten(input_shape=input_shape))
          model.add(Dense(25,activation='relu'))
          model.add(Dense(100,activation='relu'))
          model.add(Dense(150,activation='relu'))
          model.add(Dense(10,activation='softmax'))

          model.compile(loss='categorical_crossentropy',
          optimizer='Adam',metrics=['accuracy'])


          You can use this to see your model



          model.summary()


          Now you can fit your model



          model.fit(x_train, 
          y_train,
          epochs=10,
          validation_data=(x_test,y_test))



          Since CIFAR 10 is comprised of image data I would not recommend you use Dense layers early in your model. You should rather use a Convolutional Neural Network (CNN). These layers act as a filter which extracts features from a neighborhood region of the image. This reduces the number of model parameters which will lead to better performance. From the Keras docs found here:



          model = Sequential()
          model.add(Conv2D(32, (3, 3), padding='same',
          input_shape=x_train.shape[1:]))
          model.add(Activation('relu'))
          model.add(Conv2D(32, (3, 3)))
          model.add(Activation('relu'))
          model.add(MaxPooling2D(pool_size=(2, 2)))
          model.add(Dropout(0.25))

          model.add(Conv2D(64, (3, 3), padding='same'))
          model.add(Activation('relu'))
          model.add(Conv2D(64, (3, 3)))
          model.add(Activation('relu'))
          model.add(MaxPooling2D(pool_size=(2, 2)))
          model.add(Dropout(0.25))

          model.add(Flatten())
          model.add(Dense(512))
          model.add(Activation('relu'))
          model.add(Dropout(0.5))
          model.add(Dense(num_classes))
          model.add(Activation('softmax'))





          share|improve this answer











          $endgroup$













            Your Answer





            StackExchange.ifUsing("editor", function ()
            return StackExchange.using("mathjaxEditing", function ()
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
            );
            );
            , "mathjax-editing");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "557"
            ;
            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: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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%2fdatascience.stackexchange.com%2fquestions%2f46819%2fin-cifar-10-dataset%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












            $begingroup$

            The problem here is the input_shape argument you are using, firstly that is the wrong shape and you should only provide an input shape for your first layer.



            For example



            Let's import the CIFAR 10 data from Keras



            from __future__ import print_function
            import keras
            from keras.datasets import cifar10
            from keras.preprocessing.image import ImageDataGenerator
            from keras.models import Sequential
            from keras.layers import Dense, Dropout, Activation, Flatten
            from keras.layers import Conv2D, MaxPooling2D
            import os

            num_classes = 10

            # The data, split between train and test sets:
            (x_train, y_train), (x_test, y_test) = cifar10.load_data()
            print('x_train shape:', x_train.shape)
            print(x_train.shape[0], 'train samples')
            print(x_test.shape[0], 'test samples')

            # Convert class vectors to binary class matrices.
            y_train = keras.utils.to_categorical(y_train, num_classes)
            y_test = keras.utils.to_categorical(y_test, num_classes)

            input_shape = x_train.shape[1:]
            print('input_shape: ', input_shape)



            x_train shape: (50000, 32, 32, 3)

            50000 train samples

            10000 test samples

            input_shape: (32, 32, 3)




            Now we can define our model. Note that I only use the input_shape in the first layer and furthermore, if you want to use a Dense layer as your first layer then you should flatten your inputs first.



            model=Sequential()
            model.add(Flatten(input_shape=input_shape))
            model.add(Dense(25,activation='relu'))
            model.add(Dense(100,activation='relu'))
            model.add(Dense(150,activation='relu'))
            model.add(Dense(10,activation='softmax'))

            model.compile(loss='categorical_crossentropy',
            optimizer='Adam',metrics=['accuracy'])


            You can use this to see your model



            model.summary()


            Now you can fit your model



            model.fit(x_train, 
            y_train,
            epochs=10,
            validation_data=(x_test,y_test))



            Since CIFAR 10 is comprised of image data I would not recommend you use Dense layers early in your model. You should rather use a Convolutional Neural Network (CNN). These layers act as a filter which extracts features from a neighborhood region of the image. This reduces the number of model parameters which will lead to better performance. From the Keras docs found here:



            model = Sequential()
            model.add(Conv2D(32, (3, 3), padding='same',
            input_shape=x_train.shape[1:]))
            model.add(Activation('relu'))
            model.add(Conv2D(32, (3, 3)))
            model.add(Activation('relu'))
            model.add(MaxPooling2D(pool_size=(2, 2)))
            model.add(Dropout(0.25))

            model.add(Conv2D(64, (3, 3), padding='same'))
            model.add(Activation('relu'))
            model.add(Conv2D(64, (3, 3)))
            model.add(Activation('relu'))
            model.add(MaxPooling2D(pool_size=(2, 2)))
            model.add(Dropout(0.25))

            model.add(Flatten())
            model.add(Dense(512))
            model.add(Activation('relu'))
            model.add(Dropout(0.5))
            model.add(Dense(num_classes))
            model.add(Activation('softmax'))





            share|improve this answer











            $endgroup$

















              0












              $begingroup$

              The problem here is the input_shape argument you are using, firstly that is the wrong shape and you should only provide an input shape for your first layer.



              For example



              Let's import the CIFAR 10 data from Keras



              from __future__ import print_function
              import keras
              from keras.datasets import cifar10
              from keras.preprocessing.image import ImageDataGenerator
              from keras.models import Sequential
              from keras.layers import Dense, Dropout, Activation, Flatten
              from keras.layers import Conv2D, MaxPooling2D
              import os

              num_classes = 10

              # The data, split between train and test sets:
              (x_train, y_train), (x_test, y_test) = cifar10.load_data()
              print('x_train shape:', x_train.shape)
              print(x_train.shape[0], 'train samples')
              print(x_test.shape[0], 'test samples')

              # Convert class vectors to binary class matrices.
              y_train = keras.utils.to_categorical(y_train, num_classes)
              y_test = keras.utils.to_categorical(y_test, num_classes)

              input_shape = x_train.shape[1:]
              print('input_shape: ', input_shape)



              x_train shape: (50000, 32, 32, 3)

              50000 train samples

              10000 test samples

              input_shape: (32, 32, 3)




              Now we can define our model. Note that I only use the input_shape in the first layer and furthermore, if you want to use a Dense layer as your first layer then you should flatten your inputs first.



              model=Sequential()
              model.add(Flatten(input_shape=input_shape))
              model.add(Dense(25,activation='relu'))
              model.add(Dense(100,activation='relu'))
              model.add(Dense(150,activation='relu'))
              model.add(Dense(10,activation='softmax'))

              model.compile(loss='categorical_crossentropy',
              optimizer='Adam',metrics=['accuracy'])


              You can use this to see your model



              model.summary()


              Now you can fit your model



              model.fit(x_train, 
              y_train,
              epochs=10,
              validation_data=(x_test,y_test))



              Since CIFAR 10 is comprised of image data I would not recommend you use Dense layers early in your model. You should rather use a Convolutional Neural Network (CNN). These layers act as a filter which extracts features from a neighborhood region of the image. This reduces the number of model parameters which will lead to better performance. From the Keras docs found here:



              model = Sequential()
              model.add(Conv2D(32, (3, 3), padding='same',
              input_shape=x_train.shape[1:]))
              model.add(Activation('relu'))
              model.add(Conv2D(32, (3, 3)))
              model.add(Activation('relu'))
              model.add(MaxPooling2D(pool_size=(2, 2)))
              model.add(Dropout(0.25))

              model.add(Conv2D(64, (3, 3), padding='same'))
              model.add(Activation('relu'))
              model.add(Conv2D(64, (3, 3)))
              model.add(Activation('relu'))
              model.add(MaxPooling2D(pool_size=(2, 2)))
              model.add(Dropout(0.25))

              model.add(Flatten())
              model.add(Dense(512))
              model.add(Activation('relu'))
              model.add(Dropout(0.5))
              model.add(Dense(num_classes))
              model.add(Activation('softmax'))





              share|improve this answer











              $endgroup$















                0












                0








                0





                $begingroup$

                The problem here is the input_shape argument you are using, firstly that is the wrong shape and you should only provide an input shape for your first layer.



                For example



                Let's import the CIFAR 10 data from Keras



                from __future__ import print_function
                import keras
                from keras.datasets import cifar10
                from keras.preprocessing.image import ImageDataGenerator
                from keras.models import Sequential
                from keras.layers import Dense, Dropout, Activation, Flatten
                from keras.layers import Conv2D, MaxPooling2D
                import os

                num_classes = 10

                # The data, split between train and test sets:
                (x_train, y_train), (x_test, y_test) = cifar10.load_data()
                print('x_train shape:', x_train.shape)
                print(x_train.shape[0], 'train samples')
                print(x_test.shape[0], 'test samples')

                # Convert class vectors to binary class matrices.
                y_train = keras.utils.to_categorical(y_train, num_classes)
                y_test = keras.utils.to_categorical(y_test, num_classes)

                input_shape = x_train.shape[1:]
                print('input_shape: ', input_shape)



                x_train shape: (50000, 32, 32, 3)

                50000 train samples

                10000 test samples

                input_shape: (32, 32, 3)




                Now we can define our model. Note that I only use the input_shape in the first layer and furthermore, if you want to use a Dense layer as your first layer then you should flatten your inputs first.



                model=Sequential()
                model.add(Flatten(input_shape=input_shape))
                model.add(Dense(25,activation='relu'))
                model.add(Dense(100,activation='relu'))
                model.add(Dense(150,activation='relu'))
                model.add(Dense(10,activation='softmax'))

                model.compile(loss='categorical_crossentropy',
                optimizer='Adam',metrics=['accuracy'])


                You can use this to see your model



                model.summary()


                Now you can fit your model



                model.fit(x_train, 
                y_train,
                epochs=10,
                validation_data=(x_test,y_test))



                Since CIFAR 10 is comprised of image data I would not recommend you use Dense layers early in your model. You should rather use a Convolutional Neural Network (CNN). These layers act as a filter which extracts features from a neighborhood region of the image. This reduces the number of model parameters which will lead to better performance. From the Keras docs found here:



                model = Sequential()
                model.add(Conv2D(32, (3, 3), padding='same',
                input_shape=x_train.shape[1:]))
                model.add(Activation('relu'))
                model.add(Conv2D(32, (3, 3)))
                model.add(Activation('relu'))
                model.add(MaxPooling2D(pool_size=(2, 2)))
                model.add(Dropout(0.25))

                model.add(Conv2D(64, (3, 3), padding='same'))
                model.add(Activation('relu'))
                model.add(Conv2D(64, (3, 3)))
                model.add(Activation('relu'))
                model.add(MaxPooling2D(pool_size=(2, 2)))
                model.add(Dropout(0.25))

                model.add(Flatten())
                model.add(Dense(512))
                model.add(Activation('relu'))
                model.add(Dropout(0.5))
                model.add(Dense(num_classes))
                model.add(Activation('softmax'))





                share|improve this answer











                $endgroup$



                The problem here is the input_shape argument you are using, firstly that is the wrong shape and you should only provide an input shape for your first layer.



                For example



                Let's import the CIFAR 10 data from Keras



                from __future__ import print_function
                import keras
                from keras.datasets import cifar10
                from keras.preprocessing.image import ImageDataGenerator
                from keras.models import Sequential
                from keras.layers import Dense, Dropout, Activation, Flatten
                from keras.layers import Conv2D, MaxPooling2D
                import os

                num_classes = 10

                # The data, split between train and test sets:
                (x_train, y_train), (x_test, y_test) = cifar10.load_data()
                print('x_train shape:', x_train.shape)
                print(x_train.shape[0], 'train samples')
                print(x_test.shape[0], 'test samples')

                # Convert class vectors to binary class matrices.
                y_train = keras.utils.to_categorical(y_train, num_classes)
                y_test = keras.utils.to_categorical(y_test, num_classes)

                input_shape = x_train.shape[1:]
                print('input_shape: ', input_shape)



                x_train shape: (50000, 32, 32, 3)

                50000 train samples

                10000 test samples

                input_shape: (32, 32, 3)




                Now we can define our model. Note that I only use the input_shape in the first layer and furthermore, if you want to use a Dense layer as your first layer then you should flatten your inputs first.



                model=Sequential()
                model.add(Flatten(input_shape=input_shape))
                model.add(Dense(25,activation='relu'))
                model.add(Dense(100,activation='relu'))
                model.add(Dense(150,activation='relu'))
                model.add(Dense(10,activation='softmax'))

                model.compile(loss='categorical_crossentropy',
                optimizer='Adam',metrics=['accuracy'])


                You can use this to see your model



                model.summary()


                Now you can fit your model



                model.fit(x_train, 
                y_train,
                epochs=10,
                validation_data=(x_test,y_test))



                Since CIFAR 10 is comprised of image data I would not recommend you use Dense layers early in your model. You should rather use a Convolutional Neural Network (CNN). These layers act as a filter which extracts features from a neighborhood region of the image. This reduces the number of model parameters which will lead to better performance. From the Keras docs found here:



                model = Sequential()
                model.add(Conv2D(32, (3, 3), padding='same',
                input_shape=x_train.shape[1:]))
                model.add(Activation('relu'))
                model.add(Conv2D(32, (3, 3)))
                model.add(Activation('relu'))
                model.add(MaxPooling2D(pool_size=(2, 2)))
                model.add(Dropout(0.25))

                model.add(Conv2D(64, (3, 3), padding='same'))
                model.add(Activation('relu'))
                model.add(Conv2D(64, (3, 3)))
                model.add(Activation('relu'))
                model.add(MaxPooling2D(pool_size=(2, 2)))
                model.add(Dropout(0.25))

                model.add(Flatten())
                model.add(Dense(512))
                model.add(Activation('relu'))
                model.add(Dropout(0.5))
                model.add(Dense(num_classes))
                model.add(Activation('softmax'))






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 7 at 0:45

























                answered Mar 7 at 0:39









                JahKnowsJahKnows

                5,227727




                5,227727



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Data Science Stack Exchange!


                    • 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.

                    Use MathJax to format equations. MathJax reference.


                    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%2fdatascience.stackexchange.com%2fquestions%2f46819%2fin-cifar-10-dataset%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







                    fCg92V Mw0CtGG,M
                    O,Li5 aap,QESq3 DxzEvb1bX4PCL

                    Popular posts from this blog

                    Францішак Багушэвіч Змест Сям'я | Біяграфія | Творчасць | Мова Багушэвіча | Ацэнкі дзейнасці | Цікавыя факты | Спадчына | Выбраная бібліяграфія | Ушанаванне памяці | У філатэліі | Зноскі | Літаратура | Спасылкі | НавігацыяЛяхоўскі У. Рупіўся дзеля Бога і людзей: Жыццёвы шлях Лявона Вітан-Дубейкаўскага // Вольскі і Памідораў з песняй пра немца Адвакат, паэт, народны заступнік Ашмянскі веснікВ Минске появится площадь Богушевича и улица Сырокомли, Белорусская деловая газета, 19 июля 2001 г.Айцец беларускай нацыянальнай ідэі паўстаў у бронзе Сяргей Аляксандравіч Адашкевіч (1918, Мінск). 80-я гады. Бюст «Францішак Багушэвіч».Яўген Мікалаевіч Ціхановіч. «Партрэт Францішка Багушэвіча»Мікола Мікалаевіч Купава. «Партрэт зачынальніка новай беларускай літаратуры Францішка Багушэвіча»Уладзімір Іванавіч Мелехаў. На помніку «Змагарам за родную мову» Барэльеф «Францішак Багушэвіч»Памяць пра Багушэвіча на Віленшчыне Страчаная сталіца. Беларускія шыльды на вуліцах Вільні«Krynica». Ideologia i przywódcy białoruskiego katolicyzmuФранцішак БагушэвічТворы на knihi.comТворы Францішка Багушэвіча на bellib.byСодаль Уладзімір. Францішак Багушэвіч на Лідчыне;Луцкевіч Антон. Жыцьцё і творчасьць Фр. Багушэвіча ў успамінах ягоных сучасьнікаў // Запісы Беларускага Навуковага таварыства. Вільня, 1938. Сшытак 1. С. 16-34.Большая российская1188761710000 0000 5537 633Xn9209310021619551927869394п

                    Partai Komunis Tiongkok Daftar isi Kepemimpinan | Pranala luar | Referensi | Menu navigasidiperiksa1 perubahan tertundacpc.people.com.cnSitus resmiSurat kabar resmi"Why the Communist Party is alive, well and flourishing in China"0307-1235"Full text of Constitution of Communist Party of China"smengembangkannyas

                    ValueError: Expected n_neighbors <= n_samples, but n_samples = 1, n_neighbors = 6 (SMOTE) The 2019 Stack Overflow Developer Survey Results Are InCan SMOTE be applied over sequence of words (sentences)?ValueError when doing validation with random forestsSMOTE and multi class oversamplingLogic behind SMOTE-NC?ValueError: Error when checking target: expected dense_1 to have shape (7,) but got array with shape (1,)SmoteBoost: Should SMOTE be ran individually for each iteration/tree in the boosting?solving multi-class imbalance classification using smote and OSSUsing SMOTE for Synthetic Data generation to improve performance on unbalanced dataproblem of entry format for a simple model in KerasSVM SMOTE fit_resample() function runs forever with no result