卷积神经网络<二>keras实现多分支输入VGG
创始人
2024-02-07 23:33:21
0

VGG的模型图

在这里插入图片描述

在这里插入图片描述

VGG使用Keras实现

这里的代码借鉴了VGG实现Keras,但是这段代码不支持多通道,并且vgg函数的扩展性不好。下面修改一下,方便进行多分支图片输入的建立,以及更见方便的调参。

# from keras.models import
from keras.layers import *
from keras.models import Input, load_model, Sequential
from keras import Model
from keras.datasets import mnist
from keras.utils import to_categorical
from keras.losses import categorical_crossentropy
import keras.optimizers
import numpy as npdef vgg(input_shape, num_cls, filters_num, conv_nums):# print(input_shape)inputs = Input(shape=input_shape)x = inputsfor i in range(len(conv_nums)):for j in range(conv_nums[i]):x = Conv2D(filters=filters_num[i], kernel_size=3, padding='same',name='stage{0}_conv{1}'.format(i+1, j+1))(x)x = MaxPool2D((2, 2), strides=2, name='maxpool_'+str(i+1))(x)x = ZeroPadding2D((1, 1))(x)x = Flatten(name='flatten')(x)x = Dense(units=4096, name='dense4096_1')(x)x = Dense(units=4096, name='dense4096_2')(x)x = Dense(units=num_cls, name='dense1000', activation='softmax')(x)model = Model(inputs=inputs, outputs=x, name='vgg')model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['acc'])return modeldef train(net_name):path = r'C:\Users\.keras\datasets\mnist.npz'with np.load(path, allow_pickle=True) as f:x_train, y_train = f['x_train'], f['y_train']x_test, y_test = f['x_test'], f['y_test']x_train = x_train.reshape(x_train.shape[0], 28, 28, 1).astype('float32')x_test = x_test.reshape(x_test.shape[0], 28, 28, 1).astype('float32')num_classes = 10x_train = x_train / 255.x_test = x_test / 255.y_train = to_categorical(y_train, num_classes)y_test = to_categorical(y_test, num_classes)batch_size = 16epochs = 1if net_name == 'vgg-19':filters_num = [64, 128, 256, 512, 512]conv_nums = [2, 2, 4, 4, 4]else:filters_num = [32, 64, 128, 256, 512]conv_nums = [2, 2, 3, 3, 3]vgg_model = vgg(input_shape=(28, 28, 1), num_cls=num_classes, filters_num=filters_num,conv_nums=conv_nums)vgg_model.summary()vgg_model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.1)vgg_model.save('{0}-mnist.h5'.format(net_name))eval_res = vgg_model.evaluate(x_test, y_test)print(eval_res)if __name__ == '__main__':train('vgg-16')

方便调参版本

  1. 把optimizer和input等重要参数进行了封装,方便调参和调用。
  2. 建立了多分支输入函数build_multy_vgg(),方便调用。
"""
@author:fuzekun
@file:VGG_Model.py
@time:2022/11/22
@description: 定义VGG的模型进行图片的训练,首先只使用rri进行训练
"""# from keras.models import
from keras.layers import *
from keras.models import Input, load_model, Sequential
from keras import Model
from keras.datasets import mnist
from keras.utils.all_utils import to_categorical
from keras.losses import categorical_crossentropy
import keras.optimizers
import numpy as np
import tensorflow as tf
"""
这里建立模型的时候,压缩到最后就没有了,个人以为是图片太小导致的,所以240的时候可以去掉zero那一层
"""def vgg(input_shape, num_cls, filters_num, conv_nums, multy):# print(input_shape)inputs = Input(shape=input_shape)x = inputsfor i in range(len(conv_nums)):for j in range(conv_nums[i]):x = Conv2D(filters=filters_num[i], kernel_size=3, padding='same')(x)x = MaxPool2D((2, 2), strides=2)(x)if input_shape[0] < 224:x = ZeroPadding2D((1, 1))(x)x = Flatten()(x)x = Dense(units=4096)(x)x = Dense(units=4096)(x)if not multy:      # 单模型直接输出到类别x = Dense(units=num_cls, activation='softmax')(x)model = Model(inputs=inputs, outputs=x, name='vgg')return modeldef build_vgg(net_name, input_shape, num_classes, optimizer, filter_num=[], conv_nums=[], multy = False):if net_name == 'vgg-19':filters_num = [64, 128, 256, 512, 512]conv_nums = [2, 2, 4, 4, 4]else:filters_num = [32, 64, 128, 256, 512]conv_nums = [2, 2, 3, 3, 3]vgg_model = vgg(input_shape=input_shape, num_cls=num_classes, filters_num=filters_num,conv_nums=conv_nums, multy=multy)if not multy:   # 多输入的不进行编译vgg_model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['acc'])# vgg_model.summary()return vgg_model# 创建多输入的VGG模型
def build_multy_VGG(net_name, input_shape, num_classes, optimizer, n_hiddens,filter_num=[], conv_nums=[]):out_rri = build_vgg(net_name, input_shape, num_classes, optimizer, filter_num, conv_nums, True)out_edr = build_vgg(net_name, input_shape, num_classes, optimizer, filter_num, conv_nums, True)out_amp = build_vgg(net_name, input_shape, num_classes, optimizer, filter_num, conv_nums, True)# 2. 进行模型融合# print(out_rri.output)combined = concatenate([out_rri.output, out_edr.output])  # (None, 7, 7, 768)# print(combined)# 2.1融合输入x = Dense(n_hiddens, activation='relu')(combined)x = Flatten()(x)# 2.2最后输出x = Dense(num_classes, activation='softmax')(x)# 2.3模型定义完成model = Model(inputs=[out_rri.input, out_edr.input], outputs=x)model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['acc'])return modeldef train(net_name):path = r'C:\Users\.keras\datasets\mnist.npz'with np.load(path, allow_pickle=True) as f:x_train, y_train = f['x_train'], f['y_train']x_test, y_test = f['x_test'], f['y_test']x_train = x_train.reshape(x_train.shape[0], 28, 28, 1).astype('float32')x_test = x_test.reshape(x_test.shape[0], 28, 28, 1).astype('float32')num_classes = 10x_train = x_train / 255.x_test = x_test / 255.y_train = to_categorical(y_train, num_classes)y_test = to_categorical(y_test, num_classes)batch_size = 16epochs = 1lr = 0.001opt = tf.keras.optimizers.Adam(learning_rate=lr)model = build_vgg("vgg-16", input_shape=(28,28,1), num_classes=2, optimizer=opt)model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.1)model.save('{0}-mnist.h5'.format(net_name))eval_res = model.evaluate(x_test, y_test)print(eval_res)if __name__ == '__main__':train('vgg-16')

相关内容

热门资讯

喜欢穿一身黑的男生性格(喜欢穿... 今天百科达人给各位分享喜欢穿一身黑的男生性格的知识,其中也会对喜欢穿一身黑衣服的男人人好相处吗进行解...
发春是什么意思(思春和发春是什... 本篇文章极速百科给大家谈谈发春是什么意思,以及思春和发春是什么意思对应的知识点,希望对各位有所帮助,...
网络用语zl是什么意思(zl是... 今天给各位分享网络用语zl是什么意思的知识,其中也会对zl是啥意思是什么网络用语进行解释,如果能碰巧...
为什么酷狗音乐自己唱的歌不能下... 本篇文章极速百科小编给大家谈谈为什么酷狗音乐自己唱的歌不能下载到本地?,以及为什么酷狗下载的歌曲不是...
华为下载未安装的文件去哪找(华... 今天百科达人给各位分享华为下载未安装的文件去哪找的知识,其中也会对华为下载未安装的文件去哪找到进行解...
家里可以做假山养金鱼吗(假山能... 今天百科达人给各位分享家里可以做假山养金鱼吗的知识,其中也会对假山能放鱼缸里吗进行解释,如果能碰巧解...
四分五裂是什么生肖什么动物(四... 本篇文章极速百科小编给大家谈谈四分五裂是什么生肖什么动物,以及四分五裂打一生肖是什么对应的知识点,希...
怎么往应用助手里添加应用(应用... 今天百科达人给各位分享怎么往应用助手里添加应用的知识,其中也会对应用助手怎么添加微信进行解释,如果能...
客厅放八骏马摆件可以吗(家里摆... 今天给各位分享客厅放八骏马摆件可以吗的知识,其中也会对家里摆八骏马摆件好吗进行解释,如果能碰巧解决你...
美团联名卡审核成功待激活(美团... 今天百科达人给各位分享美团联名卡审核成功待激活的知识,其中也会对美团联名卡审核未通过进行解释,如果能...