[iou 추가] How to get accuracy, F1, precision and recall, iou, for a keras model?
Deep Learning/Keras 2021. 8. 14. 13:24위 사이트에 accuracy, F1, precision and recall만 구하는데, 내가 iou 구하는 코드도 추가했다.
def iou_m(y_true, y_pred, dtype=tf.float32):
# tf tensor casting
y_pred = tf.convert_to_tensor(y_pred)
y_pred = tf.cast(y_pred, dtype)
y_true = tf.cast(y_true, y_pred.dtype)
y_pred = tf.squeeze(y_pred)
y_true = tf.squeeze(y_true)
y_true_pos = tf.reshape(y_true, [-1])
y_pred_pos = tf.reshape(y_pred, [-1])
area_intersect = tf.reduce_sum(tf.multiply(y_true_pos, y_pred_pos))
area_true = tf.reduce_sum(y_true_pos)
area_pred = tf.reduce_sum(y_pred_pos)
area_union = area_true + area_pred - area_intersect
return tf.math.divide_no_nan(area_intersect, area_union)
-------------------------------------------------------------------------------------------
from keras import backend as K
def recall_m(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives / (possible_positives + K.epsilon())
return recall
def precision_m(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives / (predicted_positives + K.epsilon())
return precision
def f1_m(y_true, y_pred):
precision = precision_m(y_true, y_pred)
recall = recall_m(y_true, y_pred)
return 2*((precision*recall)/(precision+recall+K.epsilon()))
def iou_m(y_true, y_pred, dtype=tf.float32):
# tf tensor casting
y_pred = tf.convert_to_tensor(y_pred)
y_pred = tf.cast(y_pred, dtype)
y_true = tf.cast(y_true, y_pred.dtype)
y_pred = tf.squeeze(y_pred)
y_true = tf.squeeze(y_true)
y_true_pos = tf.reshape(y_true, [-1])
y_pred_pos = tf.reshape(y_pred, [-1])
area_intersect = tf.reduce_sum(tf.multiply(y_true_pos, y_pred_pos))
area_true = tf.reduce_sum(y_true_pos)
area_pred = tf.reduce_sum(y_pred_pos)
area_union = area_true + area_pred - area_intersect
return tf.math.divide_no_nan(area_intersect, area_union)
# compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc',f1_m,precision_m, recall_m])
# fit the model
history = model.fit(Xtrain, ytrain, validation_split=0.3, epochs=10, verbose=0)
# evaluate the model
loss, accuracy, f1_score, precision, recall = model.evaluate(Xtest, ytest, verbose=0)