Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get CNN kernel values in Tensorflow

Tags:

tensorflow

I am using the code below to create CNN layers.

conv1 = tf.layers.conv2d(inputs = input, filters = 20, kernel_size = [3,3],
    padding = "same", activation = tf.nn.relu)

and I want to get the values of all kernels after training. It does not work it I simply do

kernels = conv1.kernel

So how should I retrieve the value of these kernels? I am also not sure what variables and method does conv2d has since tensorflow don't really tell it in conv2d class.

like image 950
Ziyi Zhu Avatar asked Apr 06 '17 02:04

Ziyi Zhu


1 Answers

You can find all the variables in list returned by tf.global_variables() and easily lookup for variable you need.

If you wish to get these variables by name, declare a layer as:

conv_layer_1 = tf.layers.conv2d(activation=tf.nn.relu, 
                                filters=10, 
                                inputs=input_placeholder, 
                                kernel_size=(3, 3), 
                                name="conv1",         # NOTE THE NAME 
                                padding="same", 
                                strides=(1, 1))

Recover the graph as:

gr = tf.get_default_graph()

Recover the kernel values as:

conv1_kernel_val = gr.get_tensor_by_name('conv1/kernel:0').eval()

Recover the bias values as:

conv1_bias_val = gr.get_tensor_by_name('conv1/bias:0').eval()
like image 166
KrnTneJa Avatar answered Sep 18 '22 13:09

KrnTneJa