简体   繁体   English

如何使用 PyTorch model 进行预测?

[英]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.

相关问题 如何使用经过训练的 Image to Emotion Pytorch 模型进行预测 - How do I predict using a trained Image to Emotion Pytorch model 如何使用训练有素的 keras 模型预测数据 - How do I predict data using a trained keras model 如何让我的线性回归 model 使用 clf.predict 进行预测? - how do i get my linear regression model to predict using clf.predict? 如何在 PyTorch 中保存经过训练的 model? - How do I save a trained model in PyTorch? 如何在 PyTorch 中打印 model 摘要? - How do I print the model summary in PyTorch? 如何使用我的类型进行预测<torchvision.models>在我的一组图像上? Python / Torchvision / PyTorch</torchvision.models> - How do I predict using my type <torchvision.models> upon my set of images? Python / Torchvision / PyTorch 如何从我训练并保存的 pytorch model 预测 output? - how can I predict an output from a pytorch model I have trained and saved? 使用 pytorch 预训练模型进行预测时所需的图像大小 - Required image size when using pytorch pretrain model to predict 如何使用 keras 预测和打印 ann 模型的 r2 分数? - How do i predict and print out the r2 score for an ann model using keras? Keras,我如何在训练模型后进行预测? - Keras, how do I predict after I trained a model?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM