resnet18 用imagenet预训练好的模型 提取fc之前的特征 仅输出数据

该博客介绍了如何利用Python和torch库,通过预训练的ResNet18模型提取图像在全连接层前的特征,并将这些特征保存到文件中。首先,对图像进行预处理,然后加载预训练模型并替换其全连接层,接着对图像进行前向传播,得到特征向量,最后将特征向量保存为CSV文件。
摘要由CSDN通过智能技术生成
# -*- coding: utf-8 -*-
''' resnet18 用imagenet预训练好的模型 提取fc之前的特征 仅输出数据'''
import os.path
import torch
import torch.nn as nn
from torchvision import models, transforms
from torch.autograd import Variable
import numpy as np
from PIL import Image
import warnings
warnings.filterwarnings("ignore")

features_dir = 'D:/'

img_path = "./A.jpg"
file_name = img_path.split('/')[-1]
feature_path = os.path.join(features_dir, file_name + '.txt')

print(feature_path)

transform1 = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor()]
)

img = Image.open(img_path)
img1 = transform1(img)

# print(img1)

resnet18_feature_extractor = models.resnet18(pretrained=False)
resnet18_feature_extractor.load_state_dict(torch.load('./resnet18-f37072fd.pth'))
resnet18_feature_extractor.fc = nn.Linear(512, 512)
torch.nn.init.eye(resnet18_feature_
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值