从二进制数据进行PyTorch训练

uinbv5nw  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(116)

给定一个递减函数f(x,l),其定义域为[0,xmax],其中l是一个参数,我想用PyTorch写一个程序,从一些二进制值的训练数据中学习l的值。训练数据是(x_i,g(x_i)),i= 1,2,.,n,其中当f(x)>t时g(x)=1,否则为0。这里的t是一个恒定的阈值。我定义了类

class Function(torch.nn.Module):
    def __init__(self, l_init): # l is the parameter, its initial value is l_init
        self.l = torch.nn.Parameter(torch.tensor(l_init, dtype=float))
    def forward(self, x):
        return f(x) # here f is pre-defined

我还有一个变量train_data,其中train_data[0]是x_i的数组(浮点数组),train_data[1]是g(x_i)的数组(0/1数组)。我示例化了Function模块:

function = Function()

将损失函数定义为

loss_func = lambda x, y: (x - y) ** 2

对于每次训练迭代,我计算pred = function(train_data[0]),并且我必须在不丢失梯度函数的情况下计算损失。但如果我写

loss = loss_func((pred > t).float(), train_data[0])

梯度函数将丢失。我应该怎么做才能使用这个二进制训练数据来学习l的值?

wgxvkvu9

wgxvkvu91#

https://github.com/ZouJiu1/CNN_numpy/blob/master/net/loss.py#L36-L66
(pred> t)不能求导或丢失梯度信息。(pred > t)应该在预测输入时使用。在训练的时候不应该使用。
您可以通过使用带exp的BCEloss或不带exp的BCEWithLogitsLoss来完成此操作
你应该像这样定义一个损失函数,train_data应该是one_hot格式。
现在假设Pred是n × 2维

BCEloss

https://pytorch.org/docs/stable/generated/torch.nn.BCELoss.html?highlight=bce#torch.nn.BCELoss

loss_func = torch.nn.BCEloss()
train_datas = torch.zeros_like(pred)
train_datas[torch.arange(len(pred)), train_data[1]] = 1
softmax = torch.nn.Softmax(pred, dim = -1)
pred = softmax(pred)
loss = loss_func(pred, train_datas)

当你预测输入时,使用

softmax = torch.nn.Softmax(pred, dim = -1)
pred = softmax(pred)
for i in range(len(pred)):
    if pred[i][0] > 0.6:
        label = 0
        ...do something...
    elif pred[i][1] > 0.6:
        label = 1
        ...do something...

BCEWithLogitsLoss

https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html?highlight=bce#torch.nn.BCEWithLogitsLoss

loss_func = torch.nn.BCEWithLogitsLoss()
train_datas = torch.zeros_like(pred)
train_datas[torch.arange(len(pred)), train_data[1]] = 1
loss = loss_func(pred, train_datas)

当你预测输入时,使用

softmax = torch.nn.Softmax(pred, dim = -1)
pred = softmax(pred)
for i in range(len(pred)):
    if pred[i][0] > 0.6:
        label = 0
        ...do something...
    elif pred[i][1] > 0.6:
        label = 1
        ...do something...

除此之外,你也可以在多类分类中使用交叉熵损失。https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html?highlight=cross#torch.nn.CrossEntropyLoss

另一件事

如果Pred是n维的,则上述假设Pred是nx2。你应该用这个损失函数

loss_func = torch.nn.CrossEntropyLoss()
pred = torch.sigmoid(pred)
loss = loss_func(pred, train_data)

当你预测输入时,使用

softmax = torch.sigmoid(pred)
for i in range(len(pred)):
    if pred[i] > 0.6:
        ...do something...
        break

相关问题