<s> import numpy as np <EOL> from scipy . spatial import distance <EOL> from . base import _BaseFeatureExtractor <EOL> class RBFKernelPCA ( _BaseFeatureExtractor ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , gamma = <NUM_LIT> , n_components = None , copy_X = True ) : <EOL> if n_components is not None and n_components < <NUM_LIT:1> : <EOL> raise AttributeError ( '<STR_LIT>' ) <EOL> self . n_components = n_components <EOL> self . gamma = gamma <EOL> self . copy_X = copy_X <EOL> def fit ( self , X ) : <EOL> """<STR_LIT>""" <EOL> self . _check_arrays ( X = X ) <EOL> if self . n_components is None or self . n_components > X . shape [ <NUM_LIT:1> ] : <EOL> n_components = X . shape [ <NUM_LIT:1> ] <EOL> else : <EOL> n_components = self . n_components <EOL> kernel_mat = self . _kernel_matrix ( X = X , gamma = self . gamma ) <EOL> self . e_vals_ , self . e_vecs_ = self . _eigendecom ( kernel_mat ) <EOL> self . X_projected_ = self . _projection_matrix ( eig_vecs = self . e_vecs_ , <EOL> n_components = n_components ) <EOL> if self . copy_X : <EOL> self . X_ = X . copy ( ) <EOL> else : <EOL> self . X_ = X <EOL> return self <EOL> def transform ( self , X ) : <EOL> """<STR_LIT>""" <EOL> if not hasattr ( self , '<STR_LIT>' ) : <EOL> raise AttributeError ( '<STR_LIT>' ) <EOL> self . _check_arrays ( X = X ) <EOL> pair_dist = np . ones ( ( self . X_ . shape [ <NUM_LIT:0> ] , X . shape [ <NUM_LIT:0> ] ) ) <EOL> for idx in range ( X . shape [ <NUM_LIT:0> ] ) : <EOL> pair_dist [ : , idx ] = ( ( self . X_ - X [ idx ] ) ** <NUM_LIT:2> ) . sum ( axis = <NUM_LIT:1> ) <EOL> K = np . exp ( ( - <NUM_LIT:1> ) * self . gamma * pair_dist ) <EOL> e_vecs = self . _projection_matrix ( eig_vecs = self . e_vecs_ , <EOL> n_components = self . n_components ) <EOL> return K . T . dot ( e_vecs / self . e_vals_ [ : e_vecs . shape [ <NUM_LIT:1> ] ] ) <EOL> def _kernel_matrix ( self , X , gamma ) : <EOL> sq_dists = distance . pdist ( X , '<STR_LIT>' ) <EOL> mat_sq_dists = distance . squareform ( sq_dists ) <EOL> K = np . exp ( ( - <NUM_LIT:1> ) * gamma * mat_sq_dists ) <EOL> N = K . shape [ <NUM_LIT:0> ] <EOL> one_n = np . ones ( ( N , N ) ) / N <EOL> K = K - one_n . dot ( K ) - K . dot ( one_n ) + one_n . dot ( K ) . dot ( one_n ) <EOL> return K <EOL> def _eigendecom ( self , kernel_mat ) : <EOL> e_vals , e_vecs = np . linalg . eigh ( kernel_mat ) <EOL> sort_idx = np . argsort ( e_vals ) [ : : - <NUM_LIT:1> ] <EOL> e_vals , e_vecs = e_vals [ sort_idx ] , e_vecs [ : , sort_idx ] <EOL> return e_vals , e_vecs <EOL> def _projection_matrix ( self , eig_vecs , n_components ) : <EOL> matrix_w = np . vstack ( [ eig_vecs [ : , i ] for i in range ( n_components ) ] ) . T <EOL> return matrix_w </s>
