szagoruyko / functional-zoo

PyTorch and Tensorflow functional model definitions
586 stars 92 forks source link

Extract features from pre-trained model #8

Open dineshbvadhia opened 7 years ago

dineshbvadhia commented 7 years ago

To extract features from an arbitrary layer with say, VGG19, given an input image "elephant.jpg", the code in keras+TF is simply:

from keras.applications.vgg19 import VGG19 from keras.preprocessing import image from keras.applications.vgg19 import preprocess_input from keras.models import Model import numpy as np

base_model = VGG19(weights='imagenet') model = Model(input=base_model.input, output=base_model.get_layer('block4_pool').output)

img_path = 'elephant.jpg'

img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x)

block4_pool_features = model.predict(x)

This can be turned into a function to support multiple calls. How is this achieved in PyTorch?

ATSEGYPT commented 7 years ago

How to get the indices of the extracted "block4_pool_features"?