我希望你们一切都好。我是PyTorch的新手,我遇到了一个在线代码,其中包含以下代码:
cuda = True if torch.cuda.is_available() else False
num_class = opt.num_class
num_repeats = opt.num_repeats
total=0
correct=0
acc=[]
acc1=[]
model = SHMnet(num_class)
# model = AlexNet1D(num_class)
learning_rate = opt.lr
print(model)
loss = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,betas=(opt.b1,opt.b2))
if cuda:
model=model.cuda()
loss=loss.cuda()
FloatTensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor
LongTensor = torch.cuda.LongTensor if cuda else torch.LongTensor
traindataset = []
for label in range(num_class):
epdataset = epDataset(label,num_repeats)
traindataset = ConcatDataset([traindataset,epdataset])
testdataset =[]
for label in range(num_class):
eptdataset = eptDataset(label,6)
testdataset = ConcatDataset([testdataset,eptdataset])
dataloader = DataLoader(traindataset, batch_size=opt.batch_size)
viddataloader = DataLoader(testdataset,batch_size = opt.batch_size)
loss_r=[]
start = time.time()
for epoch in range(opt.n_epochs):
print('Epoch: %d' % epoch)
total = 0
correct = 0
total1 = 0
correct1 = 0
for i, (sdata, label) in enumerate(dataloader):
batch_size = sdata.shape[0]
sdata = Variable(sdata.type(FloatTensor))
noise=Variable(torch.from_numpy(np.random.normal(1, 0.2, sdata.shape))).type(FloatTensor)
x = torch.mul(sdata,noise).view(sdata.size(0), 1, sdata.size(1))
print(x)
print(x.size())
label = Variable (label.type(LongTensor))
print(label)
optimizer.zero_grad()
output = model(x)
print(output)
print(output.size())
loss1 = loss(input=output, target=label)
loss1.backward()
optimizer.step()
_, predicted = torch.max(model(x).data, 1)
temp = (predicted == label).sum()
correct += temp
total += batch_size
print(i, loss1.item())
loss_r.append(loss1.item())
print('Accuracy of training data is: %d %%' % (100 * correct / total))
acc.append(100 * correct / total)
我设法找到一个数据集,但是,运行代码时出现以下错误:
RuntimeError: “dimension out of range (expected to be in range of [-1, 0], but got 1)”
因此,我不理解此错误。可能是什么原因以及如何解决?
批处理大小为60,类数为6
编辑1
输出和标签变量的输出是:
Labels: tensor([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5])
Labels Size/Shape: torch.Size([12])
torch.Size([12, 512, 2])
Output: tensor([0.0288, 0.0125, 0.0104, 0.0222, 0.0106, 0.0121], grad_fn=<AddBackward0>)
Output Size/Shape: torch.Size([6])
编辑2
我设法将批次大小更改为6,但是输出和标签变量的输出是:
Input Size/Shape: torch.Size([6, 1, 2192])
Labels: tensor([0, 1, 2, 3, 4, 5])
Labels Size/Shape: torch.Size([6])
torch.Size([6, 512, 2])
Output: tensor([ 0.0228, -0.0088, 0.0047, 0.0224, 0.0146, 0.0357], grad_fn=<AddBackward0>)
Output Size/Shape: torch.Size([6])
但是,我遇到相同的错误,批处理大小为6,类数为6 谢谢