Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.nn.Parameter Function

PyTorch torch.nn.Parameter Function

PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual


torch.nn.Parameter is a learnable parameter tensor in PyTorch.

It is a wrapper that converts a normal tensor into a learnable parameter, automatically adding it to the module's parameter list.

Function definition



torch.nn.Parameter(data=None, requires_grad=True)


Usage examples

Example 1: Basic usage

Example

import

torch

import

torch.

nn

as

nn

class

MyModule

(

nn.

Module

)

:

   

def

init

(

self

)

:

       

super

(

MyModule

,

self

)

.

init

(

)

       

Create a learnable parameter

       

self

.

weight

=

nn.

Parameter

(

torch.

randn

(

10

,

5

)

)

       

self

.

bias

=

nn.

Parameter

(

torch.

zeros

(

5

)

)

   

def

forward

(

self

,

x

)

:

       

return

x

@

self

.

weight

.

t

(

)

self

.

bias

model

=

MyModule

(

)

print

(

"Parameter:"

,

list

(

model.

named_parameters

(

)

)

)

print

(

"Weight shape:"

,

model.

weight

.

shape

)

Example 2: Alternative to register_parameter

Example

import

torch

import

torch.

nn

as

nn

Method 1: Use nn.Parameter (recommended)

class

Net1

(

nn.

Module

)

:

   

def

init

(

self

)

:

       

super

(

)

.

init

(

)

       

self

.

param

=

nn.

Parameter

(

torch.

ones

(

5

)

)

Method 2: Use register_parameter (equivalent)

class

Net2

(

nn.

Module

)

:

   

def

init

(

self

)

:

       

super

(

)

.

init

(

)

       

self

.

register_parameter

(

'param'

,

nn.

Parameter

(

torch.

ones

(

5

)

)

)

print

(

"Method 1 parameter:"

,

list

(

Net1

(

)

.

named_parameters

(

)

)

)

print

(

"Method 2 parameter:"

,

list

(

Net2

(

)

.

named_parameters

(

)

)

)

Example 3: Non-learnable parameters

Example

import

torch

import

torch.

nn

as

nn

requires_grad=False creates a non-learnable parameter

param_no_grad

=

nn.

Parameter

(

torch.

ones

(

5

)

,

requires_grad

=

False

)

print

(

"Trainable:"

,

param_no_grad.

requires_grad

)

print

(

"Still a Parameter:"

,

type

(

param_no_grad

)

)


Use Cases

Tip: nn.Parameter is a subclass of tensor and is automatically added to parameters().


PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual