Пример #1
0
def tp(gt, pred):
    smooth = 1.
    pred_pos = backend.round(backend.clip(pred, 0, 1))
    gt_pos = backend.round(backend.clip(gt, 0, 1))
    tp = (backend.sum(gt_pos * pred_pos) + smooth) / (backend.sum(gt_pos) +
                                                      smooth)
    return tp
Пример #2
0
def tn(y_true, y_pred):
    smooth = 1
    y_pred_pos = K.round(K.clip(y_pred, 0, 1))
    y_pred_neg = 1 - y_pred_pos
    y_pos = K.round(K.clip(y_true, 0, 1))
    y_neg = 1 - y_pos
    tn = (K.sum(y_neg * y_pred_neg) + smooth) / (K.sum(y_neg) + smooth)
    return tn
Пример #3
0
def tn(gt, pred):
    smooth = 1.
    pred_pos = backend.round(backend.clip(pred, 0, 1))  #round(逐元素四舍五入)
    pred_neg = 1 - pred_pos
    gt_pos = backend.round(backend.clip(gt, 0, 1))
    gt_neg = 1 - gt_pos
    tn = (backend.sum(gt_neg * pred_neg) + smooth) / (backend.sum(gt_neg) +
                                                      smooth)
    return tn
Пример #4
0
def recall(y_true, y_pred):
    """Recall metric.
    Only computes a batch-wise average of recall. Computes the recall, a metric
    for multi-label classification of how many relevant items are selected.
    """
    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 call(self, input):
        input_shape = backend.shape(input)

        num_rows = input_shape[1]
        num_cols = input_shape[2]

        row_length = backend.cast(num_rows,
                                  'float32') / (2 * self.circle_number)
        col_length = backend.cast(num_cols,
                                  'float32') / (2 * self.circle_number)

        outputs = []
        pool_circle = []
        for jy in range(self.circle_number * 2):
            for ix in range(self.circle_number * 2):
                x1 = ix * col_length
                x2 = ix * col_length + col_length
                y1 = jy * row_length
                y2 = jy * row_length + row_length

                x1 = backend.cast(backend.round(x1), 'int32')
                x2 = backend.cast(backend.round(x2), 'int32')
                y1 = backend.cast(backend.round(y1), 'int32')
                y2 = backend.cast(backend.round(y2), 'int32')

                new_shape = [input_shape[0], y2 - y1, x2 - x1, input_shape[3]]

                x_crop = input[:, y1:y2, x1:x2, :]
                xm = backend.reshape(x_crop, new_shape)
                if self.pool_mode == 'avg':
                    pooled_val = backend.mean(xm, axis=(1, 2))
                else:
                    pooled_val = backend.max(xm, axis=(1, 2))
                pool_circle.append(
                    backend.reshape(xm, (input_shape[0], -1, input_shape[3])))

        circle_index = self._circle_index(self.circle_number)
        for cidx in circle_index:
            circle_val = [pool_circle[idx] for idx in cidx]
            if self.pool_mode == 'avg':
                pooled_val = backend.mean(backend.concatenate(circle_val,
                                                              axis=1),
                                          axis=1)
            else:
                pooled_val = backend.max(backend.concatenate(circle_val,
                                                             axis=1),
                                         axis=1)

            outputs.append(pooled_val)

        outputs = backend.concatenate(outputs)
        outputs = backend.reshape(
            outputs,
            (input_shape[0], self.nb_channels * self.num_outputs_per_channel))

        return outputs
Пример #6
0
def precision(y_true, y_pred):
    """Precision metric.
    Only computes a batch-wise average of precision. Computes the precision, a
    metric for multi-label classification of how many selected items are
    relevant.
    """
    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
Пример #7
0
def f1(y_true, y_pred):
    smooth = 1.0
    y_label = K.round(K.clip(y_pred, 0, 1))
    y_tp = K.round(K.clip(y_true * y_label, 0, 1))
    y_tp_sum = K.sum(y_tp, axis=1)
    y_true_sum = K.sum(y_true, axis=1)
    y_label_sum = K.sum(y_label, axis=1)
    dice_array = (y_tp_sum * 2 + smooth) / (y_label_sum + y_true_sum + smooth)
    dice = K.mean(dice_array)
    return 1 - dice
Пример #8
0
def artifact_precision(y_true, y_pred):
    weights = y_true[:, :, :, :, 2]

    mask = tf.equal(weights, 1)
    mask_true = tf.boolean_mask(y_true[:, :, :, :, 2], mask)
    mask_pred = tf.boolean_mask(1 - y_pred[:, :, :, :, 0], mask)

    true_positives = K.sum(K.round(K.clip(mask_true * mask_pred, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(mask_pred, 0, 1)))

    precision = true_positives / (predicted_positives + K.epsilon())

    return precision
Пример #9
0
def axon_recall(y_true, y_pred):
    weights = tf.reduce_sum(y_true, axis=-1)

    mask = tf.equal(weights, 1)

    mask_true = tf.boolean_mask(y_true[:, :, :, :, 0], mask)
    mask_pred = tf.boolean_mask(y_pred[:, :, :, :, 0], mask)

    true_positives = K.sum(K.round(K.clip(mask_true * mask_pred, 0, 1)))
    actual_positives = K.sum(K.round(K.clip(mask_true, 0, 1)))

    recall = true_positives / (actual_positives + K.epsilon())

    return recall
Пример #10
0
def axon_precision(y_true, y_pred):
    weights = tf.reduce_sum(y_true, axis=-1)

    mask = tf.equal(weights, 1)

    mask_true = tf.boolean_mask(y_true[:, :, :, :, 0], mask)
    mask_pred = tf.boolean_mask(y_pred[:, :, :, :, 0], mask)

    true_positives = K.sum(K.round(K.clip(mask_true * mask_pred, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(mask_pred, 0, 1)))

    precision = true_positives / (predicted_positives + K.epsilon())

    return precision
Пример #11
0
def get_f1(y_true, y_pred): #taken from old keras source code
    """
        description: F1 value for accuracy
        
        input:  1. Real y to compare from
                2. Predicted y to check accuracy from
        
        output: 1. The F1 value
    """
    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)))
    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
    precision = true_positives / (predicted_positives + K.epsilon())
    recall = true_positives / (possible_positives + K.epsilon())
    f1_val = 2*(precision*recall)/(precision+recall+K.epsilon())
    return f1_val
Пример #12
0
def YOLOCorrectBoxes(box_xy, box_wh, input_shape, image_shape):
    '''Get Corrected Boxes.'''
    box_yx = box_xy[..., ::-1]
    box_hw = box_wh[..., ::-1]

    input_shape = K.cast(input_shape, K.dtype(box_yx))
    image_shape = K.cast(image_shape, K.dtype(box_yx))
    new_shape = K.round(image_shape * K.min(input_shape / image_shape))

    offset = (input_shape - new_shape) / 2. / input_shape
    scale = input_shape / new_shape

    box_yx = (box_yx - offset) * scale
    box_hw *= scale

    box_mins = box_yx - (box_hw / 2.)
    box_max = box_yx + (box_hw / 2.)

    boxes = K.concatenate([
        box_mins[..., 0:1],  #y min
        box_mins[..., 1:2],  #x min
        box_max[..., 0:1],  #y max
        box_max[..., 1:2]  #x max
    ])

    #Scale boxes back to original image shape
    boxes *= K.concatenate([image_shape, image_shape])
    return boxes
Пример #13
0
def yolo_correct_boxes(box_xy, box_wh, input_shape,
                       image_shape):  #调整框的相对大小以适应原始图像的长宽比
    '''Get corrected boxes'''
    box_yx = box_xy[..., ::-1]
    box_hw = box_wh[..., ::-1]
    input_shape = K.cast(input_shape, K.dtype(box_yx))
    image_shape = K.cast(image_shape, K.dtype(box_yx))
    new_shape = K.round(image_shape * K.min(input_shape / image_shape))
    offset = (input_shape - new_shape) / 2. / input_shape
    scale = input_shape / new_shape
    box_yx = (box_yx - offset) * scale
    box_hw *= scale

    box_mins = box_yx - (box_hw / 2.)
    box_maxes = box_yx + (box_hw / 2.)
    boxes = K.concatenate([
        box_mins[..., 0:1],  # y_min
        box_mins[..., 1:2],  # x_min
        box_maxes[..., 0:1],  # y_max
        box_maxes[..., 1:2]  # x_max
    ])

    # Scale boxes back to original image shape.
    boxes *= K.concatenate([image_shape, image_shape])
    return boxes
def fbeta_score(y_true, y_pred, beta):
    '''Calculates the F score, the weighted harmonic mean of precision and recall.
  This is useful for multi-label classification, where input samples can be
  classified as sets of labels. By only using accuracy (precision) a model
  would achieve a perfect score by simply assigning every class to every
  input. In order to avoid this, a metric should penalize incorrect class
  assignments as well (recall). The F-beta score (ranged from 0.0 to 1.0)
  computes this, as a weighted mean of the proportion of correct class
  assignments vs. the proportion of incorrect class assignments.
  With beta = 1, this is equivalent to a F-measure. With beta < 1, assigning
  correct classesas_keras_metric becomes more important, and with beta > 1 the metric is
  instead weighted towards penalizing incorrect class assignments.
  '''
    '''
  https://github.com/keras-team/keras/blob/2b51317be82d4420169d2cc79dc4443028417911/keras/metrics.py
  '''
    if beta < 0:
        raise ValueError('The lowest choosable beta is zero (only precision).')

    # If there are no true positives, fix the F score at 0 like sklearn.
    if K.sum(K.round(K.clip(y_true, 0, 1))) == 0:
        return 0

    p = precision(y_true, y_pred)
    r = recall(y_true, y_pred)
    bb = beta**2
    fbeta_score = (1 + bb) * (p * r) / (bb * p + r + K.epsilon())
    return fbeta_score
Пример #15
0
def brd_max(inputs):
    b_S17 = inputs

    def _each(b_17):
        pT = tf.constant([0.8], dtype=tf.float32)
        pN = tf.constant([0.2], dtype=tf.float32)
        output = b_17 * init_max_value
        logging.getLogger().info("--_each\n  %s" % output)
        output = K.sum(output, axis=None, keepdims=False)
        logging.getLogger().info("--sum\n  %s" % output)
        output = tf.cond(tf.greater(output, init_max_hv), lambda: pT,
                         lambda: pN)
        return output

    def get_pred(inputs):
        b_S17 = inputs
        output = tf.map_fn(lambda x: _each(x), b_S17, dtype=tf.float32)
        return tf.reshape(output, [-1, 1])

    n_pred = brd_mean(b_S17)
    x_pred = get_pred(b_S17)
    n_pred = tf.reshape(n_pred, [-1])
    x_pred = tf.reshape(x_pred, [-1])
    ###
    xt = K.round(K.clip(x_pred, 0, 1))
    xn = 1 - xt
    ###
    output = n_pred * xn + x_pred * xt
    return tf.reshape(output, [-1, 1])
Пример #16
0
def precision(y_target, y_pred):
    # clip(t, clip_value_min, clip_value_max) : clip_value_min~clip_value_max 이외 가장자리를 깎아 낸다
    # round : 반올림한다
    y_pred_yn = K.round(K.clip(y_pred, 0, 1)) # 예측값을 0(Negative) 또는 1(Positive)로 설정한다
    y_target_yn = K.round(K.clip(y_target, 0, 1)) # 실제값을 0(Negative) 또는 1(Positive)로 설정한다

    # True Positive는 실제 값과 예측 값이 모두 1(Positive)인 경우이다
    count_true_positive = K.sum(y_target_yn * y_pred_yn) 

    # (True Positive + False Positive) = 예측 값이 1(Positive) 전체
    count_true_positive_false_positive = K.sum(y_pred_yn)

    # Precision = (True Positive) / (True Positive + False Positive)
    # K.epsilon()는 'divide by zero error' 예방차원에서 작은 수를 더한다
    precision = count_true_positive / (count_true_positive_false_positive + K.epsilon())

    # return a single tensor value
    return precision
Пример #17
0
def f1(y_true, y_pred):
    y_pred = K.round(y_pred)
    tp = K.sum(K.cast(y_true * y_pred, 'float'), axis=0)
    fp = K.sum(K.cast((1 - y_true) * y_pred, 'float'), axis=0)
    fn = K.sum(K.cast(y_true * (1 - y_pred), 'float'), axis=0)

    p = tp / (tp + fp + K.epsilon())
    r = tp / (tp + fn + K.epsilon())

    f1 = 2 * p * r / (p + r + K.epsilon())
    f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)
    return f1
Пример #18
0
def contingency_table(y, z):
    """Note:  if y and z are not rounded to 0 or 1, they are ignored
    """
    y = K.cast(K.round(y), K.floatx())
    z = K.cast(K.round(z), K.floatx())

    def count_matches(y, z):
        return K.sum(K.cast(y, K.floatx()) * K.cast(z, K.floatx()))

    ones = K.ones_like(y)
    zeros = K.zeros_like(y)
    y_ones = K.equal(y, ones)
    y_zeros = K.equal(y, zeros)
    z_ones = K.equal(z, ones)
    z_zeros = K.equal(z, zeros)

    tp = count_matches(y_ones, z_ones)
    tn = count_matches(y_zeros, z_zeros)
    fp = count_matches(y_zeros, z_ones)
    fn = count_matches(y_ones, z_zeros)
    return (tp, tn, fp, fn)
Пример #19
0
def adjusted_accuracy(y_true, y_pred):
    weights = tf.reduce_sum(y_true, axis=-1, keepdims=True)

    mask = K.equal(weights, 1)

    axons_true = y_true[:, :, :, :, 0]
    axons_true = K.expand_dims(axons_true, -1)

    mask_true = tf.boolean_mask(axons_true, mask)
    mask_pred = tf.boolean_mask(y_pred, mask)

    return K.mean(K.equal(mask_true, K.round(mask_pred)))
Пример #20
0
def fbeta_score(y_true, y_pred, beta=1):
    # Calculates the F score, the weighted harmonic mean of precision and recall.
    if beta < 0:
        raise ValueError('The lowest choosable beta is zero (only precision).')

    # If there are no true positives, fix the F score at 0 like sklearn.
    if K.sum(K.round(K.clip(y_true, 0, 1))) == 0:
        return 0

    p = precision(y_true, y_pred)
    r = recall(y_true, y_pred)
    bb = beta**2
    fbeta_score = (1 + bb) * (p * r) / (bb * p + r + K.epsilon())
    return fbeta_score
Пример #21
0
 def recall(y_true, y_pred):
     """Recall metric.
     Computes the recall over the whole batch using threshold_value.
     """
     threshold_value = threshold
     # Adaptation of the "round()" used before to get the predictions. Clipping to make sure that the predicted raw values are between 0 and 1.
     y_pred = K.cast(K.greater(K.clip(y_pred, 0, 1), threshold_value),
                     K.floatx())
     # Compute the number of true positives. Rounding in prevention to make sure we have an integer.
     true_positives = K.round(K.sum(K.clip(y_true * y_pred, 0, 1)))
     # Compute the number of positive targets.
     possible_positives = K.sum(K.clip(y_true, 0, 1))
     recall_ratio = true_positives / (possible_positives + K.epsilon())
     return recall_ratio
 def precision(y_true, y_pred):
     y_true = K.ones_like(y_true)
     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 recall(y_true, y_pred):
     y_true = K.ones_like(y_true)
     true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
     all_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
     recall = true_positives / (all_positives + K.epsilon())
     return recall
Пример #24
0
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
Пример #25
0
def Recall(y_true, y_pred):
    """召回率"""
    tp = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))  # true positives
    pp = K.sum(K.round(K.clip(y_true, 0, 1)))  # possible positives
    recall = tp / (pp + K.epsilon())
    return recall
Пример #26
0
def Precision(y_true, y_pred):
    """精确率"""
    tp = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))  # true positives
    pp = K.sum(K.round(K.clip(y_pred, 0, 1)))  # predicted positives
    precision = tp / (pp + K.epsilon())
    return precision
Пример #27
0
def recall(y_true, y_pred):
    # Calculates the recall
    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
Пример #28
0
def precision(y_true, y_pred):
    # Calculates the precision
    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
Пример #29
0
def binary_accuracy(y_true, y_pred):
    return K.mean(K.equal(y_true, K.round(y_pred)))
Пример #30
0
def label_sum(y_true, y_pred):
    y_label = K.round(K.clip(y_pred, 0, 1))

    return K.mean(K.sum(y_label, axis=1))