idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
31,500
def pre_map ( self , function ) : if isinstance ( self . slice , slice ) : for i in range ( * self . slice . indices ( len ( self . layout . fields ) ) ) : function ( self . layout , i ) elif isinstance ( self . slice , list ) : for pointer in self . slice : position = pointer [ 0 ] if len ( position ) == 1 : function ...
Iterates over layout objects pointed in self . slice executing function on them . It passes function penultimate layout object and the position where to find last one
31,501
def wrap ( self , LayoutClass , * args , ** kwargs ) : def wrap_object ( layout_object , j ) : layout_object . fields [ j ] = self . wrapped_object ( LayoutClass , layout_object . fields [ j ] , * args , ** kwargs ) self . pre_map ( wrap_object )
Wraps every layout object pointed in self . slice under a LayoutClass instance with args and kwargs passed .
31,502
def wrap_once ( self , LayoutClass , * args , ** kwargs ) : def wrap_object_once ( layout_object , j ) : if not isinstance ( layout_object , LayoutClass ) : layout_object . fields [ j ] = self . wrapped_object ( LayoutClass , layout_object . fields [ j ] , * args , ** kwargs ) self . pre_map ( wrap_object_once )
Wraps every layout object pointed in self . slice under a LayoutClass instance with args and kwargs passed unless layout object s parent is already a subclass of LayoutClass .
31,503
def wrap_together ( self , LayoutClass , * args , ** kwargs ) : if isinstance ( self . slice , slice ) : start = self . slice . start if self . slice . start is not None else 0 self . layout . fields [ start ] = self . wrapped_object ( LayoutClass , self . layout . fields [ self . slice ] , * args , ** kwargs ) for i i...
Wraps all layout objects pointed in self . slice together under a LayoutClass instance with args and kwargs passed .
31,504
def map ( self , function ) : if isinstance ( self . slice , slice ) : for i in range ( * self . slice . indices ( len ( self . layout . fields ) ) ) : function ( self . layout . fields [ i ] ) elif isinstance ( self . slice , list ) : for pointer in self . slice : position = pointer [ 0 ] layout_object = self . layout...
Iterates over layout objects pointed in self . slice executing function on them It passes function last layout object
31,505
def update_attributes ( self , ** original_kwargs ) : def update_attrs ( layout_object ) : kwargs = original_kwargs . copy ( ) if hasattr ( layout_object , 'attrs' ) : if 'css_class' in kwargs : if 'class' in layout_object . attrs : layout_object . attrs [ 'class' ] += " %s" % kwargs . pop ( 'css_class' ) else : layout...
Updates attributes of every layout object pointed in self . slice using kwargs
31,506
def all ( self ) : self . _check_layout ( ) return LayoutSlice ( self . layout , slice ( 0 , len ( self . layout . fields ) , 1 ) )
Returns all layout objects of first level of depth
31,507
def filter ( self , * LayoutClasses , ** kwargs ) : self . _check_layout ( ) max_level = kwargs . pop ( 'max_level' , 0 ) greedy = kwargs . pop ( 'greedy' , False ) filtered_layout_objects = self . layout . get_layout_objects ( LayoutClasses , max_level = max_level , greedy = greedy ) return LayoutSlice ( self . layout...
Returns a LayoutSlice pointing to layout objects of type LayoutClass
31,508
def filter_by_widget ( self , widget_type ) : self . _check_layout_and_form ( ) layout_field_names = self . layout . get_field_names ( ) filtered_fields = [ ] for pointer in layout_field_names : if isinstance ( self . form . fields [ pointer [ 1 ] ] . widget , widget_type ) : filtered_fields . append ( pointer ) return...
Returns a LayoutSlice pointing to fields with widgets of widget_type
31,509
def get_attributes ( self , template_pack = TEMPLATE_PACK ) : items = { 'form_method' : self . form_method . strip ( ) , 'form_tag' : self . form_tag , 'form_style' : self . form_style . strip ( ) , 'form_show_errors' : self . form_show_errors , 'help_text_inline' : self . help_text_inline , 'error_text_inline' : self ...
Used by crispy_forms_tags to get helper attributes
31,510
def flatatt ( attrs ) : return _flatatt ( { k . replace ( '_' , '-' ) : v for k , v in attrs . items ( ) } )
Convert a dictionary of attributes to a single string .
31,511
def render_crispy_form ( form , helper = None , context = None ) : from crispy_forms . templatetags . crispy_forms_tags import CrispyFormNode if helper is not None : node = CrispyFormNode ( 'form' , 'helper' ) else : node = CrispyFormNode ( 'form' , None ) node_context = Context ( context ) node_context . update ( { 'f...
Renders a form and returns its HTML output .
31,512
def bind ( self , attribute , cls , buffer , fmt , * , offset = 0 , stride = 0 , divisor = 0 , normalize = False ) -> None : self . mglo . bind ( attribute , cls , buffer . mglo , fmt , offset , stride , divisor , normalize )
Bind individual attributes to buffers .
31,513
def source ( uri , consts ) : with open ( uri , 'r' ) as fp : content = fp . read ( ) for key , value in consts . items ( ) : content = content . replace ( f"%%{key}%%" , str ( value ) ) return content
read gl code
31,514
def create_standalone_context ( require = None , ** settings ) -> 'Context' : backend = os . environ . get ( 'MODERNGL_BACKEND' ) if backend is not None : settings [ 'backend' ] = backend ctx = Context . __new__ ( Context ) ctx . mglo , ctx . version_code = mgl . create_standalone_context ( settings ) ctx . _screen = N...
Create a standalone ModernGL context .
31,515
def copy_buffer ( self , dst , src , size = - 1 , * , read_offset = 0 , write_offset = 0 ) -> None : self . mglo . copy_buffer ( dst . mglo , src . mglo , size , read_offset , write_offset )
Copy buffer content .
31,516
def copy_framebuffer ( self , dst , src ) -> None : self . mglo . copy_framebuffer ( dst . mglo , src . mglo )
Copy framebuffer content .
31,517
def detect_framebuffer ( self , glo = None ) -> 'Framebuffer' : res = Framebuffer . __new__ ( Framebuffer ) res . mglo , res . _size , res . _samples , res . _glo = self . mglo . detect_framebuffer ( glo ) res . _color_attachments = None res . _depth_attachment = None res . ctx = self res . extra = None return res
Detect framebuffer .
31,518
def core_profile_check ( self ) -> None : profile_mask = self . info [ 'GL_CONTEXT_PROFILE_MASK' ] if profile_mask != 1 : warnings . warn ( 'The window should request a CORE OpenGL profile' ) version_code = self . version_code if not version_code : major , minor = map ( int , self . info [ 'GL_VERSION' ] . split ( '.' ...
Core profile check .
31,519
def mouse_button_callback ( self , window , button , action , mods ) : button += 1 if button not in [ 1 , 2 ] : return xpos , ypos = glfw . get_cursor_pos ( self . window ) if action == glfw . PRESS : self . example . mouse_press_event ( xpos , ypos , button ) else : self . example . mouse_release_event ( xpos , ypos ,...
Handle mouse button events and forward them to the example
31,520
def write_chunks ( self , data , start , step , count ) -> None : self . mglo . write_chunks ( data , start , step , count )
Split data to count equal parts .
31,521
def read_into ( self , buffer , size = - 1 , * , offset = 0 , write_offset = 0 ) -> None : return self . mglo . read_into ( buffer , size , offset , write_offset )
Read the content into a buffer .
31,522
def clear ( self , size = - 1 , * , offset = 0 , chunk = None ) -> None : self . mglo . clear ( size , offset , chunk )
Clear the content .
31,523
def bind_to_uniform_block ( self , binding = 0 , * , offset = 0 , size = - 1 ) -> None : self . mglo . bind_to_uniform_block ( binding , offset , size )
Bind the buffer to a uniform block .
31,524
def bind_to_storage_buffer ( self , binding = 0 , * , offset = 0 , size = - 1 ) -> None : self . mglo . bind_to_storage_buffer ( binding , offset , size )
Bind the buffer to a shader storage buffer .
31,525
def swap_buffers ( self ) : self . widget . swapBuffers ( ) self . set_default_viewport ( ) self . app . processEvents ( ) self . frames += 1
Swap buffers set viewport trigger events and increment frame counter
31,526
def resize ( self , width : int , height : int ) : self . width = width // self . widget . devicePixelRatio ( ) self . height = height // self . widget . devicePixelRatio ( ) self . buffer_width = width self . buffer_height = height if self . ctx : self . set_default_viewport ( ) super ( ) . resize ( self . buffer_widt...
Replacement for Qt s resizeGL method .
31,527
def key_pressed_event ( self , event ) : if event . key ( ) == self . keys . ESCAPE : self . close ( ) self . example . key_event ( event . key ( ) , self . keys . ACTION_PRESS )
Process Qt key press events forwarding them to the example
31,528
def key_release_event ( self , event ) : self . example . key_event ( event . key ( ) , self . keys . ACTION_RELEASE )
Process Qt key release events forwarding them to the example
31,529
def mouse_move_event ( self , event ) : self . example . mouse_position_event ( event . x ( ) , event . y ( ) )
Forward mouse cursor position events to the example
31,530
def mouse_press_event ( self , event ) : if event . button ( ) not in [ 1 , 2 ] : return self . example . mouse_press_event ( event . x ( ) , event . y ( ) , event . button ( ) )
Forward mouse press events to the example
31,531
def mouse_release_event ( self , event ) : if event . button ( ) not in [ 1 , 2 ] : return self . example . mouse_release_event ( event . x ( ) , event . y ( ) , event . button ( ) )
Forward mouse release events to the example
31,532
def read ( self , viewport = None , components = 3 , * , attachment = 0 , alignment = 1 , dtype = 'f1' ) -> bytes : return self . mglo . read ( viewport , components , attachment , alignment , dtype )
Read the content of the framebuffer .
31,533
def read_into ( self , buffer , viewport = None , components = 3 , * , attachment = 0 , alignment = 1 , dtype = 'f1' , write_offset = 0 ) -> None : if type ( buffer ) is Buffer : buffer = buffer . mglo return self . mglo . read_into ( buffer , viewport , components , attachment , alignment , dtype , write_offset )
Read the content of the framebuffer into a buffer .
31,534
def resize ( self , width , height ) : if self . example : self . example . resize ( width , height )
Should be called every time window is resized so the example can adapt to the new size if needed
31,535
def set_default_viewport ( self ) : if self . aspect_ratio : expected_width = int ( self . buffer_height * self . aspect_ratio ) expected_height = int ( expected_width / self . aspect_ratio ) if expected_width > self . buffer_width : expected_width = self . buffer_width expected_height = int ( expected_width / self . a...
Calculates the viewport based on the configured aspect ratio . Will add black borders and center the viewport if the window do not match the configured viewport . If aspect ratio is None the viewport will be scaled to the entire window size regardless of size .
31,536
def print_context_info ( self ) : print ( "Context Version:" ) print ( 'ModernGL:' , moderngl . __version__ ) print ( 'vendor:' , self . ctx . info [ 'GL_VENDOR' ] ) print ( 'renderer:' , self . ctx . info [ 'GL_RENDERER' ] ) print ( 'version:' , self . ctx . info [ 'GL_VERSION' ] ) print ( 'python:' , sys . version ) ...
Prints moderngl context info .
31,537
def read ( self , * , level = 0 , alignment = 1 ) -> bytes : return self . mglo . read ( level , alignment )
Read the content of the texture into a buffer .
31,538
def parse_args ( args = None ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( '-w' , '--window' , default = "pyqt5" , choices = find_window_classes ( ) , help = 'Name for the window type to use' , ) parser . add_argument ( '-fs' , '--fullscreen' , action = "store_true" , help = 'Open the window in ful...
Parse arguments from sys . argv
31,539
def run ( self , group_x = 1 , group_y = 1 , group_z = 1 ) -> None : return self . mglo . run ( group_x , group_y , group_z )
Run the compute shader .
31,540
def get ( self , key , default ) -> Union [ Uniform , UniformBlock , Subroutine , Attribute , Varying ] : return self . _members . get ( key , default )
Returns a Uniform UniformBlock Subroutine Attribute or Varying .
31,541
def resize ( self , width , height ) : self . width = width self . height = height self . buffer_width , self . buffer_height = self . width , self . height self . set_default_viewport ( ) super ( ) . resize ( self . buffer_width , self . buffer_height )
Sets the new size and buffer size internally
31,542
def process_events ( self ) : for event in sdl2 . ext . get_events ( ) : if event . type == sdl2 . SDL_MOUSEMOTION : self . example . mouse_position_event ( event . motion . x , event . motion . y ) elif event . type == sdl2 . SDL_MOUSEBUTTONUP : if event . button . button in [ 1 , 3 ] : self . example . mouse_press_ev...
Loop through and handle all the queued events .
31,543
def destroy ( self ) : sdl2 . SDL_GL_DeleteContext ( self . context ) sdl2 . SDL_DestroyWindow ( self . window ) sdl2 . SDL_Quit ( )
Gracefully close the window
31,544
def on_key_press ( self , symbol , modifiers ) : self . example . key_event ( symbol , self . keys . ACTION_PRESS )
Pyglet specific key press callback . Forwards and translates the events to the example
31,545
def on_key_release ( self , symbol , modifiers ) : self . example . key_event ( symbol , self . keys . ACTION_RELEASE )
Pyglet specific key release callback . Forwards and translates the events to the example
31,546
def on_mouse_motion ( self , x , y , dx , dy ) : self . example . mouse_position_event ( x , self . buffer_height - y )
Pyglet specific mouse motion callback . Forwards and traslates the event to the example
31,547
def on_mouse_press ( self , x : int , y : int , button , mods ) : if button in [ 1 , 4 ] : self . example . mouse_press_event ( x , self . buffer_height - y , 1 if button == 1 else 2 , )
Handle mouse press events and forward to example window
31,548
def on_mouse_release ( self , x : int , y : int , button , mods ) : if button in [ 1 , 4 ] : self . example . mouse_release_event ( x , self . buffer_height - y , 1 if button == 1 else 2 , )
Handle mouse release events and forward to example window
31,549
def write ( self , face , data , viewport = None , * , alignment = 1 ) -> None : if type ( data ) is Buffer : data = data . mglo self . mglo . write ( face , data , viewport , alignment )
Update the content of the texture .
31,550
def key_event ( self , key , action ) : if action == self . wnd . keys . ACTION_PRESS : if key == self . wnd . keys . SPACE : print ( "Space was pressed" ) if action == self . wnd . keys . ACTION_RELEASE : if key == self . wnd . keys . SPACE : print ( "Space was released" )
Handle key events in a generic way supporting all window types .
31,551
def mouse_press_event ( self , x , y , button ) : if button == 1 : print ( "Left mouse button pressed @" , x , y ) if button == 2 : print ( "Right mouse button pressed @" , x , y )
Reports left and right mouse button presses + position
31,552
def mouse_release_event ( self , x , y , button ) : if button == 1 : print ( "Left mouse button released @" , x , y ) if button == 2 : print ( "Right mouse button released @" , x , y )
Reports left and right mouse button releases + position
31,553
def detect_format ( program , attributes ) -> str : def fmt ( attr ) : return attr . array_length * attr . dimension , attr . shape return ' ' . join ( '%d%s' % fmt ( program [ a ] ) for a in attributes )
Detect format for vertex attributes . The format returned does not contain padding .
31,554
def validate_callback_data ( method ) : @ wraps ( method ) def method_wrapper ( * args , ** kwargs ) : expected = method . __code__ . co_varnames if 'self' in kwargs : gam = kwargs [ 'self' ] del ( kwargs [ 'self' ] ) kwargs [ 'gam' ] = gam missing = [ ] for e in expected : if e == 'self' : continue if e not in kwargs ...
wraps a callback s method to pull the desired arguments from the vars dict also checks to ensure the method s arguments are in the vars dict
31,555
def validate_callback ( callback ) : if not ( hasattr ( callback , '_validated' ) ) or callback . _validated == False : assert hasattr ( callback , 'on_loop_start' ) or hasattr ( callback , 'on_loop_end' ) , 'callback must have `on_loop_start` or `on_loop_end` method' if hasattr ( callback , 'on_loop_start' ) : setattr...
validates a callback s on_loop_start and on_loop_end methods
31,556
def phi ( self , y , mu , edof , weights ) : if self . _known_scale : return self . scale else : return ( np . sum ( weights * self . V ( mu ) ** - 1 * ( y - mu ) ** 2 ) / ( len ( mu ) - edof ) )
GLM scale parameter . for Binomial and Poisson families this is unity for Normal family this is variance
31,557
def sample ( self , mu ) : shape = 1. / self . scale scale = mu / shape return np . random . gamma ( shape = shape , scale = scale , size = None )
Return random samples from this Gamma distribution .
31,558
def _clean_X_y ( X , y ) : return make_2d ( X , verbose = False ) . astype ( 'float' ) , y . astype ( 'float' )
ensure that X and y data are float and correct shapes
31,559
def mcycle ( return_X_y = True ) : motor = pd . read_csv ( PATH + '/mcycle.csv' , index_col = 0 ) if return_X_y : X = motor . times . values y = motor . accel return _clean_X_y ( X , y ) return motor
motorcyle acceleration dataset
31,560
def coal ( return_X_y = True ) : coal = pd . read_csv ( PATH + '/coal.csv' , index_col = 0 ) if return_X_y : y , x = np . histogram ( coal . values , bins = 150 ) X = x [ : - 1 ] + np . diff ( x ) / 2 return _clean_X_y ( X , y ) return coal
coal - mining accidents dataset
31,561
def faithful ( return_X_y = True ) : faithful = pd . read_csv ( PATH + '/faithful.csv' , index_col = 0 ) if return_X_y : y , x = np . histogram ( faithful [ 'eruptions' ] , bins = 200 ) X = x [ : - 1 ] + np . diff ( x ) / 2 return _clean_X_y ( X , y ) return faithful
old - faithful dataset
31,562
def trees ( return_X_y = True ) : trees = pd . read_csv ( PATH + '/trees.csv' , index_col = 0 ) if return_X_y : y = trees . Volume . values X = trees [ [ 'Girth' , 'Height' ] ] . values return _clean_X_y ( X , y ) return trees
cherry trees dataset
31,563
def default ( return_X_y = True ) : default = pd . read_csv ( PATH + '/default.csv' , index_col = 0 ) if return_X_y : default = default . values default [ : , 0 ] = np . unique ( default [ : , 0 ] , return_inverse = True ) [ 1 ] default [ : , 1 ] = np . unique ( default [ : , 1 ] , return_inverse = True ) [ 1 ] X = def...
credit default dataset
31,564
def hepatitis ( return_X_y = True ) : hep = pd . read_csv ( PATH + '/hepatitis_A_bulgaria.csv' ) . astype ( float ) if return_X_y : mask = ( hep . total > 0 ) . values hep = hep [ mask ] X = hep . age . values y = hep . hepatitis_A_positive . values / hep . total . values return _clean_X_y ( X , y ) return hep
hepatitis in Bulgaria dataset
31,565
def toy_classification ( return_X_y = True , n = 5000 ) : X = np . random . rand ( n , 5 ) * 10 - 5 cat = np . random . randint ( 0 , 4 , n ) X = np . c_ [ X , cat ] log_odds = ( - 0.5 * X [ : , 0 ] ** 2 ) + 5 + ( - 0.5 * X [ : , 1 ] ** 2 ) + np . mod ( X [ : , - 1 ] , 2 ) * - 30 p = 1 / ( 1 + np . exp ( - log_odds ) )...
toy classification dataset with irrelevant features
31,566
def head_circumference ( return_X_y = True ) : head = pd . read_csv ( PATH + '/head_circumference.csv' , index_col = 0 ) . astype ( float ) if return_X_y : y = head [ 'head' ] . values X = head [ [ 'age' ] ] . values return _clean_X_y ( X , y ) return head
head circumference for dutch boys
31,567
def chicago ( return_X_y = True ) : chi = pd . read_csv ( PATH + '/chicago.csv' , index_col = 0 ) . astype ( float ) if return_X_y : chi = chi [ [ 'time' , 'tmpd' , 'pm10median' , 'o3median' , 'death' ] ] . dropna ( ) X = chi [ [ 'time' , 'tmpd' , 'pm10median' , 'o3median' ] ] . values y = chi [ 'death' ] . values retu...
Chicago air pollution and death rate data
31,568
def toy_interaction ( return_X_y = True , n = 50000 , stddev = 0.1 ) : X = np . random . uniform ( - 1 , 1 , size = ( n , 2 ) ) X [ : , 1 ] *= 5 y = np . sin ( X [ : , 0 ] * 2 * np . pi * 1.5 ) * X [ : , 1 ] y += np . random . randn ( len ( X ) ) * stddev if return_X_y : return X , y else : data = pd . DataFrame ( np ....
a sinusoid modulated by a linear function
31,569
def gen_multi_data ( n = 5000 ) : X , y = toy_classification ( return_X_y = True , n = 10000 ) lgam = LogisticGAM ( s ( 0 ) + s ( 1 ) + s ( 2 ) + s ( 3 ) + s ( 4 ) + f ( 5 ) ) lgam . fit ( X , y ) plt . figure ( ) for i , term in enumerate ( lgam . terms ) : if term . isintercept : continue plt . plot ( lgam . partial_...
multivariate Logistic problem
31,570
def gen_tensor_data ( ) : X , y = toy_interaction ( return_X_y = True , n = 10000 ) gam = LinearGAM ( te ( 0 , 1 , lam = 0.1 ) ) . fit ( X , y ) XX = gam . generate_X_grid ( term = 0 , meshgrid = True ) Z = gam . partial_dependence ( term = 0 , meshgrid = True ) fig = plt . figure ( figsize = ( 9 , 6 ) ) ax = plt . axe...
toy interaction data
31,571
def expectiles ( ) : X , y = mcycle ( return_X_y = True ) gam50 = ExpectileGAM ( expectile = 0.5 ) . gridsearch ( X , y ) lam = gam50 . lam gam95 = ExpectileGAM ( expectile = 0.95 , lam = lam ) . fit ( X , y ) gam75 = ExpectileGAM ( expectile = 0.75 , lam = lam ) . fit ( X , y ) gam25 = ExpectileGAM ( expectile = 0.25 ...
a bunch of expectiles
31,572
def cholesky ( A , sparse = True , verbose = True ) : if SKSPIMPORT : A = sp . sparse . csc_matrix ( A ) try : F = spcholesky ( A ) P = sp . sparse . lil_matrix ( A . shape ) p = F . P ( ) P [ np . arange ( len ( p ) ) , p ] = 1 L = F . L ( ) L = P . T . dot ( L ) except CholmodNotPositiveDefiniteError as e : raise Not...
Choose the best possible cholesky factorizor .
31,573
def make_2d ( array , verbose = True ) : array = np . asarray ( array ) if array . ndim < 2 : msg = 'Expected 2D input data array, but found {}D. ' 'Expanding to 2D.' . format ( array . ndim ) if verbose : warnings . warn ( msg ) array = np . atleast_1d ( array ) [ : , None ] return array
tiny tool to expand 1D arrays the way i want
31,574
def check_array ( array , force_2d = False , n_feats = None , ndim = None , min_samples = 1 , name = 'Input data' , verbose = True ) : if force_2d : array = make_2d ( array , verbose = verbose ) ndim = 2 else : array = np . array ( array ) dtype = array . dtype if dtype . kind not in [ 'i' , 'f' ] : try : array = array...
tool to perform basic data validation . called by check_X and check_y .
31,575
def check_param ( param , param_name , dtype , constraint = None , iterable = True , max_depth = 2 ) : msg = [ ] msg . append ( param_name + " must be " + dtype ) if iterable : msg . append ( " or nested iterable of depth " + str ( max_depth ) + " containing " + dtype + "s" ) msg . append ( ", but found " + param_name ...
checks the dtype of a parameter and whether it satisfies a numerical contraint
31,576
def get_link_domain ( link , dist ) : domain = np . array ( [ - np . inf , - 1 , 0 , 1 , np . inf ] ) domain = domain [ ~ np . isnan ( link . link ( domain , dist ) ) ] return [ domain [ 0 ] , domain [ - 1 ] ]
tool to identify the domain of a given monotonic link function
31,577
def load_diagonal ( cov , load = None ) : n , m = cov . shape assert n == m , "matrix must be square, but found shape {}" . format ( ( n , m ) ) if load is None : load = np . sqrt ( np . finfo ( np . float64 ) . eps ) return cov + np . eye ( n ) * load
Return the given square matrix with a small amount added to the diagonal to make it positive semi - definite .
31,578
def round_to_n_decimal_places ( array , n = 3 ) : if issubclass ( array . __class__ , float ) and '%.e' % array == str ( array ) : return array shape = np . shape ( array ) out = ( ( np . atleast_1d ( array ) * 10 ** n ) . round ( ) . astype ( 'int' ) / ( 10. ** n ) ) return out . reshape ( shape )
tool to keep round a float to n decimal places .
31,579
def space_row ( left , right , filler = ' ' , total_width = - 1 ) : left = str ( left ) right = str ( right ) filler = str ( filler ) [ : 1 ] if total_width < 0 : spacing = - total_width else : spacing = total_width - len ( left ) - len ( right ) return left + filler * spacing + right
space the data in a row with optional filling
31,580
def gen_edge_knots ( data , dtype , verbose = True ) : if dtype not in [ 'categorical' , 'numerical' ] : raise ValueError ( 'unsupported dtype: {}' . format ( dtype ) ) if dtype == 'categorical' : return np . r_ [ np . min ( data ) - 0.5 , np . max ( data ) + 0.5 ] else : knots = np . r_ [ np . min ( data ) , np . max ...
generate uniform knots from data including the edges of the data
31,581
def ylogydu ( y , u ) : mask = ( np . atleast_1d ( y ) != 0. ) out = np . zeros_like ( u ) out [ mask ] = y [ mask ] * np . log ( y [ mask ] / u [ mask ] ) return out
tool to give desired output for the limit as y - > 0 which is 0
31,582
def combine ( * args ) : if hasattr ( args , '__iter__' ) and ( len ( args ) > 1 ) : subtree = combine ( * args [ : - 1 ] ) tree = [ ] for leaf in subtree : for node in args [ - 1 ] : if hasattr ( leaf , '__iter__' ) : tree . append ( leaf + [ node ] ) else : tree . append ( [ leaf ] + [ node ] ) return tree else : ret...
tool to perform tree search via recursion useful for developing the grid in a grid search
31,583
def isiterable ( obj , reject_string = True ) : iterable = hasattr ( obj , '__len__' ) if reject_string : iterable = iterable and not isinstance ( obj , str ) return iterable
convenience tool to detect if something is iterable . in python3 strings count as iterables to we have the option to exclude them
31,584
def check_iterable_depth ( obj , max_depth = 100 ) : def find_iterables ( obj ) : iterables = [ ] for item in obj : if isiterable ( item ) : iterables += list ( item ) return iterables depth = 0 while ( depth < max_depth ) and isiterable ( obj ) and len ( obj ) > 0 : depth += 1 obj = find_iterables ( obj ) return depth
find the maximum depth of nesting of the iterable
31,585
def flatten ( iterable ) : if isiterable ( iterable ) : flat = [ ] for item in list ( iterable ) : item = flatten ( item ) if not isiterable ( item ) : item = [ item ] flat += item return flat else : return iterable
convenience tool to flatten any nested iterable
31,586
def tensor_product ( a , b , reshape = True ) : assert a . ndim == 2 , 'matrix a must be 2-dimensional, but found {} dimensions' . format ( a . ndim ) assert b . ndim == 2 , 'matrix b must be 2-dimensional, but found {} dimensions' . format ( b . ndim ) na , ma = a . shape nb , mb = b . shape if na != nb : raise ValueE...
compute the tensor protuct of two matrices a and b
31,587
def link ( self , mu , dist ) : return np . log ( mu ) - np . log ( dist . levels - mu )
glm link function this is useful for going from mu to the linear prediction
31,588
def mu ( self , lp , dist ) : elp = np . exp ( lp ) return dist . levels * elp / ( elp + 1 )
glm mean function ie inverse of link function this is useful for going from the linear prediction to mu
31,589
def gradient ( self , mu , dist ) : return dist . levels / ( mu * ( dist . levels - mu ) )
derivative of the link function wrt mu
31,590
def derivative ( n , coef , derivative = 2 , periodic = False ) : if n == 1 : return sp . sparse . csc_matrix ( 0. ) D = sparse_diff ( sp . sparse . identity ( n + 2 * derivative * periodic ) . tocsc ( ) , n = derivative ) . tolil ( ) if periodic : cols = D [ : , : derivative ] D [ : , - 2 * derivative : - derivative ]...
Builds a penalty matrix for P - Splines with continuous features . Penalizes the squared differences between basis coefficients .
31,591
def monotonicity_ ( n , coef , increasing = True ) : if n != len ( coef . ravel ( ) ) : raise ValueError ( 'dimension mismatch: expected n equals len(coef), ' 'but found n = {}, coef.shape = {}.' . format ( n , coef . shape ) ) if n == 1 : return sp . sparse . csc_matrix ( 0. ) if increasing : mask = sp . sparse . diag...
Builds a penalty matrix for P - Splines with continuous features . Penalizes violation of monotonicity in the feature function .
31,592
def none ( n , coef ) : return sp . sparse . csc_matrix ( np . zeros ( ( n , n ) ) )
Build a matrix of zeros for features that should go unpenalized
31,593
def wrap_penalty ( p , fit_linear , linear_penalty = 0. ) : def wrapped_p ( n , * args ) : if fit_linear : if n == 1 : return sp . sparse . block_diag ( [ linear_penalty ] , format = 'csc' ) return sp . sparse . block_diag ( [ linear_penalty , p ( n - 1 , * args ) ] , format = 'csc' ) else : return p ( n , * args ) ret...
tool to account for unity penalty on the linear term of any feature .
31,594
def sparse_diff ( array , n = 1 , axis = - 1 ) : if ( n < 0 ) or ( int ( n ) != n ) : raise ValueError ( 'Expected order is non-negative integer, ' 'but found: {}' . format ( n ) ) if not sp . sparse . issparse ( array ) : warnings . warn ( 'Array is not sparse. Consider using numpy.diff' ) if n == 0 : return array nd ...
A ported sparse version of np . diff . Uses recursion to compute higher order differences
31,595
def _linear_predictor ( self , X = None , modelmat = None , b = None , term = - 1 ) : if modelmat is None : modelmat = self . _modelmat ( X , term = term ) if b is None : b = self . coef_ [ self . terms . get_coef_indices ( term ) ] return modelmat . dot ( b ) . flatten ( )
linear predictor compute the linear predictor portion of the model ie multiply the model matrix by the spline basis coefficients
31,596
def predict_mu ( self , X ) : if not self . _is_fitted : raise AttributeError ( 'GAM has not been fitted. Call fit first.' ) X = check_X ( X , n_feats = self . statistics_ [ 'm_features' ] , edge_knots = self . edge_knots_ , dtypes = self . dtype , features = self . feature , verbose = self . verbose ) lp = self . _lin...
preduct expected value of target given model and input X
31,597
def _modelmat ( self , X , term = - 1 ) : X = check_X ( X , n_feats = self . statistics_ [ 'm_features' ] , edge_knots = self . edge_knots_ , dtypes = self . dtype , features = self . feature , verbose = self . verbose ) return self . terms . build_columns ( X , term = term )
Builds a model matrix B out of the spline basis for each feature
31,598
def _cholesky ( self , A , ** kwargs ) : if sp . sparse . issparse ( A ) : diag = sp . sparse . eye ( A . shape [ 0 ] ) else : diag = np . eye ( A . shape [ 0 ] ) constraint_l2 = self . _constraint_l2 while constraint_l2 <= self . _constraint_l2_max : try : L = cholesky ( A , ** kwargs ) self . _constraint_l2 = constra...
method to handle potential problems with the cholesky decomposition .
31,599
def _pseudo_data ( self , y , lp , mu ) : return lp + ( y - mu ) * self . link . gradient ( mu , self . distribution )
compute the pseudo data for a PIRLS iterations