'I am encountering an error which i have no idea of
Hello guys am new flask and trying to deploy a model as api using flask I used transfer learning method(resnet50) in building the model Here is the print i get in the console { "error": "error in prediction" } Here is how the codes are like api.py
from flask import Flask, request,jsonify
from torch_utils import transform_image,get_prediction
app = Flask(__name__)
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg','PNG','JPG','JPEG'}
def allowed_file(filename):
# xxx.png
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/predict', methods=['POST'])
def predict():
if request.method == 'POST':
file = request.files.get('file')
if file is None or file.filename == "":
return jsonify({'error': 'No file' })
if not allowed_file(file.filename):
return jsonify({'error': 'format not supported'})
try:
img_bytes = file.read()
tensor = transform_image(img_bytes)
prediction = get_prediction(tensor)
data = {'prediction': prediction.item(0), 'class_name': str(prediction.item(0))}
return jsonify(prediction)
except Exception as ex:
return jsonify({'error': "error in prediction"})
#return jsonify({'Prediction':"benign",'Accuracy':"50%"})
if __name__ == "__main__":
app.run(port=3000,debug=True)
**torch_utils.py
import io
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.utils.data import dataloader
from torchvision import models
from torchvision import datasets, transforms
from PIL import Image
from train_test import Model
import data
#load model
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# data_loaders = data.data_loaders
# dataset_sizes = {x: len(data.image_datasets[x]) for x in ['train', 'val']}
class_names = data.image_datasets['train'].classes
# initiate pre-trained CNN model
model = models.resnet50(pretrained=True)
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, len(class_names))
model = model.to(DEVICE)
criterion = nn.CrossEntropyLoss()
optimizer_ft = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# # reduce learning rate by 0.1 after every 5 epochs
# exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=5, gamma=0.1)
PATH = "model.pth"
model.load_state_dict(torch.load(PATH))
model.eval()
def transform_image(image_bytes):
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
image = Image.open(image_bytes)
return transform(image).unsqueeze(0)
# predict
def get_prediction(image_tensor):
images = image_tensor.reshape(-1, 256 * 256).to(DEVICE)
images = image_tensor
outputs = models(images)
# max returns (value ,index)
_, predicted = torch.max(outputs.data, 1)
return predicted
And this is where api to see if it works. It might be the json in api.py that am not doing correctly. I dont know because am new to this
test.py import requests
resp = requests.post("http://127.0.0.1:3000/predict", files={'file': open('new.png', 'rb')})
print(resp.text)
The ***new.png*** is a sampl image that i trained on with the model
Answers will be greatly appreciated
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
