File size: 2,304 Bytes
a49489d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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()