使用keras实现densenet和Xception的模型融合

我正在参加天池上的一个竞赛,刚开始用的是DenseNet121但是效果没有达到预期,因此开始尝试使用模型融合,将Desenet和Xception融合起来共同提取特征。

代码如下:

def Multimodel(cnn_weights_path=None,all_weights_path=None,class_num=5,cnn_no_vary=False):
	'''
	获取densent121,xinception并联的网络
	此处的cnn_weights_path是个列表是densenet和xception的卷积部分的权值
	'''
	input_layer=Input(shape=(224,224,3))
	dense=DenseNet121(include_top=False,weights=None,input_shape=(224,224,3))
	xception=Xception(include_top=False,weights=None,input_shape=(224,224,3))
	#res=ResNet50(include_top=False,weights=None,input_shape=(224,224,3))

	if cnn_no_vary:
		for i,layer in enumerate(dense.layers):
			dense.layers[i].trainable=False
		for i,layer in enumerate(xception.layers):
			xception.layers[i].trainable=False
		#for i,layer in enumerate(res.layers):
		#	res.layers[i].trainable=False

	if cnn_weights_path!=None:
		dense.load_weights(cnn_weights_path[0])
		xception.load_weights(cnn_weights_path[1])
		#res.load_weights(cnn_weights_path[2])
	dense=dense(input_layer)
	xception=xception(input_layer)

	#对dense_121和xception进行全局最大池化
	top1_model=GlobalMaxPooling2D(data_format='channels_last')(dense)
	top2_model=GlobalMaxPooling2D(data_format='channels_last')(xception)
	#top3_model=GlobalMaxPool2D(input_shape=res.output_shape)(res.outputs[0])

	print(top1_model.shape,top2_model.shape)
	#把top1_model和top2_model连接起来
	t=keras.layers.Concatenate(axis=1)([top1_model,top2_model])
	#第一个全连接层
	top_model=Dense(units=512,activation="relu")(t)
	top_model=Dropout(rate=0.5)(top_model)
	top_model=Dense(units=class_num,activation="softmax")(top_model)

	model=Model(inputs=input_layer,outputs=top_model)

	#加载全部的参数
	if all_weights_path:
		model.load_weights(all_weights_path)
	return model

如下进行调用:

if __name__=="__main__":
 weights_path=["./densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5",
 "xception_weights_tf_dim_ordering_tf_kernels_notop.h5"]
 model=Multimodel(cnn_weights_path=weights_path,class_num=6)
 plot_model(model,to_file="G:/model.png")

最后生成的模型图如下:有点长,可以不看

需要注意的一点是,如果dense=dense(input_layer)这里报错的话,说明你用的是tensorflow1.4以下的版本,解决的方法就是

1、升级tensorflow到1.4以上

2、改代码:

def Multimodel(cnn_weights_path=None,all_weights_path=None,class_num=5,cnn_no_vary=False):
	'''
	获取densent121,xinception并联的网络
	此处的cnn_weights_path是个列表是densenet和xception的卷积部分的权值
	'''
	dir=os.getcwd()
	input_layer=Input(shape=(224,224,3))

	dense=DenseNet121(include_top=False,weights=None,input_tensor=input_layer,
		input_shape=(224,224,3))
	xception=Xception(include_top=False,weights=None,input_tensor=input_layer,
		input_shape=(224,224,3))
	#res=ResNet50(include_top=False,weights=None,input_shape=(224,224,3))

	if cnn_no_vary:
		for i,layer in enumerate(dense.layers):
			dense.layers[i].trainable=False
		for i,layer in enumerate(xception.layers):
			xception.layers[i].trainable=False
		#for i,layer in enumerate(res.layers):
		#	res.layers[i].trainable=False
	if cnn_weights_path!=None:
		dense.load_weights(cnn_weights_path[0])
		xception.load_weights(cnn_weights_path[1])

	#print(dense.shape,xception.shape)
	#对dense_121和xception进行全局最大池化
	top1_model=GlobalMaxPooling2D(input_shape=(7,7,1024),data_format='channels_last')(dense.output)
	top2_model=GlobalMaxPooling2D(input_shape=(7,7,1024),data_format='channels_last')(xception.output)
	#top3_model=GlobalMaxPool2D(input_shape=res.output_shape)(res.outputs[0])

	print(top1_model.shape,top2_model.shape)
	#把top1_model和top2_model连接起来
	t=keras.layers.Concatenate(axis=1)([top1_model,top2_model])
	#第一个全连接层
	top_model=Dense(units=512,activation="relu")(t)
	top_model=Dropout(rate=0.5)(top_model)
	top_model=Dense(units=class_num,activation="softmax")(top_model)

	model=Model(inputs=input_layer,outputs=top_model)

	#加载全部的参数
	if all_weights_path:
		model.load_weights(all_weights_path)
	return model

这个bug我也是在服务器上跑的时候才出现的,找了半天,而实验室的cuda和cudnn又改不了,tensorflow无法升级,因此只能改代码了。

如下所示,是最后画出的模型图:(很长,底下没内容了)

以上这篇使用keras实现densenet和Xception的模型融合就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 在keras下实现多个模型的融合方式

    在网上搜过发现关于keras下的模型融合框架其实很简单,奈何网上说了一大堆,这个东西官方文档上就有,自己写了个demo: # Function:基于keras框架下实现,多个独立任务分类 # Writer: PQF # Time: 2019/9/29 import numpy as np from keras.layers import Input, Dense from keras.models import Model import tensorflow as tf # 生成训练集 data

  • 使用Keras预训练模型ResNet50进行图像分类方式

    Keras提供了一些用ImageNet训练过的模型:Xception,VGG16,VGG19,ResNet50,InceptionV3.在使用这些模型的时候,有一个参数include_top表示是否包含模型顶部的全连接层,如果包含,则可以将图像分为ImageNet中的1000类,如果不包含,则可以利用这些参数来做一些定制的事情. 在运行时自动下载有可能会失败,需要去网站中手动下载,放在"~/.keras/models/"中,使用WinPython则在"settings/.ke

  • Keras使用ImageNet上预训练的模型方式

    我就废话不多说了,大家还是直接看代码吧! import keras import numpy as np from keras.applications import vgg16, inception_v3, resnet50, mobilenet #Load the VGG model vgg_model = vgg16.VGG16(weights='imagenet') #Load the Inception_V3 model inception_model = inception_v3.I

  • 关于Keras Dense层整理

    我就废话不多说了,大家还是直接看代码吧! ''' Created on 2018-4-4 ''' keras.layers.core.Dense( units, #代表该层的输出维度 activation=None, #激活函数.但是默认 liner use_bias=True, #是否使用b kernel_initializer='glorot_uniform', #初始化w权重,keras/initializers.py bias_initializer='zeros', #初始化b权重 k

  • 使用keras实现densenet和Xception的模型融合

    我正在参加天池上的一个竞赛,刚开始用的是DenseNet121但是效果没有达到预期,因此开始尝试使用模型融合,将Desenet和Xception融合起来共同提取特征. 代码如下: def Multimodel(cnn_weights_path=None,all_weights_path=None,class_num=5,cnn_no_vary=False): ''' 获取densent121,xinception并联的网络 此处的cnn_weights_path是个列表是densenet和xce

  • keras实现调用自己训练的模型,并去掉全连接层

    其实很简单 from keras.models import load_model base_model = load_model('model_resenet.h5')#加载指定的模型 print(base_model.summary())#输出网络的结构图 这是我的网络模型的输出,其实就是它的结构图 _________________________________________________________________________________________________

  • keras 解决加载lstm+crf模型出错的问题

    错误展示 new_model = load_model("model.h5") 报错: 1.keras load_model valueError: Unknown Layer :CRF 2.keras load_model valueError: Unknown loss function:crf_loss 错误修改 1.load_model修改源码:custom_objects = None 改为 def load_model(filepath, custom_objects, c

  • Keras实现DenseNet结构操作

    DenseNet结构在16年由Huang Gao和Liu Zhuang等人提出,并且在CVRP2017中被评为最佳论文.网络的核心结构为如下所示的Dense块,在每一个Dense块中,存在多个Dense层,即下图所示的H1-H4.各Dense层之间彼此均相互连接,即H1的输入为x0,输出为x1,H2的输入即为[x0, x1],输出为x2,依次类推.最终Dense块的输出即为[x0, x1, x2, x3, x4].这种结构个人感觉非常类似生物学里边的神经元连接方式,应该能够比较有效的提高了网络中

  • keras读取训练好的模型参数并把参数赋值给其它模型详解

    介绍 本博文中的代码,实现的是加载训练好的模型model_halcon_resenet.h5,并把该模型的参数赋值给两个不同的新的model. 函数式模型 官网上给出的调用一个训练好模型,并输出任意层的feature. model = Model(inputs=base_model.input, outputs=base_model.get_layer('block4_pool').output) 但是这有一个问题,就是新的model,如果输入inputs和训练好的model的inputs大小不

  • Python实现Keras搭建神经网络训练分类模型教程

    我就废话不多说了,大家还是直接看代码吧~ 注释讲解版: # Classifier example import numpy as np # for reproducibility np.random.seed(1337) # from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Act

  • 浅谈keras.callbacks设置模型保存策略

    如下所示: keras.callbacks.ModelCheckpoint(self.checkpoint_path, verbose=0, save_weights_only=True,mode="max",save_best_only=True), 默认是每一次poch,但是这样硬盘空间很快就会被耗光. 将save_best_only 设置为True使其只保存最好的模型,值得一提的是其记录的acc是来自于一个monitor_op,其默认为"val_loss",其

  • Keras中的两种模型:Sequential和Model用法

    在Keras中有两种深度学习的模型:序列模型(Sequential)和通用模型(Model).差异在于不同的拓扑结构. 序列模型 Sequential 序列模型各层之间是依次顺序的线性关系,模型结构通过一个列表来制定. from keras.models import Sequential from keras.layers import Dense, Activation layers = [Dense(32, input_shape = (784,)), Activation('relu')

  • keras的三种模型实现与区别说明

    前言 一.keras提供了三种定义模型的方式 1. 序列式(Sequential) API 序贯(sequential)API允许你为大多数问题逐层堆叠创建模型.虽然说对很多的应用来说,这样的一个手法很简单也解决了很多深度学习网络结构的构建,但是它也有限制-它不允许你创建模型有共享层或有多个输入或输出的网络. 2. 函数式(Functional) API Keras函数式(functional)API为构建网络模型提供了更为灵活的方式. 它允许你定义多个输入或输出模型以及共享图层的模型.除此之外

随机推荐