<s> """<STR_LIT>""" <EOL> from __future__ import absolute_import <EOL> import numpy as np <EOL> from random import choice <EOL> from scipy . sparse . csgraph import laplacian <EOL> from sklearn . covariance import graph_lasso <EOL> from sklearn . utils . extmath import pinvh <EOL> from . base_metric import BaseMetricLearner <EOL> class SDML ( BaseMetricLearner ) : <EOL> def __init__ ( self , balance_param = <NUM_LIT:0.5> , sparsity_param = <NUM_LIT> , use_cov = True ) : <EOL> '''<STR_LIT>''' <EOL> self . balance_param = balance_param <EOL> self . sparsity_param = sparsity_param <EOL> self . use_cov = use_cov <EOL> def _prepare_inputs ( self , X , W ) : <EOL> self . X = X <EOL> if self . use_cov : <EOL> self . M = np . cov ( X . T ) <EOL> else : <EOL> self . M = np . identity ( X . shape [ <NUM_LIT:1> ] ) <EOL> L = laplacian ( W , normed = False ) <EOL> self . loss_matrix = self . X . T . dot ( L . dot ( self . X ) ) <EOL> def metric ( self ) : <EOL> return self . M <EOL> def fit ( self , X , W , verbose = False ) : <EOL> """<STR_LIT>""" <EOL> self . _prepare_inputs ( X , W ) <EOL> P = pinvh ( self . M ) + self . balance_param * self . loss_matrix <EOL> emp_cov = pinvh ( P ) <EOL> emp_cov = emp_cov . T . dot ( emp_cov ) <EOL> self . M , _ = graph_lasso ( emp_cov , self . sparsity_param , verbose = verbose ) <EOL> return self <EOL> @ classmethod <EOL> def prepare_constraints ( self , labels , num_points , num_constraints ) : <EOL> a , c = np . random . randint ( len ( labels ) , size = ( <NUM_LIT:2> , num_constraints ) ) <EOL> b , d = np . empty ( ( <NUM_LIT:2> , num_constraints ) , dtype = int ) <EOL> for i , ( al , cl ) in enumerate ( zip ( labels [ a ] , labels [ c ] ) ) : <EOL> b [ i ] = choice ( np . nonzero ( labels == al ) [ <NUM_LIT:0> ] ) <EOL> d [ i ] = choice ( np . nonzero ( labels != cl ) [ <NUM_LIT:0> ] ) <EOL> W = np . zeros ( ( num_points , num_points ) ) <EOL> W [ a , b ] = <NUM_LIT:1> <EOL> W [ c , d ] = - <NUM_LIT:1> <EOL> W [ b , a ] = <NUM_LIT:1> <EOL> W [ d , c ] = - <NUM_LIT:1> <EOL> return W </s>
