How to input different sized images into transfer learning network The Next CEO of Stack Overflow2019 Community Moderator ElectionTensorflow oscillating Test and Train Accuracy?Accuracy drops if more layers trainable - weirdFine tuning accuracy lower than Raw Transfer Learning AccuracyInterpreting confusion matrix and validation results in convolutional networksHow to improve loss and avoid overfittingDifficulty in choosing Hyperparameters for my CNNHow to set input for proper fit with lstm?Multi-label classification, recall and precision increase but accuracy decrease, why?Using deep learning to classify similar imagesHow to properly resize input images for transfer learning

What did we know about the Kessel run before the prologues?

What happened in Rome, when the western empire "fell"?

Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?

Make solar eclipses exceedingly rare, but still have new moons

Newlines in BSD sed vs gsed

Measuring resistivity of dielectric liquid

A Man With a Stainless Steel Endoskeleton (like The Terminator) Fighting Cloaked Aliens Only He Can See

Domestic-to-international connection at Orlando (MCO)

Do I need to write [sic] when a number is less than 10 but isn't written out?

Is this "being" usage is essential?

Can MTA send mail via a relay without being told so?

Math-accent symbol over parentheses enclosing accented symbol (amsmath)

Minecraft Executing if more than 500 entities

If the updated MCAS software needs two AOA sensors, doesn't that introduce a new single point of failure?

Why isn't the Mueller report being released completely and unredacted?

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Running a General Election and the European Elections together

Received an invoice from my ex-employer billing me for training; how to handle?

How do I align (1) and (2)?

Proper way to express "He disappeared them"

Why don't programming languages automatically manage the synchronous/asynchronous problem?

If a black hole is created from light, can this black hole then move at the speed of light?

Why, when going from special to general relativity, do we just replace partial derivatives with covariant derivatives?

Why does the flight controls check come before arming the autobrake on the A320?



How to input different sized images into transfer learning network



The Next CEO of Stack Overflow
2019 Community Moderator ElectionTensorflow oscillating Test and Train Accuracy?Accuracy drops if more layers trainable - weirdFine tuning accuracy lower than Raw Transfer Learning AccuracyInterpreting confusion matrix and validation results in convolutional networksHow to improve loss and avoid overfittingDifficulty in choosing Hyperparameters for my CNNHow to set input for proper fit with lstm?Multi-label classification, recall and precision increase but accuracy decrease, why?Using deep learning to classify similar imagesHow to properly resize input images for transfer learning










0












$begingroup$


I have been looking online for a solution but have a difficult time finding a clear enough solution. I want to know how to use transfer learning (VGG16 for example) on images that have different sizes than the images the network originally trained on (so instead of inputting images of size (224,224,3) I want to input images of size (32,32,3)).



I initially thought about just padding those images but the network may look into the black pixels and think that they mean something, and I realize that might hard the accuracy and also when I tried to do that my colab notebook collapsed.



This is my VGG-16 code:
def vgg16_model(img_rows, img_cols, channel=1, num_classes=None):



model = VGG16(weights='imagenet', include_top=True)

model.layers.pop()

model.outputs = [model.layers[-1].output]

model.layers[-1].outbound_nodes = []

x=Dense(num_classes, activation='relu')(model.output)

model=Model(model.input,x)

#To set the first 8 layers to non-trainable (weights will not be updated)

for layer in model.layers[:15]:

layer.trainable = False
for layer in model.layers[16:]:
layer.trainable=True
model_new = Sequential()
for layer in model.layers[:-1]: # just exclude last layer from copying
model_new.add(layer)
model=model_new
model.add(Dense(256,activation='relu',input_shape=(1000,)))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(10,activation='softmax'))
#model.add(Dense(1,activation='softmax'))


# Learning rate is changed to 0.001
#sgd = SGD(lr=1e-2, decay=1e-6, momentum=0.9, nesterov=True)
sgd = SGD(lr=lr,decay=decay,momentum=0.95, nesterov=True)
adam=Adam(lr=1e-5, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0001, amsgrad=True)
#model.compile(optimizer=adam, loss='binary_crossentropy',metrics=['accuracy'])
model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy'])

# checkpoint
filepath="weights-improvement-epoch:02d-val_acc:.2f.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]

return model


I would greatly appreciate if someone could write the corrected version of this code in order to enable me to insert pictures of size (32,32,3).



Thanks a lot in advance!!










share|improve this question









$endgroup$











  • $begingroup$
    Have you tried upscaling images to 224*224 ?
    $endgroup$
    – Shamit Verma
    Mar 23 at 16:39










  • $begingroup$
    Yeah, I had a hard time finding an elegant, simple way of doing that but I ended up figuring it out, thanks!
    $endgroup$
    – Keren
    Mar 24 at 19:59















0












$begingroup$


I have been looking online for a solution but have a difficult time finding a clear enough solution. I want to know how to use transfer learning (VGG16 for example) on images that have different sizes than the images the network originally trained on (so instead of inputting images of size (224,224,3) I want to input images of size (32,32,3)).



I initially thought about just padding those images but the network may look into the black pixels and think that they mean something, and I realize that might hard the accuracy and also when I tried to do that my colab notebook collapsed.



This is my VGG-16 code:
def vgg16_model(img_rows, img_cols, channel=1, num_classes=None):



model = VGG16(weights='imagenet', include_top=True)

model.layers.pop()

model.outputs = [model.layers[-1].output]

model.layers[-1].outbound_nodes = []

x=Dense(num_classes, activation='relu')(model.output)

model=Model(model.input,x)

#To set the first 8 layers to non-trainable (weights will not be updated)

for layer in model.layers[:15]:

layer.trainable = False
for layer in model.layers[16:]:
layer.trainable=True
model_new = Sequential()
for layer in model.layers[:-1]: # just exclude last layer from copying
model_new.add(layer)
model=model_new
model.add(Dense(256,activation='relu',input_shape=(1000,)))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(10,activation='softmax'))
#model.add(Dense(1,activation='softmax'))


# Learning rate is changed to 0.001
#sgd = SGD(lr=1e-2, decay=1e-6, momentum=0.9, nesterov=True)
sgd = SGD(lr=lr,decay=decay,momentum=0.95, nesterov=True)
adam=Adam(lr=1e-5, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0001, amsgrad=True)
#model.compile(optimizer=adam, loss='binary_crossentropy',metrics=['accuracy'])
model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy'])

# checkpoint
filepath="weights-improvement-epoch:02d-val_acc:.2f.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]

return model


I would greatly appreciate if someone could write the corrected version of this code in order to enable me to insert pictures of size (32,32,3).



Thanks a lot in advance!!










share|improve this question









$endgroup$











  • $begingroup$
    Have you tried upscaling images to 224*224 ?
    $endgroup$
    – Shamit Verma
    Mar 23 at 16:39










  • $begingroup$
    Yeah, I had a hard time finding an elegant, simple way of doing that but I ended up figuring it out, thanks!
    $endgroup$
    – Keren
    Mar 24 at 19:59













0












0








0





$begingroup$


I have been looking online for a solution but have a difficult time finding a clear enough solution. I want to know how to use transfer learning (VGG16 for example) on images that have different sizes than the images the network originally trained on (so instead of inputting images of size (224,224,3) I want to input images of size (32,32,3)).



I initially thought about just padding those images but the network may look into the black pixels and think that they mean something, and I realize that might hard the accuracy and also when I tried to do that my colab notebook collapsed.



This is my VGG-16 code:
def vgg16_model(img_rows, img_cols, channel=1, num_classes=None):



model = VGG16(weights='imagenet', include_top=True)

model.layers.pop()

model.outputs = [model.layers[-1].output]

model.layers[-1].outbound_nodes = []

x=Dense(num_classes, activation='relu')(model.output)

model=Model(model.input,x)

#To set the first 8 layers to non-trainable (weights will not be updated)

for layer in model.layers[:15]:

layer.trainable = False
for layer in model.layers[16:]:
layer.trainable=True
model_new = Sequential()
for layer in model.layers[:-1]: # just exclude last layer from copying
model_new.add(layer)
model=model_new
model.add(Dense(256,activation='relu',input_shape=(1000,)))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(10,activation='softmax'))
#model.add(Dense(1,activation='softmax'))


# Learning rate is changed to 0.001
#sgd = SGD(lr=1e-2, decay=1e-6, momentum=0.9, nesterov=True)
sgd = SGD(lr=lr,decay=decay,momentum=0.95, nesterov=True)
adam=Adam(lr=1e-5, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0001, amsgrad=True)
#model.compile(optimizer=adam, loss='binary_crossentropy',metrics=['accuracy'])
model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy'])

# checkpoint
filepath="weights-improvement-epoch:02d-val_acc:.2f.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]

return model


I would greatly appreciate if someone could write the corrected version of this code in order to enable me to insert pictures of size (32,32,3).



Thanks a lot in advance!!










share|improve this question









$endgroup$




I have been looking online for a solution but have a difficult time finding a clear enough solution. I want to know how to use transfer learning (VGG16 for example) on images that have different sizes than the images the network originally trained on (so instead of inputting images of size (224,224,3) I want to input images of size (32,32,3)).



I initially thought about just padding those images but the network may look into the black pixels and think that they mean something, and I realize that might hard the accuracy and also when I tried to do that my colab notebook collapsed.



This is my VGG-16 code:
def vgg16_model(img_rows, img_cols, channel=1, num_classes=None):



model = VGG16(weights='imagenet', include_top=True)

model.layers.pop()

model.outputs = [model.layers[-1].output]

model.layers[-1].outbound_nodes = []

x=Dense(num_classes, activation='relu')(model.output)

model=Model(model.input,x)

#To set the first 8 layers to non-trainable (weights will not be updated)

for layer in model.layers[:15]:

layer.trainable = False
for layer in model.layers[16:]:
layer.trainable=True
model_new = Sequential()
for layer in model.layers[:-1]: # just exclude last layer from copying
model_new.add(layer)
model=model_new
model.add(Dense(256,activation='relu',input_shape=(1000,)))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(256,activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(10,activation='softmax'))
#model.add(Dense(1,activation='softmax'))


# Learning rate is changed to 0.001
#sgd = SGD(lr=1e-2, decay=1e-6, momentum=0.9, nesterov=True)
sgd = SGD(lr=lr,decay=decay,momentum=0.95, nesterov=True)
adam=Adam(lr=1e-5, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0001, amsgrad=True)
#model.compile(optimizer=adam, loss='binary_crossentropy',metrics=['accuracy'])
model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy'])

# checkpoint
filepath="weights-improvement-epoch:02d-val_acc:.2f.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
callbacks_list = [checkpoint]

return model


I would greatly appreciate if someone could write the corrected version of this code in order to enable me to insert pictures of size (32,32,3).



Thanks a lot in advance!!







deep-learning transfer-learning






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 16:16









KerenKeren

262




262











  • $begingroup$
    Have you tried upscaling images to 224*224 ?
    $endgroup$
    – Shamit Verma
    Mar 23 at 16:39










  • $begingroup$
    Yeah, I had a hard time finding an elegant, simple way of doing that but I ended up figuring it out, thanks!
    $endgroup$
    – Keren
    Mar 24 at 19:59
















  • $begingroup$
    Have you tried upscaling images to 224*224 ?
    $endgroup$
    – Shamit Verma
    Mar 23 at 16:39










  • $begingroup$
    Yeah, I had a hard time finding an elegant, simple way of doing that but I ended up figuring it out, thanks!
    $endgroup$
    – Keren
    Mar 24 at 19:59















$begingroup$
Have you tried upscaling images to 224*224 ?
$endgroup$
– Shamit Verma
Mar 23 at 16:39




$begingroup$
Have you tried upscaling images to 224*224 ?
$endgroup$
– Shamit Verma
Mar 23 at 16:39












$begingroup$
Yeah, I had a hard time finding an elegant, simple way of doing that but I ended up figuring it out, thanks!
$endgroup$
– Keren
Mar 24 at 19:59




$begingroup$
Yeah, I had a hard time finding an elegant, simple way of doing that but I ended up figuring it out, thanks!
$endgroup$
– Keren
Mar 24 at 19:59










1 Answer
1






active

oldest

votes


















1












$begingroup$

Resizing is the best option, if they are bigger downscale them, else upscale them.






share|improve this answer








New contributor




Amita Kapoor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$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%2f47851%2fhow-to-input-different-sized-images-into-transfer-learning-network%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












    $begingroup$

    Resizing is the best option, if they are bigger downscale them, else upscale them.






    share|improve this answer








    New contributor




    Amita Kapoor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






    $endgroup$

















      1












      $begingroup$

      Resizing is the best option, if they are bigger downscale them, else upscale them.






      share|improve this answer








      New contributor




      Amita Kapoor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      $endgroup$















        1












        1








        1





        $begingroup$

        Resizing is the best option, if they are bigger downscale them, else upscale them.






        share|improve this answer








        New contributor




        Amita Kapoor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        $endgroup$



        Resizing is the best option, if they are bigger downscale them, else upscale them.







        share|improve this answer








        New contributor




        Amita Kapoor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        share|improve this answer



        share|improve this answer






        New contributor




        Amita Kapoor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        answered Mar 24 at 15:29









        Amita KapoorAmita Kapoor

        111




        111




        New contributor




        Amita Kapoor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        New contributor





        Amita Kapoor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        Amita Kapoor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.



























            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%2f47851%2fhow-to-input-different-sized-images-into-transfer-learning-network%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

            Adding axes to figuresAdding axes labels to LaTeX figuresLaTeX equivalent of ConTeXt buffersRotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?TikZ scaling graphic and adjust node position and keep font sizeNumerical conditional within tikz keys?adding axes to shapesAlign axes across subfiguresAdding figures with a certain orderLine up nested tikz enviroments or how to get rid of themAdding axes labels to LaTeX figures

            Tähtien Talli Jäsenet | Lähteet | NavigointivalikkoSuomen Hippos – Tähtien Talli

            Do these cracks on my tires look bad? The Next CEO of Stack OverflowDry rot tire should I replace?Having to replace tiresFishtailed so easily? Bad tires? ABS?Filling the tires with something other than air, to avoid puncture hassles?Used Michelin tires safe to install?Do these tyre cracks necessitate replacement?Rumbling noise: tires or mechanicalIs it possible to fix noisy feathered tires?Are bad winter tires still better than summer tires in winter?Torque converter failure - Related to replacing only 2 tires?Why use snow tires on all 4 wheels on 2-wheel-drive cars?