Download model.py from AIOmarRehan/Animal_Image_Classification_Using_InceptionV3: direct link, hf CLI and curl.
- Browser
- Download file 1.22 kB
-
https://huggingface.co/spaces/AIOmarRehan/Animal_Image_Classification_Using_InceptionV3/resolve/63b7af2b3677be00ca45139ff2353976392a12ce/model.py
- Command line
-
hf download hf://spaces/AIOmarRehan/Animal_Image_Classification_Using_InceptionV3@63b7af2b3677be00ca45139ff2353976392a12ce/model.py
-
curl -L -o model.py https://huggingface.co/spaces/AIOmarRehan/Animal_Image_Classification_Using_InceptionV3/resolve/63b7af2b3677be00ca45139ff2353976392a12ce/model.py
1.22 kB
| import tensorflow as tf | |
| import numpy as np | |
| from PIL import Image | |
| # Load your trained CNN model | |
| model = tf.keras.models.load_model("saved_model/Inception_V3_Animals_Classification.h5") | |
| # Same label order you used when training (from LabelEncoder) | |
| CLASS_NAMES = ["Cat", "Dog", "Snake"] | |
| def preprocess_image(img: Image.Image, target_size=(256, 256)): | |
| """ | |
| Preprocess a PIL image to match training pipeline: | |
| - Convert to RGB | |
| - Resize | |
| - Convert to float32 | |
| - Normalize to [0,1] | |
| - Add batch dimension | |
| """ | |
| img = img.convert("RGB") # ensure 3 channels | |
| img = img.resize(target_size) | |
| img = np.array(img).astype("float32") / 255.0 # normalize | |
| img = np.expand_dims(img, axis=0) # (1, 256, 256, 3) | |
| return img | |
| def predict(img: Image.Image): | |
| # Apply preprocessing | |
| input_tensor = preprocess_image(img) | |
| # Model prediction | |
| preds = model.predict(input_tensor) | |
| probs = preds[0] | |
| class_idx = int(np.argmax(probs)) | |
| confidence = float(np.max(probs)) | |
| # Map all probabilities | |
| prob_dict = {CLASS_NAMES[i]: float(probs[i]) for i in range(len(CLASS_NAMES))} | |
| return CLASS_NAMES[class_idx], confidence, prob_dict |