paddlepaddle中动态图查看训练参数(一)

用Paddle动态图model,搭建一个神经网络,一共两层
paddlepaddle中动态图查看训练参数(一)_第1张图片

class tryNet(Layer):
    
    def __init__(self, start_node, mid_node):
        super(tryNet,self).__init__()

        self.line1 = Linear(input_dim=start_node, output_dim=mid_node, bias_attr=False, act='sigmoid', param_attr=fluid.initializer.TruncatedNormal(loc=0.0, scale=1.0, seed=824))
        self.line2 = Linear(input_dim=mid_node, output_dim=10, bias_attr=False, act='softmax', param_attr=fluid.initializer.TruncatedNormal(loc=0.0, scale=1.0, seed=824))
    
    def forward(self, img):
        
        line1 = self.line1(img)
        line2 = self.line2(line1)

        return line2

接下来要在上下文with fluid.dygraph.guard():里运行,对吧

with fluid.dygraph.guard():

    model = tryNet(start_node=start_node,  mid_node=node_num)
    model.train()
	
	XX代码段

可以用model.parameters函数来打印,该函数会返回一个列表,列表里的元素就是参数:

[ name linear_0.w_0, dtype: VarType.FP32 shape: [2, 1] 	lod: {}
	dim: 2, 1
	layout: NCHW
	dtype: float
	data: [-1.74573 -1.36293]
  
, name linear_1.w_0, dtype: VarType.FP32 shape: [1, 10] 	lod: {}
	dim: 1, 10
	layout: NCHW
	dtype: float
	data: [-1.74573 -1.36293 0.0348112 0.46533 0.230513 -0.486594 -0.39247 1.53845 0.328022 0.377883]
]

打印一下元素的种类

>>> type(model.parameters()[0])
paddle.fluid.framework.ParamBase

在稍微看两个方法,我就不解释了,直接看看例子就懂:

>>> model.parameters()[0].numpy()
array([[-1.7457268],
       [-1.3629342]], dtype=float32)

>>> model.parameters()[0].shape
[2, 1]

>>> model.parameters()[0].name        # 介个名字是paddle给你命名的, 你可以在搭建的时候命名
'linear_0.w_0'

>>> model.parameters()[0].dtype
VarType.FP32

>>> model.parameters()[0].value
bound method PyCapsule.value of name linear_0.w_0, dtype: VarType.FP32 shape: [2, 1] 	lod: {}
	dim: 2, 1
	layout: NCHW
	dtype: float
	data: [-1.74573 -1.36293]

OK,所以要看数据的话,一般用.numpy()方法即可

如有需要,可查看下一篇博客:
https://blog.csdn.net/HaoZiHuang/article/details/107610925

你可能感兴趣的:(paddlepaddle历险记,python,机器学习,深度学习,paddlepaddle)