基于Keras的inception_v3猫狗识别迁移学习

话不多说,直接上代码;

#1-加载数据
from keras.applications.inception_v3 import preprocess_input
from keras.preprocessing.image import ImageDataGenerator

IMSIZE=299
validation_generator=ImageDataGenerator(
    preprocessing_function=preprocess_input).flow_from_directory(
    'data/validation',
    target_size=(IMSIZE,IMSIZE),
    batch_size=10,
    class_mode='categorical')

train_generator=ImageDataGenerator(
    preprocessing_function=preprocess_input,
    shear_range=0.5,
    rotation_range=30,
    zoom_range=0.2,
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True).flow_from_directory(
    'data/train',
    target_size=(IMSIZE, IMSIZE),
    batch_size=5,
    class_mode='categorical'
)
from keras.applications.inception_v3 import InceptionV3
from keras.layers import GlobalAveragePooling2D,Dense,Activation
from keras import Model

base_model=InceptionV3(weights='imagenet',include_top=False)
x=base_model.output
x=GlobalAveragePooling2D()(x)
predictions=Dense(2,activation='softmax')(x)
model=Model(inputs=base_model.input,outputs=predictions)
for layer in base_model.layers:
    layer.trainable=False
model.summary()
##-------------------
from keras.optimizers import Adam
model.compile(loss='categorical_crossentropy',optimizer=Adam(lr=0.001),metrics=['accuracy'])
model.fit_generator(train_generator,epochs=100,validation_data=validation_generator)

你可能感兴趣的:(keras,迁移学习,深度学习)