tensorflow 获取变量&打印权值等方法

tensorflow 获取变量&打印权值等方法


在使用tensorflow中,我们常常需要获取某个变量的值,比如:打印某一层的权重,通常我们可以直接利用变量的name属性
来获取,但是当我们利用一些第三方的库来构造神经网络的layer时,存在一种情况:就是我们自己无法定义该层的变量,因为
是自动进行定义的。比如用tensorflow的slim库时:

def resnet_stack(images, output_shape, hparams, scope=None):
  """Create a resnet style transfer block.

  Args:
    images: [batch-size, height, width, channels] image tensor to feed as input
    output_shape: output image shape in form [height, width, channels]
    hparams: hparams objects
    scope: Variable scope

  Returns:
    Images after processing with resnet blocks.
  """
  end_points = {}
  if hparams.noise_channel:
    # separate the noise for visualization
    end_points['noise'] = images[:, :, :, -1]
  assert images.shape.as_list()[1:3] == output_shape[0:2]

  with tf.variable_scope(scope, 'resnet_style_transfer', [images]):
    with slim.arg_scope(
        [slim.conv2d],
        normalizer_fn=slim.batch_norm,
        kernel_size=[hparams.generator_kernel_size] * 2,
        stride=1):
      net = slim.conv2d(
          images,
          hparams.resnet_filters,
          normalizer_fn=None,
          activation_fn=tf.nn.relu)
      for block in range(hparams.resnet_blocks):
        net = resnet_block(net, hparams)
        end_points['resnet_block_{}'.format(block)] = net

      net = slim.conv2d(
          net,
          output_shape[-1],
          kernel_size=[1, 1],
          normalizer_fn=None,
          activation_fn=tf.nn.tanh,
          scope='conv_out')
      end_points['transferred_images'] = net
    return net, end_points

我们希望获取第一个卷积层的权重weight,该怎么办呢??

在训练时,这些可训练的变量会被tensorflow保存在 tf.trainable_variables() 中,于是我们就可以通过打印
tf.trainable_variables() 来获取该卷积层的名称(或者你也可以自己根据scope来看出来该变量的name ),
然后利用tf.get_default_grap().get_tensor_by_name 来获取该变量。举个简单的例子:

import tensorflow as tf
with tf.variable_scope("generate"):
    with tf.variable_scope("resnet_stack"):
        #简单起见,这里没有用第三方库来说明,
        bias = tf.Variable(0.0,name="bias")
        weight = tf.Variable(0.0,name="weight")

for tv in tf.trainable_variables():
    print (tv.name)

b = tf.get_default_graph().get_tensor_by_name("generate/resnet_stack/bias:0")
w = tf.get_default_graph().get_tensor_by_name("generate/resnet_stack/weight:0")

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    print(sess.run(b))
    print(sess.run(w))

结果如下:




### 如何在神经网络中输出权重 为了展示如何获取打印神经网络中的权重,在Python环境中通常使用深度学习框架如TensorFlow或PyTorch来构建模型。下面将以这两种流行框架为例说明具体方法。 #### 使用 TensorFlow/Keras 输出权重 当利用Keras建立好一个卷积神经网络之后,可以通过访问每一层对象的方法`get_weights()`获得该层所有的参数矩阵[^1]: ```python import tensorflow as tf from tensorflow.keras import layers, models # 构建简单的CNN模型作为例子 model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 3))) model.add(layers.MaxPooling2D((2, 2))) # 获取特定层的权重 conv_layer = model.layers[0] # 假设要查看第一个卷积层 weights = conv_layer.get_weights()[0] print("Weights shape:", weights.shape) print(weights) # 打印权重 ``` 这段代码创建了一个小型的卷积神经网络,并展示了怎样从指定的一层中提取出权重信息。注意这里只取了`get_weights()`返回列表的第一个元素,因为对于卷积层而言,这对应于滤波器(即卷积核)本身的权重;而第二个元素则是偏置项。 #### 使用 PyTorch 输出权重 如果采用的是PyTorch库,则可以直接遍历模型的各个子模块及其参数来进行操作[^2]: ```python import torch.nn as nn import torch class SimpleCNN(nn.Module): def __init__(self): super(SimpleCNN, self).__init__() self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3) def forward(self, x): pass # 此处省略forward过程定义 net = SimpleCNN() for name, param in net.named_parameters(): if 'weight' in name and 'conv' in name: print(f"{name}: {param.data}") ``` 此段脚本定义了一类简易版的卷积神经网路,并通过迭代`named_parameters()`函数枚举所有带名参数,从而定位到那些属于卷积层(`conv`)下的权重变量进行输出。 无论是哪种方式,都可以有效地帮助开发者监控和调试自己的模型架构,理解内部机制以及优化性能表现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值