[英]How do I predict using a PyTorch model?
I created a pyTorch Model to classify images.我创建了一个 pyTorch Model 来对图像进行分类。 I saved it once via state_dict and the entire model like that:
我通过 state_dict 和整个 model 保存了一次,如下所示:
torch.save(model.state_dict(), "model1_statedict")
torch.save(model, "model1_complete")
How can i use these models?我如何使用这些模型? I'd like to check them with some images to see if they're good.
我想用一些图像来检查它们,看看它们是否良好。
I am loading the model with:我正在加载 model:
model = torch.load(path_model)
model.eval()
This works alright, but i have no idea how to use it to predict on a new picture.这很好用,但我不知道如何使用它来预测新图片。
def predict(self, test_images):
self.eval()
# model is self(VGG class's object)
count = test_images.shape[0]
result_np = []
for idx in range(0, count):
# print(idx)
img = test_images[idx, :, :, :]
img = np.expand_dims(img, axis=0)
img = torch.Tensor(img).permute(0, 3, 1, 2).to(device)
# print(img.shape)
pred = self(img)
pred_np = pred.cpu().detach().numpy()
for elem in pred_np:
result_np.append(elem)
return result_np
network is VGG-19 and ref my source code.网络是 VGG-19 并参考我的源代码。
like this architecture:像这样的架构:
class VGG(object):
def __init__(self):
...
def train(self, train_images, valid_images):
train_dataset = torch.utils.data.Dataset(train_images)
valid_dataset = torch.utils.data.Dataset(valid_images)
trainloader = torch.utils.data.DataLoader(train_dataset)
validloader = torch.utils.data.DataLoader(valid_dataset)
self.optimizer = Adam(...)
self.criterion = CrossEntropyLoss(...)
for epoch in range(0, epochs):
...
self.evaluate(validloader, model=self, criterion=self.criterion)
...
def evaluate(self, dataloader, model, criterion):
model.eval()
for i, sample in enumerate(dataloader):
...
def predict(self, test_images):
...
if __name__ == "__main__":
network = VGG()
trainset, validset = get_dataset() # abstract function for showing
testset = get_test_dataset()
network.train(trainset, validset)
result = network.predict(testset)
A pytorch model is a function. pytorch model 是 function。 You provide it with appropriately defined input, and it returns an output.
您为其提供适当定义的输入,它会返回 output。 If you just want to visually inspect the output given a specific input image, simply call it:
如果您只想在给定特定输入图像的情况下目视检查 output,只需调用它:
model.eval()
output = model(example_image)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.