trying to concatenate two layers in keras with the same shape giving error in shapes matching












0















I am trying to build a multi-input multi-output model using keras functional api and I am following their code but I got that error:




ValueError: A Concatenate layer requires inputs with matching
shapes except for the concat axis. Got inputs shapes: [(None, 50),
(None, 50, 1)]




I have skipped the Embedding layer, here is the code:



def build_model(self):
main_input = Input(shape=(self.seq_len, 1), name='main_input')
print(main_input.shape)
# seq_len = 50
# A LSTM will transform the vector sequence into a single vector,
# containing information about the entire sequence
lstm_out = LSTM(self.seq_len,input_shape=(self.seq_len,1) )(main_input)
self.auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out)

auxiliary_input = Input(shape=(self.seq_len,1), name='aux_input')
print(auxiliary_input.shape)
x = concatenate([lstm_out, auxiliary_input])

# We stack a deep densely-connected network on top
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)

# And finally we add the main logistic regression layer
main_output = Dense(1, activation='sigmoid', name='main_output')(x)
self.model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])
print(self.model.summary())
self.model.compile(optimizer='rmsprop', loss='binary_crossentropy',
loss_weights=[1., 0.2])


I got that error in the concatenation step, although printing the shape of both layers are (?,50,1).
I do not know exactly why I got this, and what is the exact error in the input_shape of the first layer and why it does not give me the same shape as it should be using print(main_input.shape), and how to solve it ?




UPDATE:




I found a solution for the error by changing the shape of the second input layer



auxiliary_input = Input(shape=(self.seq_len,), name='aux_input')


so now they can concatenate smoothly, but still not clear to me why ?










share|improve this question





























    0















    I am trying to build a multi-input multi-output model using keras functional api and I am following their code but I got that error:




    ValueError: A Concatenate layer requires inputs with matching
    shapes except for the concat axis. Got inputs shapes: [(None, 50),
    (None, 50, 1)]




    I have skipped the Embedding layer, here is the code:



    def build_model(self):
    main_input = Input(shape=(self.seq_len, 1), name='main_input')
    print(main_input.shape)
    # seq_len = 50
    # A LSTM will transform the vector sequence into a single vector,
    # containing information about the entire sequence
    lstm_out = LSTM(self.seq_len,input_shape=(self.seq_len,1) )(main_input)
    self.auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out)

    auxiliary_input = Input(shape=(self.seq_len,1), name='aux_input')
    print(auxiliary_input.shape)
    x = concatenate([lstm_out, auxiliary_input])

    # We stack a deep densely-connected network on top
    x = Dense(64, activation='relu')(x)
    x = Dense(64, activation='relu')(x)
    x = Dense(64, activation='relu')(x)

    # And finally we add the main logistic regression layer
    main_output = Dense(1, activation='sigmoid', name='main_output')(x)
    self.model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])
    print(self.model.summary())
    self.model.compile(optimizer='rmsprop', loss='binary_crossentropy',
    loss_weights=[1., 0.2])


    I got that error in the concatenation step, although printing the shape of both layers are (?,50,1).
    I do not know exactly why I got this, and what is the exact error in the input_shape of the first layer and why it does not give me the same shape as it should be using print(main_input.shape), and how to solve it ?




    UPDATE:




    I found a solution for the error by changing the shape of the second input layer



    auxiliary_input = Input(shape=(self.seq_len,), name='aux_input')


    so now they can concatenate smoothly, but still not clear to me why ?










    share|improve this question



























      0












      0








      0








      I am trying to build a multi-input multi-output model using keras functional api and I am following their code but I got that error:




      ValueError: A Concatenate layer requires inputs with matching
      shapes except for the concat axis. Got inputs shapes: [(None, 50),
      (None, 50, 1)]




      I have skipped the Embedding layer, here is the code:



      def build_model(self):
      main_input = Input(shape=(self.seq_len, 1), name='main_input')
      print(main_input.shape)
      # seq_len = 50
      # A LSTM will transform the vector sequence into a single vector,
      # containing information about the entire sequence
      lstm_out = LSTM(self.seq_len,input_shape=(self.seq_len,1) )(main_input)
      self.auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out)

      auxiliary_input = Input(shape=(self.seq_len,1), name='aux_input')
      print(auxiliary_input.shape)
      x = concatenate([lstm_out, auxiliary_input])

      # We stack a deep densely-connected network on top
      x = Dense(64, activation='relu')(x)
      x = Dense(64, activation='relu')(x)
      x = Dense(64, activation='relu')(x)

      # And finally we add the main logistic regression layer
      main_output = Dense(1, activation='sigmoid', name='main_output')(x)
      self.model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])
      print(self.model.summary())
      self.model.compile(optimizer='rmsprop', loss='binary_crossentropy',
      loss_weights=[1., 0.2])


      I got that error in the concatenation step, although printing the shape of both layers are (?,50,1).
      I do not know exactly why I got this, and what is the exact error in the input_shape of the first layer and why it does not give me the same shape as it should be using print(main_input.shape), and how to solve it ?




      UPDATE:




      I found a solution for the error by changing the shape of the second input layer



      auxiliary_input = Input(shape=(self.seq_len,), name='aux_input')


      so now they can concatenate smoothly, but still not clear to me why ?










      share|improve this question
















      I am trying to build a multi-input multi-output model using keras functional api and I am following their code but I got that error:




      ValueError: A Concatenate layer requires inputs with matching
      shapes except for the concat axis. Got inputs shapes: [(None, 50),
      (None, 50, 1)]




      I have skipped the Embedding layer, here is the code:



      def build_model(self):
      main_input = Input(shape=(self.seq_len, 1), name='main_input')
      print(main_input.shape)
      # seq_len = 50
      # A LSTM will transform the vector sequence into a single vector,
      # containing information about the entire sequence
      lstm_out = LSTM(self.seq_len,input_shape=(self.seq_len,1) )(main_input)
      self.auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out)

      auxiliary_input = Input(shape=(self.seq_len,1), name='aux_input')
      print(auxiliary_input.shape)
      x = concatenate([lstm_out, auxiliary_input])

      # We stack a deep densely-connected network on top
      x = Dense(64, activation='relu')(x)
      x = Dense(64, activation='relu')(x)
      x = Dense(64, activation='relu')(x)

      # And finally we add the main logistic regression layer
      main_output = Dense(1, activation='sigmoid', name='main_output')(x)
      self.model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])
      print(self.model.summary())
      self.model.compile(optimizer='rmsprop', loss='binary_crossentropy',
      loss_weights=[1., 0.2])


      I got that error in the concatenation step, although printing the shape of both layers are (?,50,1).
      I do not know exactly why I got this, and what is the exact error in the input_shape of the first layer and why it does not give me the same shape as it should be using print(main_input.shape), and how to solve it ?




      UPDATE:




      I found a solution for the error by changing the shape of the second input layer



      auxiliary_input = Input(shape=(self.seq_len,), name='aux_input')


      so now they can concatenate smoothly, but still not clear to me why ?







      python machine-learning keras neural-network lstm






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 25 '18 at 9:56







      Kamal El-Saaid

















      asked Nov 24 '18 at 19:17









      Kamal El-SaaidKamal El-Saaid

      225




      225
























          1 Answer
          1






          active

          oldest

          votes


















          1














          For the second input, you specified before the bug that,



          input_shape = (50,1)# seq_length=50


          This means final shape is:



          (None,50,1)


          Now, when the first input passes through LSTM , since you didn't specify return_sequences=True it will return a tensor of shape (batch_size, units) viz. (None, 50) which you are concatenating with the above mentioned (None, 50, 1)



          Your error went away because you changed the input shape for the second input as (50,) so the final shape becomes (None,50) which matches with output of LSTM and hence it concatenated smoothly






          share|improve this answer























            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%2f53461561%2ftrying-to-concatenate-two-layers-in-keras-with-the-same-shape-giving-error-in-sh%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









            1














            For the second input, you specified before the bug that,



            input_shape = (50,1)# seq_length=50


            This means final shape is:



            (None,50,1)


            Now, when the first input passes through LSTM , since you didn't specify return_sequences=True it will return a tensor of shape (batch_size, units) viz. (None, 50) which you are concatenating with the above mentioned (None, 50, 1)



            Your error went away because you changed the input shape for the second input as (50,) so the final shape becomes (None,50) which matches with output of LSTM and hence it concatenated smoothly






            share|improve this answer




























              1














              For the second input, you specified before the bug that,



              input_shape = (50,1)# seq_length=50


              This means final shape is:



              (None,50,1)


              Now, when the first input passes through LSTM , since you didn't specify return_sequences=True it will return a tensor of shape (batch_size, units) viz. (None, 50) which you are concatenating with the above mentioned (None, 50, 1)



              Your error went away because you changed the input shape for the second input as (50,) so the final shape becomes (None,50) which matches with output of LSTM and hence it concatenated smoothly






              share|improve this answer


























                1












                1








                1







                For the second input, you specified before the bug that,



                input_shape = (50,1)# seq_length=50


                This means final shape is:



                (None,50,1)


                Now, when the first input passes through LSTM , since you didn't specify return_sequences=True it will return a tensor of shape (batch_size, units) viz. (None, 50) which you are concatenating with the above mentioned (None, 50, 1)



                Your error went away because you changed the input shape for the second input as (50,) so the final shape becomes (None,50) which matches with output of LSTM and hence it concatenated smoothly






                share|improve this answer













                For the second input, you specified before the bug that,



                input_shape = (50,1)# seq_length=50


                This means final shape is:



                (None,50,1)


                Now, when the first input passes through LSTM , since you didn't specify return_sequences=True it will return a tensor of shape (batch_size, units) viz. (None, 50) which you are concatenating with the above mentioned (None, 50, 1)



                Your error went away because you changed the input shape for the second input as (50,) so the final shape becomes (None,50) which matches with output of LSTM and hence it concatenated smoothly







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 25 '18 at 10:07









                VitrioilVitrioil

                894




                894






























                    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%2f53461561%2ftrying-to-concatenate-two-layers-in-keras-with-the-same-shape-giving-error-in-sh%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







                    Popular posts from this blog

                    Contact image not getting when fetch all contact list from iPhone by CNContact

                    count number of partitions of a set with n elements into k subsets

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks