Search code examples
pythonpytorchneural-network

How to remove grad_fn when printing neural network weights


I have a neural net that uses nn.Linear connections between layers. When printing the weights between input and hidden layers with the code below:

print("Weight:", net.fc1.weight[0])

The print out looks like this:

Weight: tensor([ 0.0375,  0.1901,  0.0787,  0.2476,  0.0740,  0.2848, -0.2852, -0.0864,
     0.1827,  0.1384], grad_fn=<SelectBackward0>)

Is there a way to stop printing out the grad_fn=<SelectBackward0> and just print the weights out like this:

Weight: tensor([ 0.0375,  0.1901,  0.0787,  0.2476,  0.0740,  0.2848, -0.2852, -0.0864,
 0.1827,  0.1384])

Solution

  • Just use .data attribute

    print("Weight:", net.fc1.weight[0].data)