迁移学习之利用keras预训练网络提取图片特征

      keras是基于python的深度学习的库,其中封装了多种基于ImageNet训练的预训练模型,非常适合进行迁移学习。

      keras的安装方法网上有很多教程,作者是直接pip install keras的,方便快捷。

      一般来说,进行迁移学习最简单的方式有三种,一种是直接利用预训练模型;第二种是在预训练模型的基础上进行参数的微调;第三种则是将与训练神经网络的最顶层(也就是分类层)去除,将剩下的部分看作是一个特征提取器,用于提取数据特征。        利用预训练神经网络提取图片特征的代码如下(以VGG19为例),如果需要调用别的模型则只需更改相应的模型名称即可,最终将每一幅图片的全连接层特征保存为一个txt文件存储在指定路径中,用于后续操作,非常方便。

# -*- coding: utf-8 -*-
"""
Created on Mon Nov 12 21:35:24 2018

@author: 13260
"""
import os
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 




def feature_extraction(filename,save_path):
    model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc2').output)
    img_path = filename 
    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)
    fc2 = model.predict(x)     // 获取VGG19全连接层特征
    np.savetxt(save_path +'.txt',fc2,fmt='%s') // 保存特征文件
    
def read_image(rootdir,save_path):
    list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
    # print(list)
    # files = []
    for i in range(0,len(list)):
        path = os.path.join(rootdir,list[i])
        # print(path)
        # subFiles = []
        for file in os.listdir(path):
            # subFiles.append(file)
            savePath = os.path.join(save_path,file[:-4])
            #print(file)
            filename = os.path.join(path,file)
            feature_extraction(filename,savePath)
            print("successfully saved "+ file[:-4] +".txt !")

    
if __name__ == '__main__':
    base_model = VGG19(weights='imagenet', include_top=True) //加载VGG19模型及参数
    print("Model has been onload !")
    rootdir = 'F:/shiyan/TensorFlow/retrain/data/train'  //图片路径
    save_path = "F:/python/VGG19_feature"   // 提取特征文件保存路径
    read_image(rootdir,save_path)
    print("work has been done !")
    
    
      
              
发布了50 篇原创文章 · 获赞 5 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_31207499/article/details/84294790