[英]How to use model architecture of pretrained models but no weights
I want to use ResNet model architecture and want to change last few layers;我想使用 ResNet model 架构并想更改最后几层; how can I only use model architecture from model zoo in Tensorflow?我怎样才能只使用 Tensorflow 中 model 动物园的 model 架构?
To use a ResNet model, you can choose a select few from tensorflow.keras.applications
including ResNet50
, ResNet101
, and ResNet152
. To use a ResNet model, you can choose a select few from tensorflow.keras.applications
including ResNet50
, ResNet101
, and ResNet152
. Then, you will need to change a few of the default arguments if you want to do transfer learning.然后,如果要进行迁移学习,则需要更改一些默认的 arguments。 For your question, you will need to set the weights
parameter equal to None
.对于您的问题,您需要将weights
参数设置为None
。 Otherwise, 'imagenet'
weights are provided.否则,会提供'imagenet'
权重。 Also, you need to set include_top
to be False
since the number of classes for your problem will likely be different from ImageNet.此外,您需要将include_top
设置为False
,因为您的问题的类数可能与 ImageNet 不同。 Finally, you will need to provide the shape of your data in input_shape
.最后,您需要在input_shape
中提供数据的形状。 This would look something like this.这看起来像这样。
base = tf.keras.applications.ResNet50(include_top=False, weights=None, input_shape=shape)
To get a summary of the model, you can do要获得 model 的摘要,您可以执行以下操作
base.summary()
To add your own head, you can use the Functional API.要添加自己的头部,您可以使用功能 API。 You will need to add an Input
layer and your own Dense
layer which will correspond to your task.您将需要添加一个Input
层和您自己的Dense
层,这将与您的任务相对应。 This could be这可能是
input = tf.keras.layers.Input(shape=shape)
base = base(input)
out = tf.keras.layers.Dense(num_classes, activation='softmax')(base)
Finally, to construct a model, you can do最后,构造一个model,你可以做
model = tf.keras.models.Model(input, out)
The Model
constructor takes 2 arguments. Model
构造函数需要 2 个 arguments。 The first being the inputs to your model, and the second being the outputs.第一个是 model 的输入,第二个是输出。 Note that calling model.summary()
will show the ResNet base as a separate layer.请注意,调用model.summary()
会将 ResNet 基础显示为单独的层。 To view all layers of the ResNet base, you can do model.layers[1].summary()
, or you can modify the code on how you built your model.要查看 ResNet 基础的所有层,您可以执行model.layers[1].summary()
,或者您可以修改有关如何构建 model 的代码。 The second way would be第二种方法是
out = tf.keras.layers.Dense(num_classes, activation='softmax')(base.output)
model = tf.keras.models.Model(base.input, out)
Now you can view all layers with just model.summary()
.现在您可以仅使用model.summary()
查看所有层。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.