<s> from __future__ import absolute_import <EOL> import numpy as np <EOL> import scipy as sp <EOL> from six . moves import range <EOL> from six . moves import zip <EOL> def to_categorical ( y , nb_classes = None ) : <EOL> '''<STR_LIT>''' <EOL> if not nb_classes : <EOL> nb_classes = np . max ( y ) + <NUM_LIT:1> <EOL> Y = np . zeros ( ( len ( y ) , nb_classes ) ) <EOL> for i in range ( len ( y ) ) : <EOL> Y [ i , y [ i ] ] = <NUM_LIT:1.> <EOL> return Y <EOL> def normalize ( a , axis = - <NUM_LIT:1> , order = <NUM_LIT:2> ) : <EOL> l2 = np . atleast_1d ( np . linalg . norm ( a , order , axis ) ) <EOL> l2 [ l2 == <NUM_LIT:0> ] = <NUM_LIT:1> <EOL> return a / np . expand_dims ( l2 , axis ) <EOL> def binary_logloss ( p , y ) : <EOL> epsilon = <NUM_LIT> <EOL> p = sp . maximum ( epsilon , p ) <EOL> p = sp . minimum ( <NUM_LIT:1> - epsilon , p ) <EOL> res = sum ( y * sp . log ( p ) + sp . subtract ( <NUM_LIT:1> , y ) * sp . log ( sp . subtract ( <NUM_LIT:1> , p ) ) ) <EOL> res *= - <NUM_LIT:1.0> / len ( y ) <EOL> return res <EOL> def multiclass_logloss ( P , Y ) : <EOL> npreds = [ P [ i ] [ Y [ i ] - <NUM_LIT:1> ] for i in range ( len ( Y ) ) ] <EOL> score = - ( <NUM_LIT:1.> / len ( Y ) ) * np . sum ( np . log ( npreds ) ) <EOL> return score <EOL> def accuracy ( p , y ) : <EOL> return np . mean ( [ a == b for a , b in zip ( p , y ) ] ) <EOL> def probas_to_classes ( y_pred ) : <EOL> if len ( y_pred . shape ) > <NUM_LIT:1> and y_pred . shape [ <NUM_LIT:1> ] > <NUM_LIT:1> : <EOL> return categorical_probas_to_classes ( y_pred ) <EOL> return np . array ( [ <NUM_LIT:1> if p > <NUM_LIT:0.5> else <NUM_LIT:0> for p in y_pred ] ) <EOL> def categorical_probas_to_classes ( p ) : <EOL> return np . argmax ( p , axis = <NUM_LIT:1> ) <EOL> def convert_kernel ( kernel , dim_ordering = '<STR_LIT>' ) : <EOL> '''<STR_LIT>''' <EOL> new_kernel = np . copy ( kernel ) <EOL> if dim_ordering == '<STR_LIT>' : <EOL> w = kernel . shape [ <NUM_LIT:2> ] <EOL> h = kernel . shape [ <NUM_LIT:3> ] <EOL> for i in range ( w ) : <EOL> for j in range ( h ) : <EOL> new_kernel [ : , : , i , j ] = kernel [ : , : , w - i - <NUM_LIT:1> , h - j - <NUM_LIT:1> ] <EOL> elif dim_ordering == '<STR_LIT>' : <EOL> w = kernel . shape [ <NUM_LIT:0> ] <EOL> h = kernel . shape [ <NUM_LIT:1> ] <EOL> for i in range ( w ) : <EOL> for j in range ( h ) : <EOL> new_kernel [ i , j , : , : ] = kernel [ w - i - <NUM_LIT:1> , h - j - <NUM_LIT:1> , : , : ] <EOL> else : <EOL> raise Exception ( '<STR_LIT>' + str ( dim_ordering ) ) <EOL> return new_kernel </s>
