Viewing the individual components in a neural network in tensorflow

Issue

Is there actually a way to view the individual components in a neural network? Suppose the code below in tensorflow. How do I view the content of each layer, neurons and weights?

# Create a `Sequential` model and add a Dense layer as the first layer.
model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=(16,)))
model.add(tf.keras.layers.Dense(32, activation='relu'))
# Now the model will take as input arrays of shape (None, 16)
# and output arrays of shape (None, 32).
# Note that after the first layer, you don't need to specify
# the size of the input anymore:
model.add(tf.keras.layers.Dense(32))
model.output_shape

Solution

You can give your layers names. Your code would look like this:

model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape=(16,)))
model.add(tf.keras.layers.Dense(32, activation='relu'), name="layer_1")
# Now the model will take as input arrays of shape (None, 16)
# and output arrays of shape (None, 32).
# Note that after the first layer, you don't need to specify
# the size of the input anymore:
model.add(tf.keras.layers.Dense(32), name="layer_1")
model.output_shape

If you do this, you can access the layer weights by doing

model.get_layer("layer_1").weights

So in this way you could print the weights of your layers.

Answered By – Marc Felix

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published