tensorflow.js copy weights from one model to another

Viewed 102

Hello) Is there a best way to copy trained weights from one model to another in Tensorflow.js? Or how to convert model to string? I need to copy trained weights of model from one worker and send them to another.

1 Answers

You can get the weights of a particular layer with tf.layers.Layer.getWeights. This will return a tensor of the weights for that entire specified layer. You can set those weights with setWeights on another model.

To specify a particular layer, you can use the getLayer function. Here's an example of getting a specific layer's weights and printing them.

 tf.loadLayersModel('https://d1zv2aa70wpiur.cloudfront.net/tfjs_quant_nsfw_mobilenet/model.json')
    .then(myModel => {
      myModel.summary() // Lists layers
      const chosenLayer = myModel.getLayer('Conv_1')
      chosenLayer.getWeights()[0].print()
  })

Related