Python 如何在PyTorch模型中评估单个图像?
我使用此代码来训练一个模型:Python 如何在PyTorch模型中评估单个图像?,python,python-3.x,pytorch,Python,Python 3.x,Pytorch,我使用此代码来训练一个模型: def train(model, epochs): for epoch in range(epochs): for idx, batch in enumerate(train_loader): x, bndbox = batch # unpack batch pred_bndbox = model(x)# forward pass #print('label:',
def train(model, epochs):
for epoch in range(epochs):
for idx, batch in enumerate(train_loader):
x, bndbox = batch # unpack batch
pred_bndbox = model(x)# forward pass
#print('label:', bndbox, 'prediction:', pred_bndbox)
loss = criterion(pred_bndbox, bndbox) # compute loss for this batch
optimiser.zero_grad()# zero gradients of optimiser
loss.backward() # backward pass (find rate of change of loss with respect to model parameters)
optimiser.step()# take optimisation step
print('Epoch:', epoch, 'Batch:', idx, 'Loss:', loss.item())
writer.add_scalar('DETECTION Loss/Train', loss, epoch*len(train_loader) + idx) # write loss to a graph
train(cnn, epochs)
torch.save(cnn.state_dict(), str(time.time()))# save model
def visualise(model, n):
model.eval()
for idx, batch in enumerate(test_loader):
x, y = batch
pred_bndbox = model(x)
S40dataset.show(batch, pred_bndbox=pred_bndbox)
if idx == n:
break
如何在单个图像上评估模型预测以检查神经网络的运行?您可以使用:
model.eval() # turn the model to evaluate mode
with torch.no_grad(): # does not calculate gradient
class_index = model(single_image).argmax() #gets the prediction for the image's class
此代码将网络预测保存为class\u index
变量中的类索引。您必须将要检查的图像以正确的形状保存在single_image
变量中
希望有帮助 嗨,你说你想“上传”一张图片到NN是什么意思?你的意思是在新图像上评估网络的预测吗?是的。请帮帮我