简体   繁体   English

如何将 tensorflow.keras 模型移动到 GPU

[英]How to move a tensorflow.keras model to GPU

Let's say I have a keras model like this:假设我有一个像这样的 keras 模型:

with tf.device("/CPU"):
    model = tf.keras.Sequential([
    # Adds a densely-connected layer with 64 units to the model:
    tf.keras.layers.Dense(64, activation='relu', input_shape=(32,)),
    # Add another:
    tf.keras.layers.Dense(64, activation='relu'),
    # Add a softmax layer with 10 output units:
    tf.keras.layers.Dense(10, activation='softmax')])

I would like to move this model to GPU.我想将此模型移至 GPU。

I tried doing this:我尝试这样做:

with tf.device("/GPU:0"):
    gpu_model = tf.keras.models.clone_model(model)

But the problem with this is that, the variable names change.但问题在于,变量名称会发生​​变化。 For example:例如:

The first layer's weight's name of model is: Got from model.layers[0].weights[0].name的第一层的权重的姓名model是:得到了来自model.layers[0].weights[0].name

'dense/kernel:0' '密集/内核:0'

But the first layer's weight's name of gpu_model is: Got from gpu_model.layers[0].weights[0].name但是gpu_model的第一层权重的名称是:Got from gpu_model.layers[0].weights[0].name

'dense_3/kernel:0' 'dense_3/内核:0'

How can I do this GPU transformation while also preserving the names of the variables?如何在保留变量名称的同时进行 GPU 转换?

I don't want to save the model to disk and load again我不想将模型保存到磁盘并再次加载

I am answering my own question.我正在回答我自己的问题。 If someone has a better solution.如果有人有更好的解决方案。 Kindly post it请张贴

This is a work around I found:这是我发现的一项工作:

  1. Create a state_dict like PyTorch创建一个类似 PyTorch 的 state_dict
  2. Get the model architecture as JSON以 JSON 形式获取模型架构
  3. Clear the Keras session and delete the model instance清除 Keras 会话并删除模型实例
  4. Create a new model from the JSON within tf.device contexttf.device上下文中从 JSON 创建一个新模型
  5. Load the previous weights from state_dict从 state_dict 加载之前的权重
state_dict = {}
for layer in model.layers:
    for weight in layer.weights:
        state_dict[weight.name] = weight.numpy()

model_json_config = model.to_json()
tf.keras.backend.clear_session() # this is crucial to get previous names again
del model

with tf.device("/GPU:0"):
    new_model = tf.keras.models.model_from_json(model_json_config)

for layer in new_model.layers:
    current_layer_weights = []
    for weight in layer.weights:
        current_layer_weights.append(state_dict[weight.name])
    layer.set_weights(current_layer_weights)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Keras模型到tensorflow.keras - Keras model to tensorflow.keras 如何在 tensorflow.keras 模型指标中使用 sklearn AUC? - how to use sklearn AUC in tensorflow.keras model metrics? 如何解决 tensorflow.keras 中的值错误? - how to solve Value Error in tensorflow.keras? 每 10 个 epoch 保存一次模型 tensorflow.keras v2 - Save model every 10 epochs tensorflow.keras v2 将输入输入到 tensorflow.keras model 的中间层 - Feed input to intermediate layer of tensorflow.keras model tensorflow.keras model 具有多个不同形状的输入(错误) - tensorflow.keras model with multiple inputs with different shapes (Error) 如何在`tensorflow.keras`中替换`keras.layers.merge._Merge` - How to substitute `keras.layers.merge._Merge` in `tensorflow.keras` In Tensorflow.keras 2.0, when a model has multiple outputs, how to define a flexible loss function for model.fit()? - In Tensorflow.keras 2.0, when a model has multiple outputs, how to define a flexible loss function for model.fit()? 如何将自定义数据生成器输入到 model.fit 中,它会生成 X,y 和一个额外的数组,到 tensorflow.keras Z20F4ZF011622Z Z20F4ZF35E630DAF39466 - How to input custom data generator into model.fit, which generates X,y and one additional array, into tensorflow.keras model? 如何在训练期间替换损失函数 tensorflow.keras - How to replace loss function during training tensorflow.keras
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM