自定义损失函数不会在PyTorch中最小化

4jb9z9bj  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(116)

我正在使用PyTorch代码在无监督设置中对自定义损失函数进行训练。然而,在训练阶段的五个时期内,损失不会下降并保持不变。请参阅下面的训练代码片段:

X = np.load(<data path>) #Load dataset which is a numpy array of N points with some dimension each.
num_samples, num_features = X.shape

gmm = GaussianMixture(n_components=num_classes, covariance_type='spherical')
gmm.fit(X)
z_gmm = gmm.predict(X)

R_gmm = gmm.predict_proba(X)
pre_R = Variable(torch.log(torch.from_numpy(R_gmm + 1e-8)).type(dtype), requires_grad=True)
R = torch.nn.functional.softmax(pre_R)

F = torch.stack(Variable(torch.from_numpy(X).type(dtype), requires_grad=True))
U = Variable(torch.from_numpy(gmm.means_).type(dtype), requires_grad=False)

z_pred = torch.max(R, 1)[1]

distances = torch.sum(((F.unsqueeze(1) - U) ** 2), dim=2)
custom_loss = torch.sum(R * distances) / num_samples

learning_rate = 1e-3
opt_train= torch.optim.Adam([train_var], lr = learning_rate)
U = torch.div(torch.mm(torch.t(R), F), torch.sum(R, dim=0).unsqueeze(1)) #In place assignment with a formula over variables and hence no gradient update is needed.

for epoch in range(max_epochs+1):
    running_loss = 0.0
    for i in range(stepSize):
    # zero the parameter gradients
    opt_train.zero_grad()

    # forward + backward + optimize
    loss = custom_loss
    loss.backward(retain_graph=True)
    opt_train.step()
    running_loss += loss.data[0]

if epoch % 25 == 0:
    print(epoch, loss.data[0]) # OR running_loss also gives the same values.
    running_loss = 0.0

O/P: 0 5.8993988037109375 25 5.8993988037109375 50 5.8993988037109375 75 5.8993988037109375 100 5.8993988037109375
我在培训中错过了什么吗?我遵循了这个example/tutorial。在这方面的任何帮助和指点将不胜感激。

x6yk4ghg

x6yk4ghg1#

在自定义损失函数中尝试以下结构并进行必要的更改。通过在代码中编写以下语句来使用此损失函数:

criterion = Custom_Loss()

在这里,我展示了一个名为Custom_Loss的自定义损失,它将2种输入x和y作为输入。然后它将x重塑为与y相似,最后通过计算重塑后的x和y之间的L2差异来返回损失。这是你在训练网络中经常遇到的标准事情。
假设x是形状(5,10),y是形状(5,5,10)。因此,我们需要向x添加一个维度,然后沿着添加的维度重复它以匹配y的维度。然后,(x-y)将是形状(5,5,10)。我们必须将所有三个维度相加,即三个torch.sum()以获得标量。

class Custom_Loss(torch.nn.Module):
    
    def __init__(self):
        super(Regress_Loss,self).__init__()
        
    def forward(self,x,y):
        y_shape = y.size()[1]
        x_added_dim = x.unsqueeze(1)
        x_stacked_along_dimension1 = x_added_dim.repeat(1,NUM_WORDS,1)
        diff = torch.sum((y - x_stacked_along_dimension1)**2,2)
        totloss = torch.sum(torch.sum(torch.sum(diff)))
        return totloss

相关问题