#训练模型 for epoch inrange(args.num_epochs): for batch in train_loader: img,label=batch img=img.reshape(img.size(0),28*28) if torch.cuda.is_available(): img=img.cuda() label=label.cuda() out=model(img) loss=criterion(out,label) optimizer.zero_grad() loss.backward() optimizer.step() print("epochs:{},loss:{:.6f}".format(epoch,loss))
测试模型:
#测试模型 model.eval() eval_loss=0 eval_acc=0 for batch in test_loader: img,label=batch img=img.reshape(img.size(0),28*28) if torch.cuda.is_available(): img=img.cuda() label=label.cuda() out=model(img) loss=criterion(out,label) eval_loss+=loss.detach()*label.size(0) pred=torch.max(out,dim=1)[1] num_correct=(pred==label).sum() eval_acc+=num_correct.detach() print('Test loss:{},ACC:{:.6f}'.format(eval_loss/len(test_data),eval_acc/len(test_data)))