Advertisement
Guest User

Untitled

a guest
Jun 25th, 2018
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. import keras.backend as K
  2. import numpy as np
  3.  
  4. inp = Input(shape=(x_train_show.shape[1],1000))
  5. nnet = Dense(64, activation='relu')(inp)
  6. nnet = Dropout(0.1)(nnet)
  7. nnet = Dense(128, activation='relu')(nnet)
  8. output = Dense(1, activation='sigmoid')(nnet)
  9. model = Model(inputs=inp, outputs=output)
  10.  
  11. spec_loss = specificity_loss_wrapper()
  12. model.compile(loss=spec_loss,optimizer=Adam(lr=0.00001))
  13.  
  14.  
  15. def compute_specificity(y_pred, y_true):
  16.     """Compute the confusion matrix for a set of predictions.
  17.  
  18.    Parameters
  19.    ----------
  20.    y_pred   : predicted values for a batch if samples (must be binary: 0 or 1)
  21.    y_true   : correct values for the set of samples used (must be binary: 0 or 1)
  22.  
  23.    Returns
  24.    -------
  25.    out : the specificity
  26.    """
  27.  
  28.     num_classes = 2
  29.     conf_mat = np.zeros((num_classes, num_classes))
  30.  
  31.     for i in range(K.flatten(y_true).shape[0].value):
  32.         conf_mat[y_true[i]][y_pred[i]] += 1
  33.  
  34.     # Convert the conf_mat to a Keras Tensor
  35.     conf_mat = K.variable(conf_mat, dtype=np.int32))
  36.  
  37.     # Compute the actual specificity
  38.     specificity = conf_mat[0,0] / (conf_mat[0,0] + conf_mat[0, 1])
  39.  
  40.     # Could also compute other metrics from the conf_mat, such as:
  41.     # sensitivity, false discovery rate, F1 score, Jaccard index etc.
  42.  
  43.     return specificity
  44.  
  45. def specificity_loss_wrapper():
  46.     """A wrapper to create and return a function which computes the specificity loss, as (1 - specificity)
  47.  
  48.    """
  49.     # Define the function for your loss
  50.     def specificity_loss(y_true, y_pred):
  51.         return 1.0 - compute_specificity(y_true, y_pred)
  52.  
  53.     return specificity_loss    # we return this function object
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement