python - PyTorch - 运行时错误 : Assertion 'cur_target >= 0 && cur_target < n_classes' failed

标签 python python-2.7 pandas dataframe pytorch

我正在尝试使用 PyTorch 制作一个神经网络来预测学生的期末考试成绩。我是这样做的 -

# Hyper Parameters
input_size = 2
hidden_size = 50
num_classes =21
num_epochs = 500
batch_size = 5
learning_rate = 0.1

# define a customise torch dataset
class DataFrameDataset(torch.utils.data.Dataset):
def __init__(self, df):
    self.data_tensor = torch.Tensor(df.as_matrix())

# a function to get items by index
def __getitem__(self, index):
    obj = self.data_tensor[index]
    input = self.data_tensor[index][0:-1]
    target = self.data_tensor[index][-1] - 1
    return input, target

# a function to count samples
def __len__(self):
    n, _ = self.data_tensor.shape
    return n

# load all data
data_i = pd.read_csv('dataset/student-mat.csv', header=None,delimiter=";")
data = data_i.iloc[:,30:33]

# normalise input data
for column in data:
# the last column is target
if column != data.shape[1] - 1:
    data[column] = data.loc[:, [column]].apply(lambda x: (x - x.mean()) / x.std())

# randomly split data into training set (80%) and testing set (20%)
msk = np.random.rand(len(data)) < 0.8
train_data = data[msk]
test_data = data[~msk]

# define train dataset and a data loader
train_dataset = DataFrameDataset(df=train_data)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)

# Neural Network
class Net(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
    super(Net, self).__init__()
    self.fc1 = nn.Linear(input_size, hidden_size)
    self.sigmoid = nn.Sigmoid()
    self.fc2 = nn.Linear(hidden_size, num_classes)

def forward(self, x):
    out = self.fc1(x)
    out = self.sigmoid(out)
    out = self.fc2(out)
    return out


net = Net(input_size, hidden_size, num_classes)

# Loss and Optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Rprop(net.parameters(), lr=learning_rate)

# store all losses for visualisation
all_losses = []

# train the model by batch
for epoch in range(num_epochs):
    for step, (batch_x, batch_y) in enumerate(train_loader):
        # convert torch tensor to Variable
        X = Variable(batch_x)
        Y = Variable(batch_y.long())

        # Forward + Backward + Optimize
        optimizer.zero_grad()  # zero the gradient buffer
        outputs = net(X)
        loss = criterion(outputs, Y)
        all_losses.append(loss.data[0])
        loss.backward()
        optimizer.step()

        if epoch % 50 == 0:
            _, predicted = torch.max(outputs, 1)
            # calculate and print accuracy
            total = predicted.size(0)
            correct = predicted.data.numpy() == Y.data.numpy()

            print('Epoch [%d/%d], Step [%d/%d], Loss: %.4f, Accuracy: %.2f %%'
                  % (epoch + 1, num_epochs, step + 1,
                      len(train_data) // batch_size + 1,
                      loss.data[0], 100 * sum(correct)/total))

我在 loss = criterion(outputs, Y) 行遇到错误上面写着—— RuntimeError: Assertion 'cur_target >= 0 && cur_target < n_classes' failed. at /pytorch/torch/lib/THNN/generic/ClassNLLCriterion.c:62

我无法弄清楚我做错了什么,因为我对此很陌生,并且我已经检查过这里的其他帖子,但是它们似乎没有帮助。 data数据框看起来像 -

     30  31  32

0     5   6   6
1     5   5   6
2     7   8  10
3    15  14  15
4     6  10  10
5    15  15  15

谁能告诉我我做错了什么以及如何纠正。任何帮助表示赞赏!谢谢! :)

最佳答案

我的程序也有同样的错误 我刚刚意识到问题出在网络中的输出节点数量上 在我的程序中,模型的输出节点数不等于数据的标签数 输出数量为1,目标标签数量为10。然后我将输出数量改为10,没有错误

关于python - PyTorch - 运行时错误 : Assertion 'cur_target >= 0 && cur_target < n_classes' failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49971958/

相关文章:

python - pyparsing 之后的下一步是什么?

python - 使用 python 请求从 oanda V20 Rest api 流式定价

javascript - 向 websocket 客户端发送消息时压缩位必须为 0

python - 如果值在列表 pandas 中,则 bool 向量

python - 在 Pandas DataFrame 中查找第一列匹配条件的矢量化方法

python - 如何选择标签编码分类变量来创建虚拟变量?

python - 为什么我不能 "deactivate"pyenv/virtualenv?如何安装 "fix"

python 包导入模块使用 __init__.py

python - 获取没有内部子标签文本的 HTML 标签文本

python - 在循环中迭代数据帧行