This message was deleted.
# ask-for-help
s
This message was deleted.
s
Hi @Taeef Najib, maybe you could reference the PyTorch example here, https://github.com/bentoml/BentoML/blob/main/examples/pytorch_mnist/service.py. To return the actual class name, can you apply the
softmax
function?
t
Hi @Sean I took that example as a reference. Added the preprocessing steps as required. But still not sure how to use
softmax
function for this one. Here's an updated code. Do you see any issues in my code?
Copy code
from __future__ import annotations

import typing as t
from typing import TYPE_CHECKING

import numpy as np
from PIL.Image import Image as PILImage

import bentoml
from <http://bentoml.io|bentoml.io> import Image
from <http://bentoml.io|bentoml.io> import NumpyNdarray

if TYPE_CHECKING:
    from numpy.typing import NDArray

import torch
import torch.nn.functional as F
import torchvision.transforms as T

mnist_runner = bentoml.pytorch.get("covid_new").to_runner()

svc = bentoml.Service(name="covid_new", runners=[mnist_runner])

def to_numpy(tensor):
    return tensor.detach().cpu().numpy()

# Transformation pipeline to preprocess the input image
img_size = 224
test_transform = T.Compose(
    [
        T.Resize(size=(img_size, img_size)),
        T.ToTensor(),
        # for 3-channel images, normalize using mean and std of each channel
        T.Normalize(
            [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
        ),
    ]
)

@svc.api(input=Image(), output=NumpyNdarray(dtype="float32"))
async def predict_image(f: PILImage) -> NDArray[t.Any]:
    assert isinstance(f, PILImage)
    img = test_transform(f)
    
    # Add batch dimension to input tensor
    img = img.unsqueeze(0)

    output_tensor = await mnist_runner.async_run(img)
    
    # Apply softmax function to get a probability distribution over the classes
    probabilities = F.softmax(output_tensor, dim=1)
    
    # Get the index of the class with the highest probability
    _, predicted_class = probabilities.topk(1, dim=1)
    
    # Convert the tensor to numpy array and return the predicted class as integer
    return to_numpy(predicted_class.squeeze()).astype(np.int64)
s
It’s hard to evaluate by reading only source code because I don’t know the format of the output tensor. Have you tried to run it?
t
I'll do that. I'll mention any error that I receive as soon as I have it. Thank you so much for your kind support.
@Sean this is the error I recieved:
Copy code
KeyError: 'content-type'
2023-05-03T01:24:41+0000 [INFO] [api_server:1] 10.0.147.193:36070 (scheme=http,method=POST,path=/predict_image,type=,length=0) (status=500,type=application/json,length=110) 5.625ms (trace=1bc5fa36867bae13e55504e1c6f51275,span=e7d2b25c7692cce6,sampled=0)
On postman, my content-type is
image/jpeg
and on my code, as you can see, my type is
PILImage
I think you pointed me to the most correct direction. But I don't know how to fix this one error.