pretained.py 960 B

123456789101112131415161718192021222324252627282930313233343536
  1. #%%
  2. import tensorflow as tf
  3. from tensorflow import keras
  4. from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
  5. #%%
  6. # 加载预训练网络模型,并去掉最后一层
  7. resnet = keras.applications.ResNet50(weights='imagenet',include_top=False)
  8. resnet.summary()
  9. # 测试网络的输出
  10. x = tf.random.normal([4,224,224,3])
  11. out = resnet(x)
  12. out.shape
  13. #%%
  14. # 新建池化层
  15. global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
  16. # 利用上一层的输出作为本层的输入,测试其输出
  17. x = tf.random.normal([4,7,7,2048])
  18. out = global_average_layer(x)
  19. print(out.shape)
  20. #%%
  21. # 新建全连接层
  22. fc = tf.keras.layers.Dense(100)
  23. # 利用上一层的输出作为本层的输入,测试其输出
  24. x = tf.random.normal([4,2048])
  25. out = fc(x)
  26. print(out.shape)
  27. #%%
  28. # 重新包裹成我们的网络模型
  29. mynet = Sequential([resnet, global_average_layer, fc])
  30. mynet.summary()
  31. #%%
  32. resnet.trainable = False
  33. mynet.summary()
  34. #%%