Spaces:
Build error
Build error
| import gradio as gr | |
| import tensorflow as tf | |
| import numpy as np | |
| from tensorflow.keras import backend as K | |
| def fbeta(y_true, y_pred, threshold_shift=0): | |
| beta = 2 | |
| y_pred = K.clip(y_pred, 0, 1) | |
| y_pred_bin = K.round(y_pred + threshold_shift) | |
| tp = K.sum(K.round(y_true * y_pred_bin)) + K.epsilon() | |
| fp = K.sum(K.round(K.clip(y_pred_bin - y_true, 0, 1))) | |
| fn = K.sum(K.round(K.clip(y_true - y_pred, 0, 1))) | |
| precision = tp / (tp + fp) | |
| recall = tp / (tp + fn) | |
| beta_squared = beta**2 | |
| return ( | |
| (beta_squared + 1) | |
| * (precision * recall) | |
| / (beta_squared * precision + recall + K.epsilon()) | |
| ) | |
| def accuracy_score(y_true, y_pred, epsilon=1e-4): | |
| y_true = tf.cast(y_true, tf.float32) | |
| y_pred = tf.cast( | |
| tf.greater(tf.cast(y_pred, tf.float32), tf.constant(0.5)), tf.float32 | |
| ) | |
| tp = tf.reduce_sum(y_true * y_pred, axis=1) | |
| fp = tf.reduce_sum(y_pred, axis=1) - tp | |
| fn = tf.reduce_sum(y_true, axis=1) - tp | |
| y_true = tf.cast(y_true, tf.bool) | |
| y_pred = tf.cast(y_pred, tf.bool) | |
| tn = tf.reduce_sum( | |
| tf.cast(tf.logical_not(y_true), tf.float32) | |
| * tf.cast(tf.logical_not(y_pred), tf.float32), | |
| axis=1, | |
| ) | |
| return (tp + tn) / (tp + tn + fp + fn + epsilon) | |
| model = tf.keras.models.load_model( | |
| "final.h5", custom_objects={"fbeta": fbeta, "accuracy_score": accuracy_score} | |
| ) | |
| class_names = [ | |
| "clear", | |
| "agriculture", | |
| "selective_logging", | |
| "haze", | |
| "bare_ground", | |
| "blooming", | |
| "habitation", | |
| "artisinal_mine", | |
| "blow_down", | |
| "road", | |
| "slash_burn", | |
| "primary", | |
| "cultivation", | |
| "water", | |
| "conventional_mine", | |
| "cloudy", | |
| "partly_cloudy", | |
| ] | |
| def predict(image): | |
| image = tf.image.resize(image, [64, 64]) | |
| image = image / 255.0 | |
| image = np.expand_dims(image, axis=0) | |
| predictions = model.predict(image)[0] | |
| print(predictions) | |
| results = {class_names[i]: float(predictions[i]) for i in range(len(class_names))} | |
| return results | |
| test_examples = [ | |
| "./images/test_10158.jpg", # Path to Test Image 1 | |
| "./images/train_10004.jpg", # Path to Test Image 2 | |
| ] | |
| iface = gr.Interface( | |
| fn=predict, | |
| inputs=gr.Image(type="numpy"), | |
| outputs=gr.Label(num_top_classes=17), | |
| examples=test_examples, | |
| ) | |
| iface.launch() | |