小编Uma*_*pta的帖子

如何使用 lambda 函数在 pytorch 中保存 LambdaLR 调度程序?

使用 python 3.6 运行 pytorch 0.4.1 我遇到了这个问题:
我无法使用torch.save我的学习率调度程序,因为 python 不会腌制 lambda 函数:

lambda1 = lambda epoch: epoch // 30
scheduler = LambdaLR(optimizer, lr_lambda=lambda1)
torch.save(scheduler.state_dict(), 'scheduler.pth.tar')
Run Code Online (Sandbox Code Playgroud)

结果有错误

PicklingError: Can't pickle <function <lambda> at 0x7f7583fe92f0>:
attribute lookup <lambda> on __main__ failed
Run Code Online (Sandbox Code Playgroud)

如何保存我的调度程序?


我知道lambda1可以保存使用适当的函数而不是 lambda 函数,但是我需要一个 lambda 函数,因为我希望能够在定义此函数时对其进行控制(例如,我希望能够更改固定的 30在分母中)。
如何做到这一点并且仍然允许我保存调度程序?

python-3.x pytorch

3
推荐指数
1
解决办法
1553
查看次数

Why there are different output between model.forward(input) and model(input)

I'm using pytorch to build a simple model like VGG16,and I have overloaded the function forward in my model.

I found everyone tends to use model(input) to get the output rather than model.forward(input), and I am interested in the difference between them. I try to input the same data, but the result is different. I'm confused.

I have output the layer_weight before I input data, the weight not be changed, and I know when we using model(input) it using …

model forward pytorch

3
推荐指数
1
解决办法
418
查看次数

将张量转换为索引的一个热编码张量

我有形状为(1,1,128,128,128)的标签张量,其中值的范围可能为0.24。我想使用nn.fucntional.one_hot函数将其转换为一个热编码张量

n = 24
one_hot = torch.nn.functional.one_hot(indices, n)
Run Code Online (Sandbox Code Playgroud)

但这确实需要一个指数张量,老实说,我不确定如何获得这些指数。我唯一的张量是上述形状的标签张量,它包含1-24范围内的值,而不是索引

如何从张量中获取索引张量?提前致谢。

one-hot-encoding pytorch

2
推荐指数
1
解决办法
913
查看次数

在Pytorch中自定义距离损失功能?

我想在pytorch中实现以下距离损失功能。我正在关注pytorch论坛上的https://discuss.pytorch.org/t/custom-loss-functions/29387/4主题

np.linalg.norm(output - target)
# where output.shape = [1, 2] and target.shape = [1, 2]
Run Code Online (Sandbox Code Playgroud)

所以我实现了这样的损失功能

def my_loss(output, target):    
    loss = torch.tensor(np.linalg.norm(output.detach().numpy() - target.detach().numpy()))
    return loss
Run Code Online (Sandbox Code Playgroud)

使用此损失函数,向后调用会产生运行时错误

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
Run Code Online (Sandbox Code Playgroud)

我的整个代码看起来像这样

model = nn.Linear(2, 2)

x = torch.randn(1, 2)
target = torch.randn(1, 2)
output = model(x)

loss = my_loss(output, target)
loss.backward()   <----- Error here

print(model.weight.grad)
Run Code Online (Sandbox Code Playgroud)

PS:我知道pytorch是成对丢失的,但是由于它的某些限制,我必须自己实现。

按照pytorch源代码,我尝试了以下操作,

class my_function(torch.nn.Module): # forgot to define backward()
    def forward(self, …
Run Code Online (Sandbox Code Playgroud)

pytorch loss-function

0
推荐指数
1
解决办法
63
查看次数