卷积神经网络迁移学习代码.py
.
└── 找例子网_kerastrans1.py
0 directories, 1 file
# -*- coding: utf-8 -*-
import os from keras.utils
import plot_model from keras.applications.resnet50
import ResNet50 from keras.applications.vgg19
import VGG19 from keras.applications.inception_v3
import InceptionV3 from efficientnet.keras
import EfficientNetB0 # from keras.applications.nasnetmobile
import NASNetMobile # #每个网络要求的输入形状大小: # EfficientNetB0 - (224, 224, 3) # EfficientNetB1 - (240, 240, 3) # EfficientNetB2 - (260, 260, 3 # EfficientNetB3 - (300, 300, 3) # EfficientNetB4 - (380, 380, 3) # EfficientNetB5 - (456, 456, 3) # EfficientNetB6 - (528, 528, 3) # EfficientNetB7 - (600, 600, 3) from keras.layers import Dense, Flatten, GlobalAveragePooling2D,BatchNormalization,regularizers,Dropout,Input,GlobalAveragePooling1D,Reshape,Activation,multiply from keras.models import Model, load_model from keras.optimizers import SGD from keras.preprocessing.image import ImageDataGenerator import matplotlib.pyplot as plt import tensorflow as tf from keras import backend as K class PowerTransferMode: # 数据准备 def DataGen(self, dir_path, img_row, img_col, batch_size, is_train): #image_size, image_size, batch_size, True) if is_train: datagen = ImageDataGenerator(rescale=1. / 255, #随机偏移、转动等变换图像处理 zoom_range=0.25, rotation_range=15., channel_shift_range=25., width_shift_range=0.02, height_shift_range=0.02, horizontal_flip=True, fill_mode='constant') else: datagen = ImageDataGenerator(rescale=1. / 255,rotation_range=15.) generator = datagen.flow_from_directory( #返回一个生成 (x, y) 元组的 DirectoryIterator,其中 x 是一个包含一批尺寸为 (batch_size, *target_size, # channels)的图像的 Numpy 数组,y 是对应标签的 Numpy 数组 dir_path, target_size=(img_row, img_col), batch_size=batch_size, # batch_size = 32 # class_mode='binary', shuffle=True) return generator # ResNet模型 def ResNet50_model(self, lr=0.005, decay=1e-6, momentum=0.9, nb_classes=3, img_rows=224, img_cols=224, RGB=True, is_plot_model=False): color = 3 if RGB else 1 base_model = ResNet50(weights='imagenet', include_top=False,layers=tf.keras.layers, pooling=None, input_shape=(img_rows, img_cols, color), classes=nb_classes) # 冻结base_model所有层,这样就可以正确获得bottleneck特征 # for layer in base_model.layers: # layer.trainable = False # for i, layer in enumerate(base_model.layers): # print(i, layer.name) for layer in base_model.layers[:121]: #解冻第N层 layer.trainable = False for layer in base_model.layers[121:]: layer.trainable = True K.set_learning_phase(0) Inp = Input((224, 224, 3)) K.set_learning_phase(1) x = base_model(Inp) # 添加自己的全链接分类层 #x = Flatten()(x) #只用这个 loss 8.6 acc 0.5 改后无改善 x = GlobalAveragePooling2D()(x) # x = BatchNormalization()(x) x = Dropout(0.02)(x) x = Dense(1024,kernel_regularizer=regularizers.l2(0.01), activation='relu')(x) # x = BatchNormalization()(x) predictions = Dense(nb_classes, activation='softmax')(x) # 训练模型 model = Model(inputs=Inp, outputs=predictions) sgd = SGD(lr=lr, decay=decay, momentum=momentum, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) # 绘制模型 if is_plot_model: plot_model(model, to_file='resnet50_model.png', show_shapes=True) return model
评论