在使用tensorflow中,我们常常需要获取某个变量的值,比如:打印某一层的权重,通常我们可以直接利用变量的name属性来获取,但是当我们利用一些第三方的库来构造神经网络的layer时,存在一种情况:就是我们自己无法定义该层的变量,因为是自动进行定义的。
比如用tensorflow的slim库时:
<span style="font-size:14px;">def resnet_stack(images, output_shape, hparams, scope=None):</span><span style="font-size:14px;"> """Create a resnet style transfer block.</span><span style="font-size:14px;"></span><span style="font-size:14px;"> Args:</span><span style="font-size:14px;"> images: [batch-size, height, width, channels] image tensor to feed as input</span><span style="font-size:14px;"> output_shape: output image shape in form [height, width, channels]</span><span style="font-size:14px;"> hparams: hparams objects</span><span style="font-size:14px;"> scope: Variable scope</span><span style="font-size:14px;"></span><span style="font-size:14px;"> Returns:</span><span style="font-size:14px;"> Images after processing with resnet blocks.</span><span style="font-size:14px;"> """</span><span style="font-size:14px;"> end_points = {}</span><span style="font-size:14px;"> if hparams.noise_channel:</span><span style="font-size:14px;"> # separate the noise for visualization</span><span style="font-size:14px;"> end_points['noise'] = images[:, :, :, -1]</span><span style="font-size:14px;"> assert images.shape.as_list()[1:3] == output_shape[0:2]</span><span style="font-size:14px;"></span><span style="font-size:14px;"> with tf.variable_scope(scope, 'resnet_style_transfer', [images]):</span><span style="font-size:14px;"> with slim.arg_scope(</span><span style="font-size:14px;"> [slim.conv2d],</span><span style="font-size:14px;"> normalizer_fn=slim.batch_norm,</span><span style="font-size:14px;"> kernel_size=[hparams.generator_kernel_size] * 2,</span><span style="font-size:14px;"> stride=1):</span><span style="font-size:14px;"> net = slim.conv2d(</span><span style="font-size:14px;"> images,</span><span style="font-size:14px;"> hparams.resnet_filters,</span><span style="font-size:14px;"> normalizer_fn=None,</span><span style="font-size:14px;"> activation_fn=tf.nn.relu)</span><span style="font-size:14px;"> for block in range(hparams.resnet_blocks):</span><span style="font-size:14px;"> net = resnet_block(net, hparams)</span><span style="font-size:14px;"> end_points['resnet_block_{}'.format(block)] = net</span><span style="font-size:14px;"></span><span style="font-size:14px;"> net = slim.conv2d(</span><span style="font-size:14px;"> net,</span><span style="font-size:14px;"> output_shape[-1],</span><span style="font-size:14px;"> kernel_size=[1, 1],</span><span style="font-size:14px;"> normalizer_fn=None,</span><span style="font-size:14px;"> activation_fn=tf.nn.tanh,</span><span style="font-size:14px;"> scope='conv_out')</span><span style="font-size:14px;"> end_points['transferred_images'] = net</span><span style="font-size:14px;"> return net, end_points</span>
新闻热点
疑难解答