<s> from facerec . classifier import SVM <EOL> from facerec . validation import KFoldCrossValidation <EOL> from facerec . model import PredictableModel <EOL> from svmutil import * <EOL> from itertools import product <EOL> import numpy as np <EOL> import logging <EOL> def range_f ( begin , end , step ) : <EOL> seq = [ ] <EOL> while True : <EOL> if step == <NUM_LIT:0> : break <EOL> if step > <NUM_LIT:0> and begin > end : break <EOL> if step < <NUM_LIT:0> and begin < end : break <EOL> seq . append ( begin ) <EOL> begin = begin + step <EOL> return seq <EOL> def grid ( grid_parameters ) : <EOL> grid = [ ] <EOL> for parameter in grid_parameters : <EOL> begin , end , step = parameter <EOL> grid . append ( range_f ( begin , end , step ) ) <EOL> return product ( * grid ) <EOL> def grid_search ( model , X , y , C_range = ( - <NUM_LIT:5> , <NUM_LIT:15> , <NUM_LIT:2> ) , gamma_range = ( <NUM_LIT:3> , - <NUM_LIT:15> , - <NUM_LIT:2> ) , k = <NUM_LIT:5> , num_cores = <NUM_LIT:1> ) : <EOL> if not isinstance ( model , PredictableModel ) : <EOL> raise TypeError ( "<STR_LIT>" ) <EOL> if not isinstance ( model . classifier , SVM ) : <EOL> raise TypeError ( "<STR_LIT>" ) <EOL> logger = logging . getLogger ( "<STR_LIT>" ) <EOL> logger . info ( "<STR_LIT>" ) <EOL> best_parameter = svm_parameter ( "<STR_LIT>" ) <EOL> best_parameter . kernel_type = model . classifier . param . kernel_type <EOL> best_parameter . nu = model . classifier . param . nu <EOL> best_parameter . coef0 = model . classifier . param . coef0 <EOL> if ( gamma_range is None ) or ( model . classifier . param . kernel_type == LINEAR ) : <EOL> gamma_range = ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:1> ) <EOL> best_accuracy = np . finfo ( '<STR_LIT:float>' ) . min <EOL> g = grid ( [ C_range , gamma_range ] ) <EOL> results = [ ] <EOL> for p in g : <EOL> C , gamma = p <EOL> C , gamma = <NUM_LIT:2> ** C , <NUM_LIT:2> ** gamma <EOL> model . classifier . param . C , model . classifier . param . gamma = C , gamma <EOL> cv = KFoldCrossValidation ( model = model , k = k ) <EOL> cv . validate ( X , y ) <EOL> results . append ( [ C , gamma , cv . accuracy ] ) <EOL> if cv . accuracy > best_accuracy : <EOL> logger . info ( "<STR_LIT>" % ( cv . accuracy ) ) <EOL> best_accuracy = cv . accuracy <EOL> best_parameter . C , best_parameter . gamma = C , gamma <EOL> logger . info ( "<STR_LIT>" % ( k , cv . accuracy ) ) <EOL> return best_parameter , results </s>
