6

I want to use a learnable parameter that only takes values between 0 and 1. How can I do this in pytorch?

Currently I am using:

self.beta = Parameter(torch.Tensor(1))
#initialize
zeros(self.beta)

But I am getting zeros and NaN for this parameter, as I train.

1 Answer 1

5

You can have a "raw" parameter taking any values, and then pass it through a sigmoid function to get a values in range (0, 1) to be used by your function.

For example:

class MyZeroOneLayer(nn.Module):
  def __init__(self):
    self.raw_beta = nn.Parameter(data=torch.Tensor(1), requires_grad=True)

  def forward(self):  # no inputs
    beta = torch.sigmoid(self.raw_beta)  # get (0,1) value
    return beta

Now you have a module with trainable parameter that is effectively in range (0,1)

Sign up to request clarification or add additional context in comments.

3 Comments

Which mean to have a value of 1 you will need the parameter to be infinity. Not sure if that will work as intended.
This is incorrect. After sigmoid, self.raw_beta will no longer be a nn.Parameter.
@JackShi self.raw_beta will always be a nn.Parameter. The local variable beta inside forward method is not a parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.