做二元类分类。我使用二元交叉熵作为损失函数(nn.BCEloss()),最后一层的单位为1。
在将 (input, target) 放入损失函数之前,我将目标从 Long 转换为 float。只有DataLoader最后一步出现错误信息,错误信息如下。
"RuntimeError: Expected object of scalar type Float but got scalar type Long for argument #2 'target'"
代码中定义了 DataLoader(如果批处理大小不匹配,我将删除最后一个批处理),我不确定是否与错误相关。
我试图打印目标和输入(神经网络的输出)的类型,并且两个变量的类型都是浮点数。我把“类型结果”和代码放在下面。
trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE,
shuffle=True, drop_last=True)
loss_func = nn.BCELoss()
# training
for epoch in range(EPOCH):
test_loss = 0
train_loss = 0
for step, (b_x, b_y) in enumerate(trainloader): # gives batch data
b_x = b_x.view(-1, TIME_STEP, 1) # reshape x to (batch, time_step, input_size)
print("step: ", step)
b_x = b_x.to(device)
print("BEFORE|b_y type: ",b_y.type())
b_y …Run Code Online (Sandbox Code Playgroud)