当火车标签为-1,0,1时,我应该使用哪种pytorch损失功能?

时间:2019-04-16 10:32:47

标签: python-3.x

我正在尝试使用pytorch创建一个三层神经网络,火车标签为-1,0,1。我知道使用CrossEntropyLoss时标签应为正数。我应该使用哪种损失函数?

import scipy.io as scio
import numpy as np
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torch.autograd import Variable

# load data
data_file = r'C:\Users\11709\Desktop\第二学期\NN\homework1\train_data.mat'
train_data = scio.loadmat(data_file)['train_data']
train_data = Variable(torch.FloatTensor(train_data))
data_file = r'C:\Users\11709\Desktop\第二学期\NN\homework1\train_label.mat'
train_label = scio.loadmat(data_file)['train_label']
train_label = Variable(torch.LongTensor(train_label))
train_label =  torch.squeeze(train_label, dim = 1)

# make net
class Net(torch.nn.Module):
    def __init__(self,n_feature, n_hidden, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)
        self.output = torch.nn.Linear(n_hidden, n_output)
    def forward(self, x):
        x = F.relu(self.hidden(x))
        x = self.output(x)
        return x

net = Net(310,100, 3)
print(net)

# optimizer
optimizer = torch.optim.SGD(net.parameters(), lr = 0.02)
loss_func = torch.nn.CrossEntropyLoss()

# training
for i in range(100):
    out  = net(train_data)
    loss = loss_func(out, train_label)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

0 个答案:

没有答案