Extract feature using pytorch

I need to write a code using PyTorch to extract features like this one

def extract_features(image):
    feature_extractor = models[config.base_model_name]["model"](
        include_top=False, weights="imagenet"
    )

    print(feature_extractor.summary())
    if config.pooling != "avg":
        feature_extractor = tf.keras.Model(
            feature_extractor.input,
            tf.keras.layers.AveragePooling2D(int(config.pooling[0]))(
                feature_extractor.output
            ),
        )

I tried this one


model.head = nn.Identity()
model.eval()
def extract_features(directory):
    results = []
    preprocess = T.Compose([
        T.Resize(256, interpolation=3),
        T.CenterCrop(224),
        T.ToTensor(),
        T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
    ])
    for name in listdir(directory):
        filename=directory + '/' + name
        image= load_img(filename)
        vector=model(preprocess(image))

but the averaging pool I don’t use, how can I apply it with PyTorch, or does the Keras function extract features from the layer before classification only?

Could you show which exact model are you using and which layers do you want to remove? According to classic implementation of the Style Transferring (which i believe is very similar to your problem), features are extracted from various depths of the model. But you might require another approach.

Please do, print(model) and describe your problem better.

I’m using the ResNet50 model and I need to remove the last layer which is for classification as I need to extract the features for the images before classifying them. but i found this code for extract features of medical images

def extract_features(image):
    feature_extractor = models[config.base_model_name]["model"](
        include_top=False, weights="imagenet"
    )

    print(feature_extractor.summary())
    if config.pooling != "avg":
        feature_extractor = tf.keras.Model(
            feature_extractor.input,
            tf.keras.layers.AveragePooling2D(int(config.pooling[0]))(
                feature_extractor.output
            ),
        )

so I compared what I’m using for the code I saw and found that difference, does that make changes in the features I extract or not