imrkash's picture
Upload efficientNet-algo/predict.py with huggingface_hub
7a733d3 verified
Raw History Blame Contribute Delete
1.77 kB
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import tensorflow as tf
from PIL import Image
import os
classes = [ "cocci" , "healthy" , "ncd" , "salmo" , ]
def predict():
# Assuming model, classes, and test are already defined
result = []
test= load_test_data()
for index, i in enumerate(test.filename):
img = Image.open(i).convert('RGB')
img = img.resize((300, 300 * img.size[1] // img.size[0]), Image.Resampling.LANCZOS)
inp_numpy = np.array(img)[None]
inp = tf.constant(inp_numpy, dtype='float32')
# Get model predictions
model = tf.saved_model.load(get_model_path())
class_scores = model(inp)[0].numpy()
predicted_class_index = class_scores.argmax()
predicted_class = classes[predicted_class_index]
confidence = class_scores[predicted_class_index]
result.append({"label":predicted_class, "accuracy":confidence})
return result
def get_pwd():
# Define the path relative to the script's directory
return os.path.dirname(os.path.abspath(__file__))
def get_upload_dir(relative_path='../uploads'):
upload_dir = os.path.join(get_pwd(),relative_path)
# Get the absolute path to the uploads directory
return os.path.abspath(upload_dir)
def get_model_path():
current_dir = get_pwd()
return os.path.join(current_dir, 'EfficientNet-model')
def load_test_data():
Id = []
upload_dir = get_upload_dir()
for dirname, _, filenames in os.walk(upload_dir) :
for filename in filenames:
Id.append(os.path.join(dirname, filename))
test=pd.DataFrame()
test=test.assign(filename=Id)
test.head()
return test