我有一个用于转移学习的网络,并且想在两个GPU上进行训练。到目前为止,我只接受过一种培训,并且正在寻找加快速度的方法。关于如何最有效地使用它,我得到了矛盾的答案。
strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0","/gpu:1"])
with strategy.scope():
base_model = MobileNetV2(weights='imagenet',include_top=False,input_shape=(200,200,3))
x = base_model.output
x = GlobalAveragePooling2D(name="class_pool")(x)
x = Dense(1024,activation='relu',name="class_dense1")(x)
types = Dense(20,activation='softmax',name='Class')(x)
model = Model(inputs=base_model.input,outputs=[types])
然后我设置了可训练的图层:
for layer in model.layers[:160]:
layer.trainable=False
for layer in model.layers[135:]:
layer.trainable=True
然后我编译
optimizer = Adam(learning_rate=.0000001)
model.compile(optimizer=optimizer,loss='categorical_crossentropy',metrics='accuracy')
是否应将所有内容嵌套在strategy.scope()
中?
此tutorial显示compile
在内部,但此tutorial显示其在外部。
第一个显示在外面
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1,input_shape=(1,))])
model.compile(loss='mse',optimizer='sgd')
但是在之后说
在此示例中,我们使用了MirroredStrategy,因此我们可以在具有多个GPU的计算机上运行它。 strategy.scope()向Keras指示使用哪种策略来分发培训。在此范围内创建模型/优化器/指标可以使我们创建分布式变量而不是常规变量。设置好之后,您就可以像平时一样适应模型。 MirroredStrategy负责在可用的GPU上复制模型的训练,汇总渐变等。