官网实例详解4.34(mnist_transfer_cnn.py)-keras学习笔记

迁移学习实例

Keras实例目录

代码注释

[python]  view plain  copy
  1. '''''Transfer learning toy example. 
  2. 迁移学习实例 
  3. 1 - Train a simple convnet on the MNIST dataset the first 5 digits [0..4]. 
  4. 1 - 基于MINIST数据集,训练简单卷积网络,前5个数字[0..4]. 
  5. 2 - Freeze convolutional layers and fine-tune dense layers 
  6.    for the classification of digits [5..9]. 
  7. 2 - 为[5..9]数字分类,冻结卷积层并微调全连接层 
  8.  
  9. Get to 99.8% test accuracy after 5 epochs 
  10. for the first five digits classifier 
  11. and 99.2% for the last five digits after transfer + fine-tuning. 
  12. 5个周期后,前5个数字分类测试准确率99.8% ,同时通过迁移+微调,后5个数字测试准确率99.2% 
  13. '''  
  14.   
  15. from __future__ import print_function  
  16.   
  17. import datetime  
  18. import keras  
  19. from keras.datasets import mnist  
  20. from keras.models import Sequential  
  21. from keras.layers import Dense, Dropout, Activation, Flatten  
  22. from keras.layers import Conv2D, MaxPooling2D  
  23. from keras import backend as K  
  24.   
  25. now = datetime.datetime.now  
  26.   
  27. batch_size = 128  
  28. num_classes = 5  
  29. epochs = 5  
  30.   
  31. # input image dimensions  
  32. # 输入图像维度  
  33. img_rows, img_cols = 2828  
  34. # number of convolutional filters to use  
  35. # 使用的卷积过滤器数量  
  36. filters = 32  
  37. # size of pooling area for max pooling  
  38. # 最大值池化的池化区域大小  
  39. pool_size = 2  
  40. # convolution kernel size  
  41. # 卷积核大小  
  42. kernel_size = 3  
  43.   
  44. if K.image_data_format() == 'channels_first':  
  45.     input_shape = (1, img_rows, img_cols)  
  46. else:  
  47.     input_shape = (img_rows, img_cols, 1)  
  48.   
  49.   
  50. def train_model(model, train, test, num_classes):  
  51.     x_train = train[0].reshape((train[0].shape[0],) + input_shape)  
  52.     x_test = test[0].reshape((test[0].shape[0],) + input_shape)  
  53.     x_train = x_train.astype('float32')  
  54.     x_test = x_test.astype('float32')  
  55.     x_train /= 255  
  56.     x_test /= 255  
  57.     print('x_train shape:', x_train.shape)  
  58.     print(x_train.shape[0], 'train samples')  
  59.     print(x_test.shape[0], 'test samples')  
  60.   
  61.     # convert class vectors to binary class matrices  
  62.     # 类别向量转为多分类矩阵  
  63.     y_train = keras.utils.to_categorical(train[1], num_classes)  
  64.     y_test = keras.utils.to_categorical(test[1], num_classes)  
  65.   
  66.     model.compile(loss='categorical_crossentropy',  
  67.                   optimizer='adadelta',  
  68.                   metrics=['accuracy'])  
  69.   
  70.     t = now()  
  71.     model.fit(x_train, y_train,  
  72.               batch_size=batch_size,  
  73.               epochs=epochs,  
  74.               verbose=1,  
  75.               validation_data=(x_test, y_test))  
  76.     print('Training time: %s' % (now() - t))  
  77.     score = model.evaluate(x_test, y_test, verbose=0)  
  78.     print('Test score:', score[0])  
  79.     print('Test accuracy:', score[1])  
  80.   
  81.   
  82. # the data, shuffled and split between train and test sets  
  83. # 筛选(数据顺序打乱)、划分训练集和测试集  
  84. (x_train, y_train), (x_test, y_test) = mnist.load_data()  
  85.   
  86. # create two datasets one with digits below 5 and one with 5 and above  
  87. # 创建2个数据集,一个数字小于5,另一个数学大于等与5  
  88. x_train_lt5 = x_train[y_train < 5]  
  89. y_train_lt5 = y_train[y_train < 5]  
  90. x_test_lt5 = x_test[y_test < 5]  
  91. y_test_lt5 = y_test[y_test < 5]  
  92.   
  93. x_train_gte5 = x_train[y_train >= 5]  
  94. y_train_gte5 = y_train[y_train >= 5] - 5  
  95. x_test_gte5 = x_test[y_test >= 5]  
  96. y_test_gte5 = y_test[y_test >= 5] - 5  
  97.   
  98. # define two groups of layers: feature (convolutions) and classification (dense)  
  99. # 定义2组层:特征(卷积)和分类(全连接)  
  100. feature_layers = [  
  101.     Conv2D(filters, kernel_size,  
  102.            padding='valid',  
  103.            input_shape=input_shape),  
  104.     Activation('relu'),  
  105.     Conv2D(filters, kernel_size),  
  106.     Activation('relu'),  
  107.     MaxPooling2D(pool_size=pool_size),  
  108.     Dropout(0.25),  
  109.     Flatten(),  
  110. ]  
  111.   
  112. classification_layers = [  
  113.     Dense(128),  
  114.     Activation('relu'),  
  115.     Dropout(0.5),  
  116.     Dense(num_classes),  
  117.     Activation('softmax')  
  118. ]  
  119.   
  120. # create complete model  
  121. # 创建完整模型  
  122. model = Sequential(feature_layers + classification_layers)  
  123.   
  124. # train model for 5-digit classification [0..4]  
  125. # 为5数字分类[0..4]训练模型  
  126. train_model(model,  
  127.             (x_train_lt5, y_train_lt5),  
  128.             (x_test_lt5, y_test_lt5), num_classes)  
  129.   
  130. # freeze feature layers and rebuild model  
  131. # 冻结特征层并重建模型  
  132. for l in feature_layers:  
  133.     l.trainable = False  
  134.   
  135. # transfer: train dense layers for new classification task [5..9]  
  136. # 迁移:训练全连接层为[5..9]分类任务  
  137. train_model(model,  
  138.             (x_train_gte5, y_train_gte5),  
  139.             (x_test_gte5, y_test_gte5), num_classes)  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值