Sequential Models Weights

Overview


The sequential model is the basic model of a neural network, that is, it consists of layers of inputs, weights, an activation function, and a set of outputs, which feeds the next input.

When manipulating a tensor flow model, often you will need to extract or change the models weights. This page discusses ways to interact with a models weights.

Retrieving the Weights


After a fmodel has been fit, the weights for any layer of the model can be easily retrieved using the tensor flow util module.


let ut = await import('/lib/tensor-flow/util/v1.0.0/util.mjs');

let layer = 0;
let weights = await ut.weights(model,layer);
				
Try it!

Setting the Weights


After training a model, you may wish to extract the weights and set them back on a newly constructed model. The setWeights method lets you set the weights on a selected layer of a model. The setWeights method expects an array with two entries, the weights and the bias.

Note in this example, the first layer expects 3 inputs and has 1 output. Therefore, the weights matrix should be a 3x1 matrix.


let wmatrix = [[1],[1],[1]];
let weights = tf.tensor(wmatrix);
let bias = tf.tensor([0]);

const model = tf.sequential({
    layers:[
      tf.layers.dense({inputShape:[3],units:1,activation:'relu'}),
      tf.layers.dense({units:2,activation:'softmax'}),
    ]
  });
model.layers[0].setWeights([weights, bias]);
				
Try it!

Contents