How to remove the last layer from a pre-trained model. I have tried model.layers.pop() but it is not workingHow to remove an element from a list by index?How to remove a key from a Python dictionary?Add dropout layers between pretrained dense layers in kerasGetting the output of layer as a feature vector (KERAS)Removing layers from a pretrained keras model gives the same output as original modelTransfer learning why remove last hidden layer?Transfer learning with CNN - why remove last 2 layersRemove middle layers in the pre-trained VGG16 model in KerasToo many parameters trying to rebuild VGG16Why replacing max pool by average pool using Keras APIs fails?

Employer wants to use my work email account after I quit

Unusual mail headers, evidence of an attempted attack. Have I been pwned?

An external consultant working on an internal project tried recruiting me. Should I tell my manager?

How to split an equation in two lines?

Require advice on power conservation for backpacking trip

Should I hide continue button until tasks are completed?

How to connect QSFP+ transceiver with MPO connector and SFP+ transceiver with LC connector?

How do I respond to requests for a "guarantee" not to leave after a few months?

Why is the Turkish president's surname spelt in Russian as Эрдоган, with г?

Lodash Flow and TypeScript

Is it damaging to turn off a small fridge for two days every week?

What happens when your group is victim of a surprise attack but you can't be surprised?

Cascading Repair Costs following Blown Head Gasket on a 2004 Subaru Outback

Apply brace expansion in "reverse order"

Fedora boot screen shows both Fedora logo and Lenovo logo. Why and How?

Does the posterior necessarily follow the same conditional dependence structure as the prior?

Can White Castle? #2

Links to webpages in books

Using “sparkling” as a diminutive of “spark” in a poem

How long would it take to cross the Channel in 1890's?

Do French speakers not use the subjunctive informally?

Why do some professors with PhDs leave their professorships to teach high school?

MH370 blackbox - is it still possible to retrieve data from it?

An expansion from Ramanujan related to birthday problem



How to remove the last layer from a pre-trained model. I have tried model.layers.pop() but it is not working


How to remove an element from a list by index?How to remove a key from a Python dictionary?Add dropout layers between pretrained dense layers in kerasGetting the output of layer as a feature vector (KERAS)Removing layers from a pretrained keras model gives the same output as original modelTransfer learning why remove last hidden layer?Transfer learning with CNN - why remove last 2 layersRemove middle layers in the pre-trained VGG16 model in KerasToo many parameters trying to rebuild VGG16Why replacing max pool by average pool using Keras APIs fails?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am trying to remove the last layer so that I can use transfer Leaning.



vgg16_model = keras.applications.vgg16.VGG16()
model = Sequential()

for layer in vgg16_model.layers:
model.add(layer)

model.layers.pop()


# Freeze the layers
for layer in model.layers:
layer.trainable = False


# Add 'softmax' instead of earlier 'prediction' layer.
model.add(Dense(2, activation='softmax'))


# Check the summary, and yes new layer has been added.
model.summary()


But the output I am getting is not what I expected. It is still showing the last layer of vgg16 model.



Here is the output



 _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
block1_conv1 (Conv2D) (None, 224, 224, 64) 1792
_________________________________________________________________
block1_conv2 (Conv2D) (None, 224, 224, 64) 36928

**THE HIDDEN LAYERS**
_________________________________________________________________
fc1 (Dense) (None, 4096) 102764544
_________________________________________________________________
fc2 (Dense) (None, 4096) 16781312
_________________________________________________________________
predictions (Dense) (None, 1000) 4097000
_________________________________________________________________
dense_10 (Dense) (None, 2) 2002
=================================================================
Total params: 138,359,546
Trainable params: 2,002
Non-trainable params: 138,357,544


Note- In the output I have not shown the whole model, just showed the first few layers and the last layers.



How should I remove the last layer to do transfer learning??



P.S Keras version = 2.2.4










share|improve this question






























    0















    I am trying to remove the last layer so that I can use transfer Leaning.



    vgg16_model = keras.applications.vgg16.VGG16()
    model = Sequential()

    for layer in vgg16_model.layers:
    model.add(layer)

    model.layers.pop()


    # Freeze the layers
    for layer in model.layers:
    layer.trainable = False


    # Add 'softmax' instead of earlier 'prediction' layer.
    model.add(Dense(2, activation='softmax'))


    # Check the summary, and yes new layer has been added.
    model.summary()


    But the output I am getting is not what I expected. It is still showing the last layer of vgg16 model.



    Here is the output



     _________________________________________________________________
    Layer (type) Output Shape Param #
    =================================================================
    block1_conv1 (Conv2D) (None, 224, 224, 64) 1792
    _________________________________________________________________
    block1_conv2 (Conv2D) (None, 224, 224, 64) 36928

    **THE HIDDEN LAYERS**
    _________________________________________________________________
    fc1 (Dense) (None, 4096) 102764544
    _________________________________________________________________
    fc2 (Dense) (None, 4096) 16781312
    _________________________________________________________________
    predictions (Dense) (None, 1000) 4097000
    _________________________________________________________________
    dense_10 (Dense) (None, 2) 2002
    =================================================================
    Total params: 138,359,546
    Trainable params: 2,002
    Non-trainable params: 138,357,544


    Note- In the output I have not shown the whole model, just showed the first few layers and the last layers.



    How should I remove the last layer to do transfer learning??



    P.S Keras version = 2.2.4










    share|improve this question


























      0












      0








      0








      I am trying to remove the last layer so that I can use transfer Leaning.



      vgg16_model = keras.applications.vgg16.VGG16()
      model = Sequential()

      for layer in vgg16_model.layers:
      model.add(layer)

      model.layers.pop()


      # Freeze the layers
      for layer in model.layers:
      layer.trainable = False


      # Add 'softmax' instead of earlier 'prediction' layer.
      model.add(Dense(2, activation='softmax'))


      # Check the summary, and yes new layer has been added.
      model.summary()


      But the output I am getting is not what I expected. It is still showing the last layer of vgg16 model.



      Here is the output



       _________________________________________________________________
      Layer (type) Output Shape Param #
      =================================================================
      block1_conv1 (Conv2D) (None, 224, 224, 64) 1792
      _________________________________________________________________
      block1_conv2 (Conv2D) (None, 224, 224, 64) 36928

      **THE HIDDEN LAYERS**
      _________________________________________________________________
      fc1 (Dense) (None, 4096) 102764544
      _________________________________________________________________
      fc2 (Dense) (None, 4096) 16781312
      _________________________________________________________________
      predictions (Dense) (None, 1000) 4097000
      _________________________________________________________________
      dense_10 (Dense) (None, 2) 2002
      =================================================================
      Total params: 138,359,546
      Trainable params: 2,002
      Non-trainable params: 138,357,544


      Note- In the output I have not shown the whole model, just showed the first few layers and the last layers.



      How should I remove the last layer to do transfer learning??



      P.S Keras version = 2.2.4










      share|improve this question
















      I am trying to remove the last layer so that I can use transfer Leaning.



      vgg16_model = keras.applications.vgg16.VGG16()
      model = Sequential()

      for layer in vgg16_model.layers:
      model.add(layer)

      model.layers.pop()


      # Freeze the layers
      for layer in model.layers:
      layer.trainable = False


      # Add 'softmax' instead of earlier 'prediction' layer.
      model.add(Dense(2, activation='softmax'))


      # Check the summary, and yes new layer has been added.
      model.summary()


      But the output I am getting is not what I expected. It is still showing the last layer of vgg16 model.



      Here is the output



       _________________________________________________________________
      Layer (type) Output Shape Param #
      =================================================================
      block1_conv1 (Conv2D) (None, 224, 224, 64) 1792
      _________________________________________________________________
      block1_conv2 (Conv2D) (None, 224, 224, 64) 36928

      **THE HIDDEN LAYERS**
      _________________________________________________________________
      fc1 (Dense) (None, 4096) 102764544
      _________________________________________________________________
      fc2 (Dense) (None, 4096) 16781312
      _________________________________________________________________
      predictions (Dense) (None, 1000) 4097000
      _________________________________________________________________
      dense_10 (Dense) (None, 2) 2002
      =================================================================
      Total params: 138,359,546
      Trainable params: 2,002
      Non-trainable params: 138,357,544


      Note- In the output I have not shown the whole model, just showed the first few layers and the last layers.



      How should I remove the last layer to do transfer learning??



      P.S Keras version = 2.2.4







      python keras keras-layer tf.keras






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 25 at 11:41









      markuscosinus

      1,4691 gold badge2 silver badges14 bronze badges




      1,4691 gold badge2 silver badges14 bronze badges










      asked Mar 25 at 9:59









      LuciferLucifer

      83 bronze badges




      83 bronze badges






















          2 Answers
          2






          active

          oldest

          votes


















          1
















          Just do not add the last layer to your model in the first place. This way you won't even need pop



          vgg16_model = keras.applications.vgg16.VGG16()
          model = Sequential()

          for layer in vgg16_model.layers[:-1]: # this is where I changed your code
          model.add(layer)

          # Freeze the layers
          for layer in model.layers:
          layer.trainable = False

          # Add 'softmax' instead of earlier 'prediction' layer.
          model.add(Dense(2, activation='softmax'))





          share|improve this answer
































            0














            Alternatively to markuscosinus answer, you can take the output before the prediction layer and pass it through your own prediction layer. You can do it as follows:



            for layer in vgg16_model.layers: 
            layer.trainable = False
            last_layer = vgg16_model.get_layer('fc2').output
            out = Flatten()(last_layer)
            out = Dense(128, activation='relu', name='fc3')(out)
            out = Dropout(0.5)(out)
            out = Dense(n_classes, activation='softmax', name='prediction')(out)
            vgg16_custom_model = Model(input=vgg16_model.input, output=out)


            I suggest you to add a Flatten and another Dense layer before your softmax because the last one "fc2" have 4096 nodes and it's hard to change it to 2.



            And of course, dropout before the prediction will give you better resoults.






            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%2f55335228%2fhow-to-remove-the-last-layer-from-a-pre-trained-model-i-have-tried-model-layers%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1
















              Just do not add the last layer to your model in the first place. This way you won't even need pop



              vgg16_model = keras.applications.vgg16.VGG16()
              model = Sequential()

              for layer in vgg16_model.layers[:-1]: # this is where I changed your code
              model.add(layer)

              # Freeze the layers
              for layer in model.layers:
              layer.trainable = False

              # Add 'softmax' instead of earlier 'prediction' layer.
              model.add(Dense(2, activation='softmax'))





              share|improve this answer





























                1
















                Just do not add the last layer to your model in the first place. This way you won't even need pop



                vgg16_model = keras.applications.vgg16.VGG16()
                model = Sequential()

                for layer in vgg16_model.layers[:-1]: # this is where I changed your code
                model.add(layer)

                # Freeze the layers
                for layer in model.layers:
                layer.trainable = False

                # Add 'softmax' instead of earlier 'prediction' layer.
                model.add(Dense(2, activation='softmax'))





                share|improve this answer



























                  1












                  1








                  1









                  Just do not add the last layer to your model in the first place. This way you won't even need pop



                  vgg16_model = keras.applications.vgg16.VGG16()
                  model = Sequential()

                  for layer in vgg16_model.layers[:-1]: # this is where I changed your code
                  model.add(layer)

                  # Freeze the layers
                  for layer in model.layers:
                  layer.trainable = False

                  # Add 'softmax' instead of earlier 'prediction' layer.
                  model.add(Dense(2, activation='softmax'))





                  share|improve this answer

















                  Just do not add the last layer to your model in the first place. This way you won't even need pop



                  vgg16_model = keras.applications.vgg16.VGG16()
                  model = Sequential()

                  for layer in vgg16_model.layers[:-1]: # this is where I changed your code
                  model.add(layer)

                  # Freeze the layers
                  for layer in model.layers:
                  layer.trainable = False

                  # Add 'softmax' instead of earlier 'prediction' layer.
                  model.add(Dense(2, activation='softmax'))






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 25 at 11:17

























                  answered Mar 25 at 10:40









                  markuscosinusmarkuscosinus

                  1,4691 gold badge2 silver badges14 bronze badges




                  1,4691 gold badge2 silver badges14 bronze badges























                      0














                      Alternatively to markuscosinus answer, you can take the output before the prediction layer and pass it through your own prediction layer. You can do it as follows:



                      for layer in vgg16_model.layers: 
                      layer.trainable = False
                      last_layer = vgg16_model.get_layer('fc2').output
                      out = Flatten()(last_layer)
                      out = Dense(128, activation='relu', name='fc3')(out)
                      out = Dropout(0.5)(out)
                      out = Dense(n_classes, activation='softmax', name='prediction')(out)
                      vgg16_custom_model = Model(input=vgg16_model.input, output=out)


                      I suggest you to add a Flatten and another Dense layer before your softmax because the last one "fc2" have 4096 nodes and it's hard to change it to 2.



                      And of course, dropout before the prediction will give you better resoults.






                      share|improve this answer



























                        0














                        Alternatively to markuscosinus answer, you can take the output before the prediction layer and pass it through your own prediction layer. You can do it as follows:



                        for layer in vgg16_model.layers: 
                        layer.trainable = False
                        last_layer = vgg16_model.get_layer('fc2').output
                        out = Flatten()(last_layer)
                        out = Dense(128, activation='relu', name='fc3')(out)
                        out = Dropout(0.5)(out)
                        out = Dense(n_classes, activation='softmax', name='prediction')(out)
                        vgg16_custom_model = Model(input=vgg16_model.input, output=out)


                        I suggest you to add a Flatten and another Dense layer before your softmax because the last one "fc2" have 4096 nodes and it's hard to change it to 2.



                        And of course, dropout before the prediction will give you better resoults.






                        share|improve this answer

























                          0












                          0








                          0







                          Alternatively to markuscosinus answer, you can take the output before the prediction layer and pass it through your own prediction layer. You can do it as follows:



                          for layer in vgg16_model.layers: 
                          layer.trainable = False
                          last_layer = vgg16_model.get_layer('fc2').output
                          out = Flatten()(last_layer)
                          out = Dense(128, activation='relu', name='fc3')(out)
                          out = Dropout(0.5)(out)
                          out = Dense(n_classes, activation='softmax', name='prediction')(out)
                          vgg16_custom_model = Model(input=vgg16_model.input, output=out)


                          I suggest you to add a Flatten and another Dense layer before your softmax because the last one "fc2" have 4096 nodes and it's hard to change it to 2.



                          And of course, dropout before the prediction will give you better resoults.






                          share|improve this answer













                          Alternatively to markuscosinus answer, you can take the output before the prediction layer and pass it through your own prediction layer. You can do it as follows:



                          for layer in vgg16_model.layers: 
                          layer.trainable = False
                          last_layer = vgg16_model.get_layer('fc2').output
                          out = Flatten()(last_layer)
                          out = Dense(128, activation='relu', name='fc3')(out)
                          out = Dropout(0.5)(out)
                          out = Dense(n_classes, activation='softmax', name='prediction')(out)
                          vgg16_custom_model = Model(input=vgg16_model.input, output=out)


                          I suggest you to add a Flatten and another Dense layer before your softmax because the last one "fc2" have 4096 nodes and it's hard to change it to 2.



                          And of course, dropout before the prediction will give you better resoults.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 25 at 11:06









                          EricEric

                          2831 gold badge5 silver badges16 bronze badges




                          2831 gold badge5 silver badges16 bronze badges



























                              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%2f55335228%2fhow-to-remove-the-last-layer-from-a-pre-trained-model-i-have-tried-model-layers%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

                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                              용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                              155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해