当前位置:   article > 正文

Keras —— 应用模型_keras 模型应用

keras 模型应用

Keras应用是可用的具有预训练权重的深度学习模型。这些模型可用于预测,特征提取和细调。

实例化模型时权重自动下载,储存在~/.keras/models/

可用模型

在ImageNet上预训练权重的图像分类模型有:

-Xception

-VGG16

-VGG19

-ResNet50

-InceptionV3

Xception模型只有TensorFlow版,因为它依赖于SeparableConvolution层。其他模型有TensorFlow和Theano两个版本。

图像分类模型使用举例

使用ResNet50分类图像

  1. from keras.applications.resnet50 import ResNet50
  2. from keras.preprocessing import image
  3. from keras.applications.resnet50 import preprocess_input, decode_predictions
  4. import numpy as np
  5. model = ResNet50(weights='imagenet')
  6. img_path = 'elephant.jpg'
  7. img = image.load_img(img_path, target_size=(224, 224))
  8. x = image.img_to_array(img)
  9. x = np.expand_dims(x, axis=0)
  10. x = preprocess_input(x)
  11. preds = model.predict(x)
  12. # decode the results into a list of tuples (class, description, probability)
  13. # (one such list for each sample in the batch)
  14. print('Predicted:', decode_predictions(preds, top=3)[0])
  15. # Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), (u'n01871265', u'tusker', 0.1122357), (u'n02504458', u'African_elephant', 0.061040461)]


使用VGG16提取特征

  1. from keras.applications.vgg16 import VGG16
  2. from keras.preprocessing import image
  3. from keras.applications.vgg16 import preprocess_input
  4. import numpy as np
  5. model = VGG16(weights='imagenet', include_top=False)
  6. img_path = 'elephant.jpg'
  7. img = image.load_img(img_path, target_size=(224, 224))
  8. x = image.img_to_array(img)
  9. x = np.expand_dims(x, axis=0)
  10. x = preprocess_input(x)
  11. features = model.predict(x)

从VGG19任意中间层提取特征

  1. from keras.applications.vgg19 import VGG19
  2. from keras.preprocessing import image
  3. from keras.applications.vgg19 import preprocess_input
  4. from keras.models import Model
  5. import numpy as np
  6. base_model = VGG19(weights='imagenet')
  7. model = Model(inputs=base_model.input, outputs=base_model.get_layer('block4_pool').output)
  8. img_path = 'elephant.jpg'
  9. img = image.load_img(img_path, target_size=(224, 224))
  10. x = image.img_to_array(img)
  11. x = np.expand_dims(x, axis=0)
  12. x = preprocess_input(x)
  13. block4_pool_features = model.predict(x)

在新类别上细调InceptionV3

  1. from keras.applications.inception_v3 import InceptionV3
  2. from keras.preprocessing import image
  3. from keras.models import Model
  4. from keras.layers import Dense, GlobalAveragePooling2D
  5. from keras import backend as K
  6. # create the base pre-trained model
  7. base_model = InceptionV3(weights='imagenet', include_top=False)
  8. # add a global spatial average pooling layer
  9. x = base_model.output
  10. x = GlobalAveragePooling2D()(x)
  11. # let's add a fully-connected layer
  12. x = Dense(1024, activation='relu')(x)
  13. # and a logistic layer -- let's say we have 200 classes
  14. predictions = Dense(200, activation='softmax')(x)
  15. # this is the model we will train
  16. model = Model(inputs=base_model.input, outputs=predictions)
  17. # first: train only the top layers (which were randomly initialized)
  18. # i.e. freeze all convolutional InceptionV3 layers
  19. for layer in base_model.layers:
  20. layer.trainable = False
  21. # compile the model (should be done *after* setting layers to non-trainable)
  22. model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
  23. # train the model on the new data for a few epochs
  24. model.fit_generator(...)
  25. # at this point, the top layers are well trained and we can start fine-tuning
  26. # convolutional layers from inception V3. We will freeze the bottom N layers
  27. # and train the remaining top layers.
  28. # let's visualize layer names and layer indices to see how many layers
  29. # we should freeze:
  30. for i, layer in enumerate(base_model.layers):
  31. print(i, layer.name)
  32. # we chose to train the top 2 inception blocks, i.e. we will freeze
  33. # the first 172 layers and unfreeze the rest:
  34. for layer in model.layers[:172]:
  35. layer.trainable = False
  36. for layer in model.layers[172:]:
  37. layer.trainable = True
  38. # we need to recompile the model for these modifications to take effect
  39. # we use SGD with a low learning rate
  40. from keras.optimizers import SGD
  41. model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy')
  42. # we train our model again (this time fine-tuning the top 2 inception blocks
  43. # alongside the top Dense layers
  44. model.fit_generator(...)

在定制输入张量上构建InceptionV3

  1. from keras.applications.inception_v3 import InceptionV3
  2. from keras.layers import Input
  3. # this could also be the output a different Keras model or layer
  4. input_tensor = Input(shape=(224, 224, 3)) # this assumes K.image_data_format() == 'channels_last'
  5. model = InceptionV3(input_tensor=input_tensor, weights='imagenet', include_top=True)

模型文档

Xception

keras.applications.xception.Xception(include_top=True, weights='imagenet', input_tensor=None, input_shape=None)
在ImageNet上,模型top-1验证准确率为0.790,top-5验证准确率0.945。

注意,由于依赖SeparableConvolution层,该模型只支持TensorFlow后端。此外只支持数据格式"channel_last"(高度、宽度、通道)

默认输入大小为299*299

VGG16

keras.applications.vgg16.VGG16(include_top=True, weights='imagenet', input_tensor=None, input_shape=None)
默认输入大小为224*224

VGG19

keras.applications.vgg19.VGG19(include_top=True, weights='imagenet', input_tensor=None, input_shape=None)
默认输入大小为224*224

ResNet50

keras.applications.resnet50.ResNet50(include_top=True, weights='imagenet', input_tensor=None, input_shape=None)
默认输入大小为224*224

InceptionV3

keras.applications.inception_v3.InceptionV3(include_top=True, weights='imagenet', input_tensor=None, input_shape=None)
默认输入大小为299*299






声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/103957
推荐阅读
相关标签
  

闽ICP备14008679号