leminhhung0101 commited on
Commit
08f875f
·
verified ·
1 Parent(s): 3b7e4b9

Create ClassiferTest.py

Browse files
Files changed (1) hide show
  1. ClassiferTest.py +252 -0
ClassiferTest.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Script doc lap de test model phan loai u nao da train (.keras).
3
+ Khong can toan bo pipeline training - chi can model + 1 file de test.
4
+
5
+ Ho tro 2 loai input:
6
+ 1. File .h5 (dung dinh dang giong data training, co dataset 'image')
7
+ 2. File anh thong thuong (.png, .jpg, .jpeg) - se duoc chuyen ve grayscale
8
+
9
+ Cach dung:
10
+ python test_inference.py --model /path/to/model.keras --input /path/to/slice.h5
11
+ python test_inference.py --model /path/to/model.keras --input /path/to/image.png
12
+ """
13
+
14
+ import argparse
15
+ import numpy as np
16
+ import cv2
17
+ import h5py
18
+ import tensorflow as tf
19
+ from tensorflow.keras.layers import Layer, Dense, Dropout
20
+ from tensorflow.keras.applications.efficientnet_v2 import preprocess_input as efficientnetv2_preprocess
21
+
22
+ IMG_SIZE = (299, 299)
23
+ NUM_SLICES = 3
24
+ CLASS_NAMES = ["non-tumor", "tumor"]
25
+
26
+
27
+ # ============================================================
28
+ # CAC CUSTOM LAYER / LOSS - BAT BUOC PHAI CO DE load_model() HOAT DONG
29
+ # (copy y nguyen tu script training goc)
30
+ # ============================================================
31
+ class AttentionVisualizer(Layer):
32
+ def __init__(self, **kwargs):
33
+ super(AttentionVisualizer, self).__init__(**kwargs)
34
+
35
+ def call(self, attention_weights):
36
+ spatial_attention = tf.reduce_mean(attention_weights, axis=-1, keepdims=True)
37
+ spatial_attention = (spatial_attention - tf.reduce_min(spatial_attention, axis=(1, 2), keepdims=True)) / \
38
+ (tf.reduce_max(spatial_attention, axis=(1, 2), keepdims=True) -
39
+ tf.reduce_min(spatial_attention, axis=(1, 2), keepdims=True) + 1e-8)
40
+ return spatial_attention
41
+
42
+
43
+ class MCDropout(Layer):
44
+ def __init__(self, rate, **kwargs):
45
+ super(MCDropout, self).__init__(**kwargs)
46
+ self.rate = rate
47
+ self.dropout = Dropout(rate)
48
+
49
+ def call(self, inputs, training=None):
50
+ return self.dropout(inputs, training=True)
51
+
52
+
53
+ class EvidentialLoss(tf.keras.losses.Loss):
54
+ def __init__(self, class_weights=None, name="evidential_loss",
55
+ reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE):
56
+ super(EvidentialLoss, self).__init__(name=name, reduction=reduction)
57
+ self.class_weights = class_weights if class_weights is not None else {}
58
+
59
+ def call(self, y_true, y_pred):
60
+ ce_loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred)
61
+ if self.class_weights:
62
+ class_indices = tf.argmax(y_true, axis=1)
63
+ weights = tf.gather(tf.constant(list(self.class_weights.values()), dtype=tf.float32), class_indices)
64
+ ce_loss = ce_loss * weights
65
+ reg_loss = tf.reduce_mean(tf.square(y_pred - y_true))
66
+ return tf.reduce_mean(ce_loss + 0.01 * reg_loss)
67
+
68
+ def get_config(self):
69
+ config = super(EvidentialLoss, self).get_config()
70
+ config.update({'class_weights': self.class_weights})
71
+ return config
72
+
73
+
74
+ class EvidentialLayer(Layer):
75
+ def __init__(self, num_classes, **kwargs):
76
+ super(EvidentialLayer, self).__init__(**kwargs)
77
+ self.num_classes = num_classes
78
+
79
+ def build(self, input_shape):
80
+ self.dense = Dense(self.num_classes, dtype=tf.float32)
81
+ super(EvidentialLayer, self).build(input_shape)
82
+
83
+ def call(self, inputs):
84
+ evidence = tf.nn.softplus(self.dense(inputs))
85
+ evidence = tf.clip_by_value(evidence, 0, 1e6)
86
+ alpha = evidence + 1
87
+ S = tf.reduce_sum(alpha, axis=1, keepdims=True) + 1e-10
88
+ prob = alpha / S
89
+ epistemic_uncertainty = self.num_classes / S
90
+ aleatoric_uncertainty = tf.reduce_sum(prob * (1 - prob) / (S + 1), axis=1, keepdims=True)
91
+ return prob, epistemic_uncertainty, aleatoric_uncertainty
92
+
93
+ def get_config(self):
94
+ config = super(EvidentialLayer, self).get_config()
95
+ config.update({'num_classes': self.num_classes})
96
+ return config
97
+
98
+
99
+ class ExplainableSelfAttention(Layer):
100
+ def __init__(self, units, return_attention=False, **kwargs):
101
+ super(ExplainableSelfAttention, self).__init__(**kwargs)
102
+ self.units = units
103
+ self.return_attention = return_attention
104
+
105
+ def build(self, input_shape):
106
+ self.W_q = Dense(self.units, use_bias=False)
107
+ self.W_k = Dense(self.units, use_bias=False)
108
+ self.W_v = Dense(self.units, use_bias=False)
109
+ self.dense = Dense(input_shape[-1])
110
+ self.attention_visualizer = AttentionVisualizer()
111
+ super(ExplainableSelfAttention, self).build(input_shape)
112
+
113
+ def call(self, inputs, return_attention=None):
114
+ return_attention = return_attention if return_attention is not None else self.return_attention
115
+ batch_size = tf.shape(inputs)[0]
116
+ height, width, channels = inputs.shape[1:]
117
+ x = tf.reshape(inputs, [batch_size, height * width, channels])
118
+ q = self.W_q(x)
119
+ k = self.W_k(x)
120
+ v = self.W_v(x)
121
+ scale = tf.cast(tf.sqrt(tf.cast(self.units, inputs.dtype)), inputs.dtype)
122
+ scores = tf.matmul(q, k, transpose_b=True) / scale
123
+ attention_weights = tf.nn.softmax(scores, axis=-1)
124
+ attended = tf.matmul(attention_weights, v)
125
+ output = self.dense(attended)
126
+ output = tf.reshape(output, [batch_size, height, width, channels])
127
+ output = inputs + output
128
+ if return_attention:
129
+ attention_spatial = tf.reshape(attention_weights, [batch_size, height, width, height * width])
130
+ attention_map = self.attention_visualizer(attention_spatial)
131
+ return output, attention_map
132
+ return output
133
+
134
+ def get_config(self):
135
+ config = super(ExplainableSelfAttention, self).get_config()
136
+ config.update({'units': self.units, 'return_attention': self.return_attention})
137
+ return config
138
+
139
+
140
+ class MaxProbLayer(Layer):
141
+ def __init__(self, **kwargs):
142
+ super(MaxProbLayer, self).__init__(**kwargs)
143
+
144
+ def call(self, inputs):
145
+ return tf.reduce_max(inputs, axis=1, keepdims=True)
146
+
147
+
148
+ CUSTOM_OBJECTS = {
149
+ 'AttentionVisualizer': AttentionVisualizer,
150
+ 'MCDropout': MCDropout,
151
+ 'EvidentialLoss': EvidentialLoss,
152
+ 'EvidentialLayer': EvidentialLayer,
153
+ 'ExplainableSelfAttention': ExplainableSelfAttention,
154
+ 'MaxProbLayer': MaxProbLayer,
155
+ }
156
+
157
+
158
+ # ============================================================
159
+ # TIEN XU LY ANH - GIONG HET LOGIC TRONG GENERATOR TRAINING
160
+ # ============================================================
161
+ def load_slice_from_h5(path):
162
+ """Doc 1 slice tu file .h5 (dataset ten 'image')."""
163
+ with h5py.File(path, 'r') as f:
164
+ if 'image' not in f:
165
+ raise ValueError(f"File h5 khong co dataset 'image': {path}")
166
+ img = f['image'][:].astype(np.float32)
167
+ if img.ndim == 3:
168
+ img = img[..., 0]
169
+ elif img.ndim != 2:
170
+ raise ValueError(f"Shape anh khong hop le: {img.shape}")
171
+ return img
172
+
173
+
174
+ def load_slice_from_image(path):
175
+ """Doc 1 slice tu file anh thuong (.png/.jpg), chuyen ve grayscale."""
176
+ img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
177
+ if img is None:
178
+ raise ValueError(f"Khong doc duoc anh: {path}")
179
+ return img.astype(np.float32)
180
+
181
+
182
+ def preprocess_slice(img_slice):
183
+ """Resize, chuan hoa mean/std, clip, tao 3-channel stack, roi ap dung
184
+ efficientnetv2_preprocess - dung y nhu trong _load_slice/_generate_batch
185
+ cua ImprovedBrainTumorGenerator ban goc."""
186
+ if img_slice.shape != IMG_SIZE:
187
+ img_slice = cv2.resize(img_slice, IMG_SIZE, interpolation=cv2.INTER_LINEAR)
188
+
189
+ mean = np.mean(img_slice)
190
+ std = np.std(img_slice) + 1e-8
191
+ img_slice = (img_slice - mean) / std
192
+ img_slice = np.clip(img_slice, -3, 3)
193
+
194
+ # gia lap 3 slice lan can bang cach lap lai slice trung tam
195
+ stack = np.stack([img_slice, img_slice, img_slice], axis=-1)
196
+
197
+ X = np.expand_dims(stack, axis=0).astype(np.float32) # (1, 299, 299, 3)
198
+ X = efficientnetv2_preprocess(X)
199
+ return X
200
+
201
+
202
+ def load_and_preprocess(path):
203
+ if path.lower().endswith(('.h5', '.hdf5')):
204
+ img_slice = load_slice_from_h5(path)
205
+ else:
206
+ img_slice = load_slice_from_image(path)
207
+ return preprocess_slice(img_slice)
208
+
209
+
210
+ # ============================================================
211
+ # CHAY INFERENCE
212
+ # ============================================================
213
+ def run_inference(model_path, input_path):
214
+ print(f"Dang load model: {model_path}")
215
+ model = tf.keras.models.load_model(model_path, custom_objects=CUSTOM_OBJECTS)
216
+
217
+ print(f"Dang doc va tien xu ly file: {input_path}")
218
+ X = load_and_preprocess(input_path)
219
+
220
+ print("Dang du doan...")
221
+ outputs = model.predict(X, verbose=0)
222
+
223
+ # model tra ve dict cac output (classification, evidential_prob, confidence_score, ...)
224
+ probs = outputs['classification'][0]
225
+ pred_idx = int(np.argmax(probs))
226
+ pred_label = CLASS_NAMES[pred_idx]
227
+
228
+ print("\n" + "=" * 50)
229
+ print("KET QUA DU DOAN")
230
+ print("=" * 50)
231
+ print(f"Nhan du doan: {pred_label}")
232
+ for i, name in enumerate(CLASS_NAMES):
233
+ print(f" P({name}) = {probs[i]:.4f}")
234
+
235
+ if 'confidence_score' in outputs:
236
+ print(f"Confidence score: {float(outputs['confidence_score'][0][0]):.4f}")
237
+ if 'epistemic_uncertainty' in outputs:
238
+ print(f"Epistemic uncertainty: {float(outputs['epistemic_uncertainty'][0][0]):.4f}")
239
+ if 'aleatoric_uncertainty' in outputs:
240
+ print(f"Aleatoric uncertainty: {float(outputs['aleatoric_uncertainty'][0][0]):.4f}")
241
+ print("=" * 50)
242
+
243
+ return outputs
244
+
245
+
246
+ if __name__ == "__main__":
247
+ parser = argparse.ArgumentParser(description="Test model phan loai u nao voi 1 file don le")
248
+ parser.add_argument("--model", required=True, help="Duong dan file model .keras")
249
+ parser.add_argument("--input", required=True, help="Duong dan file .h5 hoac anh (.png/.jpg) can test")
250
+ args = parser.parse_args()
251
+
252
+ run_inference(args.model, args.input)