idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
34,800 | def close_filenos ( preserve ) : maxfd = resource . getrlimit ( resource . RLIMIT_NOFILE ) [ 1 ] if maxfd == resource . RLIM_INFINITY : maxfd = 4096 for fileno in range ( maxfd ) : if fileno not in preserve : try : os . close ( fileno ) except OSError as err : if not err . errno == errno . EBADF : raise DaemonError ( '... | Close unprotected file descriptors |
34,801 | def default_signal_map ( ) : name_map = { 'SIGTSTP' : None , 'SIGTTIN' : None , 'SIGTTOU' : None , 'SIGTERM' : 'terminate' } signal_map = { } for name , target in list ( name_map . items ( ) ) : if hasattr ( signal , name ) : signal_map [ getattr ( signal , name ) ] = target return signal_map | Create the default signal map for this system . |
34,802 | def parent_is_inet ( ) : result = False sock = socket . fromfd ( sys . __stdin__ . fileno ( ) , socket . AF_INET , socket . SOCK_RAW ) try : sock . getsockopt ( socket . SOL_SOCKET , socket . SO_TYPE ) result = True except ( OSError , socket . error ) as err : if not err . args [ 0 ] == errno . ENOTSOCK : result = True... | Check if parent is inet |
34,803 | def redirect_stream ( system , target ) : if target is None : target_fd = os . open ( os . devnull , os . O_RDWR ) else : target_fd = target . fileno ( ) try : os . dup2 ( target_fd , system . fileno ( ) ) except OSError as err : raise DaemonError ( 'Could not redirect {0} to {1}: {2}' . format ( system , target , err ... | Redirect Unix streams |
34,804 | def _get_signal_handler ( self , handler ) : if not handler : result = signal . SIG_IGN elif isinstance ( handler , string_types ) : result = getattr ( self , handler ) else : result = handler return result | get the callback function for handler |
34,805 | def _files_preserve ( self ) : result = set ( ) files = [ ] if not self . files_preserve else self . files_preserve files . extend ( [ self . stdin , self . stdout , self . stderr ] ) for item in files : if hasattr ( item , 'fileno' ) : result . add ( item . fileno ( ) ) if isinstance ( item , int ) : result . add ( it... | create a set of protected files |
34,806 | def working_directory ( self ) : if self . chroot_directory and not self . _working_directory . startswith ( self . chroot_directory ) : return self . chroot_directory + self . _working_directory else : return self . _working_directory | The working_directory property |
34,807 | def register ( model , app = None , manager_name = "history" , records_class = None , table_name = None , ** records_config ) : from . import models if records_class is None : records_class = models . HistoricalRecords records = records_class ( ** records_config ) records . manager_name = manager_name records . table_n... | Create historical model for model and attach history manager to model . |
34,808 | def get_urls ( self ) : urls = super ( SimpleHistoryAdmin , self ) . get_urls ( ) admin_site = self . admin_site opts = self . model . _meta info = opts . app_label , opts . model_name history_urls = [ url ( "^([^/]+)/history/([^/]+)/$" , admin_site . admin_view ( self . history_form_view ) , name = "%s_%s_simple_histo... | Returns the additional urls used by the Reversion admin . |
34,809 | def save_model ( self , request , obj , form , change ) : obj . _history_user = request . user super ( SimpleHistoryAdmin , self ) . save_model ( request , obj , form , change ) | Set special model attribute to user for reference after save |
34,810 | def _bulk_history_create ( self , model , batch_size ) : instances = [ ] history = utils . get_history_manager_for_model ( model ) if self . verbosity >= 1 : self . stdout . write ( "Starting bulk creating history models for {} instances {}-{}" . format ( model , 0 , batch_size ) ) iterator_kwargs = ( { "chunk_size" : ... | Save a copy of all instances to the historical model . |
34,811 | def transform_field ( field ) : field . name = field . attname if isinstance ( field , models . AutoField ) : field . __class__ = models . IntegerField elif isinstance ( field , models . FileField ) : field . __class__ = models . TextField field . auto_now = False field . auto_now_add = False if field . primary_key or ... | Customize field appropriately for use in historical model |
34,812 | def create_history_model ( self , model , inherited ) : attrs = { "__module__" : self . module , "_history_excluded_fields" : self . excluded_fields , } app_module = "%s.models" % model . _meta . app_label if inherited : attrs [ "__module__" ] = model . __module__ elif model . __module__ != self . module : attrs [ "__m... | Creates a historical model to associate with the model provided . |
34,813 | def copy_fields ( self , model ) : fields = { } for field in self . fields_included ( model ) : field = copy . copy ( field ) field . remote_field = copy . copy ( field . remote_field ) if isinstance ( field , OrderWrt ) : field . __class__ = models . IntegerField if isinstance ( field , models . ForeignKey ) : old_fie... | Creates copies of the model s original fields returning a dictionary mapping field name to copied field object . |
34,814 | def get_extra_fields ( self , model , fields ) : def revert_url ( self ) : opts = model . _meta app_label , model_name = opts . app_label , opts . model_name return reverse ( "%s:%s_%s_simple_history" % ( admin . site . name , app_label , model_name ) , args = [ getattr ( self , opts . pk . attname ) , self . history_i... | Return dict of extra fields added to the historical record model |
34,815 | def get_meta_options ( self , model ) : meta_fields = { "ordering" : ( "-history_date" , "-history_id" ) , "get_latest_by" : "history_date" , } if self . user_set_verbose_name : name = self . user_set_verbose_name else : name = format_lazy ( "historical {}" , smart_text ( model . _meta . verbose_name ) ) meta_fields [ ... | Returns a dictionary of fields that will be added to the Meta inner class of the historical record model . |
34,816 | def get_history_user ( self , instance ) : try : return instance . _history_user except AttributeError : request = None try : if self . thread . request . user . is_authenticated : request = self . thread . request except AttributeError : pass return self . get_user ( instance = instance , request = request ) | Get the modifying user from instance or middleware . |
34,817 | def most_recent ( self ) : if not self . instance : raise TypeError ( "Can't use most_recent() without a {} instance." . format ( self . model . _meta . object_name ) ) tmp = [ ] excluded_fields = getattr ( self . model , "_history_excluded_fields" , [ ] ) for field in self . instance . _meta . fields : if field . name... | Returns the most recent copy of the instance available in the history . |
34,818 | def as_of ( self , date ) : if not self . instance : return self . _as_of_set ( date ) queryset = self . get_queryset ( ) . filter ( history_date__lte = date ) try : history_obj = queryset [ 0 ] except IndexError : raise self . instance . DoesNotExist ( "%s had not yet been created." % self . instance . _meta . object_... | Get a snapshot as of a specific date . |
34,819 | def bulk_history_create ( self , objs , batch_size = None ) : historical_instances = [ self . model ( history_date = getattr ( instance , "_history_date" , now ( ) ) , history_user = getattr ( instance , "_history_user" , None ) , history_change_reason = getattr ( instance , "changeReason" , "" ) , history_type = "+" ,... | Bulk create the history for the objects specified by objs |
34,820 | def get_history_manager_for_model ( model ) : try : manager_name = model . _meta . simple_history_manager_attribute except AttributeError : raise NotHistoricalModelError ( "Cannot find a historical model for {model}." . format ( model = model ) ) return getattr ( model , manager_name ) | Return the history manager for a given app model . |
34,821 | def pop_parameter ( key ) : names = key . split ( '/' ) if len ( names ) > 1 : with parameter_scope ( names [ 0 ] ) : return pop_parameter ( '/' . join ( names [ 1 : ] ) ) global current_scope param = current_scope . get ( key , None ) if param is not None : del current_scope [ key ] return param | Remove and get parameter by key . |
34,822 | def get_parameter_or_create ( name , shape = None , initializer = None , need_grad = True , as_need_grad = None ) : names = name . split ( '/' ) if len ( names ) > 1 : with parameter_scope ( names [ 0 ] ) : return get_parameter_or_create ( '/' . join ( names [ 1 : ] ) , shape , initializer , need_grad , as_need_grad ) ... | Returns an existing parameter variable with the provided name . If a variable with the provided name does not exist a new variable with the provided name is returned . |
34,823 | def get_parameters ( params = None , path = '' , grad_only = True ) : global current_scope if params is None : params = OrderedDict ( ) for k , v in iteritems ( current_scope ) : if isinstance ( v , dict ) : with parameter_scope ( k ) : params = get_parameters ( params , '/' . join ( [ path , k ] ) if path else k , gra... | Get parameter Variables under the current parameter scope . |
34,824 | def import_extension_module ( ext_name ) : import importlib try : return importlib . import_module ( '.' + ext_name , 'nnabla_ext' ) except ImportError as e : from nnabla import logger logger . error ( 'Extension `{}` does not exist.' . format ( ext_name ) ) raise e | Import an extension module by name . |
34,825 | def list_extensions ( ) : import nnabla_ext . cpu from os . path import dirname , join , realpath from os import listdir ext_dir = realpath ( ( join ( dirname ( nnabla_ext . cpu . __file__ ) , '..' ) ) ) return listdir ( ext_dir ) | List up available extensions . |
34,826 | def imsave ( path , img , channel_first = False , as_uint16 = False , auto_scale = True ) : img = _imsave_before ( img , channel_first , auto_scale ) if img . dtype == np . uint16 or as_uint16 : raise ValueError ( "Pillow only supports uint8 image to save. Cast img to uint8." "If you want to save image as uint16, insta... | Save image by pillow module . Currently pillow supports only uint8 to save . |
34,827 | def get_network ( self , name , batch_size = None , callback = None ) : network_proto = nnabla_pb2 . Network ( ) network_proto . CopyFrom ( self . network_dict [ name ] ) return NnpNetwork ( network_proto , self . _params , batch_size , callback = callback ) | Create a variable graph given network by name |
34,828 | def set_function_name ( func , node_name , base_name , func_counter ) : func . name , count = generate_function_name ( func . type , base_name , node_name , func_counter ) update_function_counter ( func . type , func_counter , count ) | Set a sufficient name for the function |
34,829 | def generate_transpose ( node_name , in_name , out_name , axes , base_name , func_counter ) : trans = nnabla_pb2 . Function ( ) trans . type = "Transpose" set_function_name ( trans , node_name , base_name , func_counter ) trans . input . extend ( [ in_name ] ) trans . output . extend ( [ out_name ] ) tp = trans . trans... | Generate a Transpose operator to transpose the specified buffer . |
34,830 | def generate_broadcast_to ( node_name , x , y , out_name , axis , base_name , func_counter ) : bt = nnabla_pb2 . Function ( ) bt . type = "BroadcastTo" set_function_name ( bt , node_name , base_name , func_counter ) bt . input . extend ( [ x , y ] ) bt . output . extend ( [ out_name ] ) btp = bt . broadcast_to_param bt... | Generate a BroadcastTo operator to brodcast specified buffer |
34,831 | def convert_parameter_shape ( pb ) : if len ( pb . network ) != 1 : raise ValueError ( "NNP with more then a single network is currently not supported" ) net = pb . network [ 0 ] batch_norm_constants = [ ] for f in net . function : if f . type == "BatchNormalization" : batch_norm_constants . extend ( f . input [ 1 : 5 ... | Convert the shape of some parameters so they fit NNabla s requirements . We do this as a post conversion because in the future we may be able to delete the whole conversion if NNabla s code gets changed |
34,832 | def add_tensor_as_parameter ( pb , tensor ) : p = pb . parameter . add ( ) p . variable_name = tensor . name p . shape . dim . extend ( tensor . dims ) if tensor . data_type == TensorProto . FLOAT : if tensor . raw_data : p . data . extend ( np . fromstring ( tensor . raw_data , dtype = np . float32 ) ) elif len ( tens... | Add given tensor as a parameter |
34,833 | def BroadcastOperator ( self , func_name , func_list , n ) : broadcasting = False broadcast_axis = - 1 func = self . generate_default_function ( func_name , n ) for attr in n . attribute : if attr . name == "axis" : if attr . type != AttributeProto . INT : raise ValueError ( "Only INT is supported for axis in {} op_typ... | Converts a broadcasting operator to a composite with BroadcastTo |
34,834 | def imread ( path , grayscale = False , size = None , interpolate = "bilinear" , channel_first = False , as_uint16 = False , num_channels = - 1 ) : _imread_before ( grayscale , num_channels ) f = path if hasattr ( path , "read" ) else open ( path , "rb" ) r = png . Reader ( file = f ) width , height , pixels , metadata... | Read image by pypng module . |
34,835 | def imsave ( path , img , channel_first = False , as_uint16 = False , auto_scale = True ) : img = _imsave_before ( img , channel_first , auto_scale ) if auto_scale : img = upscale_pixel_intensity ( img , as_uint16 ) img = check_type_and_cast_if_necessary ( img , as_uint16 ) bitdepth = 8 if img . dtype == np . uint8 els... | Save image by pypng module . |
34,836 | def context_scope ( ctx ) : global current_ctx global context_level context_level += 1 prev_context = current_ctx current_ctx = ctx try : yield finally : context_level -= 1 current_ctx = prev_context | Context as Python context . |
34,837 | def generate_scalar_constant ( output_name , tensor_name , scalar ) : t = onnx . helper . make_tensor ( tensor_name , data_type = TensorProto . FLOAT , dims = [ 1 ] , vals = [ scalar ] ) c = onnx . helper . make_node ( "Constant" , [ ] , [ output_name ] , value = t ) return c | Convert a scalar value to a Constant buffer . This is mainly used for xxScalar operators . |
34,838 | def replace_negative_size_with_batch_size ( shape , batch_size ) : sl = [ ] for d in shape . dim : if d < 0 : sl . append ( batch_size ) else : sl . append ( d ) out_shape = nnabla_pb2 . Shape ( ) out_shape . dim . extend ( sl ) return out_shape | Replace all dimensions with negative values to batch size |
34,839 | def BinarySigmoid ( self , func ) : n = onnx . helper . make_node ( 'HardSigmoid' , func . input , func . output , alpha = 1.0 , beta = 0.0 ) return [ n ] | Currently caffe2 does not support this function . |
34,840 | def convert ( self , vroot , entry_variables ) : for converter in self . converters : vroot = converter . convert ( vroot , entry_variables ) return vroot | Convert a given graph . |
34,841 | def calc_normal_std_he_forward ( inmaps , outmaps , kernel = ( 1 , 1 ) ) : r return np . sqrt ( 2. / ( np . prod ( kernel ) * inmaps ) ) | r Calculates the standard deviation proposed by He et al . |
34,842 | def calc_normal_std_glorot ( inmaps , outmaps , kernel = ( 1 , 1 ) ) : r return np . sqrt ( 2. / ( np . prod ( kernel ) * inmaps + outmaps ) ) | r Calculates the standard deviation proposed by Glorot et al . |
34,843 | def calc_uniform_lim_glorot ( inmaps , outmaps , kernel = ( 1 , 1 ) ) : r d = np . sqrt ( 6. / ( np . prod ( kernel ) * inmaps + outmaps ) ) return - d , d | r Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al . |
34,844 | def _get_unique_function_name ( function_type , functions ) : function_name = function_name_base = function_type count = 2 while function_name in functions : function_name = '{}_{}' . format ( function_name_base , count ) count += 1 return function_name | Get a unique function name . |
34,845 | def _get_unique_variable_name ( vname , variables ) : count = 2 vname_base = vname while vname in variables : vname = '{}_{}' . format ( vname_base , count ) count += 1 return vname | Get a unique variable name . |
34,846 | def sum ( x , axis = None , keepdims = False ) : from . function_bases import sum as sum_base if axis is None : axis = range ( x . ndim ) elif not hasattr ( axis , '__iter__' ) : axis = [ axis ] return sum_base ( x , axis , keepdims ) | Reduction along axes with sum operation . |
34,847 | def mean ( x , axis = None , keepdims = False ) : from . function_bases import mean as mean_base if axis is None : axis = range ( x . ndim ) elif not hasattr ( axis , '__iter__' ) : axis = [ axis ] return mean_base ( x , axis , keepdims ) | Reduction along axes with mean operation . |
34,848 | def prod ( x , axis = None , keepdims = False ) : from . function_bases import prod as prod_base if axis is None : axis = range ( x . ndim ) elif not hasattr ( axis , '__iter__' ) : axis = [ axis ] return prod_base ( x , axis , keepdims ) | Reduction along axes with product operation . |
34,849 | def reduce ( x , op = 'sum' ) : import warnings warnings . warn ( "Deprecated API. Use ``sum`` or ``mean`` instead." , DeprecationWarning ) from . function_bases import reduce_sum , reduce_mean if op == 'sum' : return reduce_sum ( x ) elif op == 'mean' : return reduce_mean ( x ) raise ValueError ( ) | Reduction function with given operation . |
34,850 | def split ( x , axis = 0 ) : from . function_bases import split as split_base return split_base ( x , axis , x . shape [ axis ] ) | Split arrays at the specified axis . |
34,851 | def batch_normalization ( x , beta , gamma , mean , variance , axes = [ 1 ] , decay_rate = 0.9 , eps = 1e-05 , batch_stat = True , output_stat = False , n_outputs = None ) : r from . function_bases import batch_normalization as batch_normalization_base n_outputs = 3 if output_stat else 1 assert batch_stat or ( not outp... | r Batch normalization . |
34,852 | def fixed_point_quantize ( x , sign = True , n = 8 , delta = 2 ** - 4 , quantize = True , ste_fine_grained = True , outputs = None ) : r from . function_bases import fixed_point_quantize as fixed_point_quantize_base if not quantize : return x return fixed_point_quantize_base ( x , sign , n , delta , ste_fine_grained , ... | r Fixed Point Quantize |
34,853 | def pow2_quantize ( x , sign = True , with_zero = True , n = 8 , m = 1 , quantize = True , ste_fine_grained = True , outputs = None ) : r from . function_bases import pow2_quantize as pow2_quantize_base if not quantize : return x return pow2_quantize_base ( x , sign , with_zero , n , m , ste_fine_grained , outputs = ou... | r Pow2 Quantize |
34,854 | def clip_by_value ( x , min , max ) : r from . function_bases import maximum2 as maximum2_base from . function_bases import minimum2 as minimum2_base return minimum2_base ( maximum2_base ( x , min ) , max ) | r Clip inputs by values . |
34,855 | def interpolate ( x , scale = None , output_size = None , mode = 'linear' , align_corners = None ) : from . function_bases import interpolate as interpolate_base import math if scale is None and output_size is None : raise ValueError ( 'Either scale or output_size must be given' ) elif output_size is None : output_size... | Resize an ND array with interpolation . |
34,856 | def sort ( x , axis = - 1 , reverse = False , with_index = False , only_index = False ) : from . function_bases import sort as sort_base n_outputs = 2 if with_index and not only_index else 1 return sort_base ( x , axis , reverse , with_index , only_index , n_outputs ) | Sorts the elements of x along a given axis in ascending order by value . A negative axis counts from the last dimension of x so the default of - 1 sorts along the last dimension . If reverse is True then the elements are soreted in descending order . |
34,857 | def download ( url , output_file = None , open_file = True , allow_overwrite = False ) : filename = url . split ( '/' ) [ - 1 ] if output_file is None : cache = os . path . join ( get_data_home ( ) , filename ) else : cache = output_file if os . path . exists ( cache ) and not allow_overwrite : logger . info ( "> {} al... | Download a file from URL . |
34,858 | def imread ( path , grayscale = False , size = None , interpolate = "bilinear" , channel_first = False , as_uint16 = False , num_channels = - 1 ) : _imread_before ( grayscale , num_channels ) r_mode = cv2 . IMREAD_GRAYSCALE if grayscale else cv2 . IMREAD_UNCHANGED img = _imread_helper ( path , r_mode ) if as_uint16 and... | Read image by cv2 module . |
34,859 | def get_learning_rate ( self , iter ) : return self . init_lr * ( ( 1.0 - iter * 1.0 / self . max_iter ) ** self . power ) | Get learning rate with polymomial decay based on current iteration . |
34,860 | def get_learning_rate ( self , iter ) : return self . init_lr * ( ( math . cos ( iter * 1.0 / ( self . max_iter ) * math . pi ) + 1.0 ) * 0.5 ) | Get learning rate with cosine decay based on current iteration . |
34,861 | def affine ( inp , n_outmaps , base_axis = 1 , w_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True , apply_w = None , apply_b = None ) : if not hasattr ( n_outmaps , '__iter__' ) : n_outmaps = [ n_outmaps ] n_outmaps = list ( n_outmaps ) n_outmap = int ( np . prod ( n_outmaps ) ) if w... | The affine layer also known as the fully connected layer . Computes |
34,862 | def binary_weight_affine ( inp , n_outmaps , base_axis = 1 , quantize_zero_to = 1.0 , w_init = None , wb_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True ) : if not hasattr ( n_outmaps , '__iter__' ) : n_outmaps = [ n_outmaps ] n_outmaps = list ( n_outmaps ) n_outmap = int ( np . pro... | Binary Weight Affine multiplier - less inner - product with a scale factor . |
34,863 | def inq_affine ( inp , n_outmaps , base_axis = 1 , num_bits = 4 , inq_iterations = ( ) , selection_algorithm = 'random' , seed = - 1 , w_init = None , i_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True ) : if not hasattr ( n_outmaps , '__iter__' ) : n_outmaps = [ n_outmaps ] n_outmap... | Incremental Network Quantization Affine Layer |
34,864 | def binary_connect_convolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , quantize_zero_to = 1.0 , w_init = None , wb_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True ) : if w_init is None : w_init = UniformInitializer ( calc... | Binary Connect Convolution multiplier - less inner - product . |
34,865 | def inq_convolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , num_bits = 4 , inq_iterations = ( ) , selection_algorithm = 'random' , seed = - 1 , w_init = None , i_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True ) : if w_in... | Incremental Network Quantization Convolution Layer |
34,866 | def depthwise_convolution ( inp , kernel , pad = None , stride = None , dilation = None , multiplier = 1 , w_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True ) : if w_init is None : w_init = UniformInitializer ( calc_uniform_lim_glorot ( inp . shape [ base_axis ] * mu... | N - D Depthwise Convolution with a bias term . |
34,867 | def batch_normalization ( inp , axes = [ 1 ] , decay_rate = 0.9 , eps = 1e-5 , batch_stat = True , output_stat = False , fix_parameters = False , param_init = None ) : shape_stat = [ 1 for _ in inp . shape ] for i in range ( len ( axes ) ) : shape_stat [ axes [ i ] ] = inp . shape [ axes [ i ] ] if param_init is None :... | Batch normalization layer . |
34,868 | def mean_subtraction ( inp , base_axis = 1 , update_running_mean = True , fix_parameters = False ) : assert len ( inp . shape ) >= base_axis shape = inp . shape [ base_axis : ] mean = get_parameter_or_create ( "mean" , shape , ConstantInitializer ( 0 ) , False ) t = get_parameter_or_create ( "t" , ( 1 , ) , ConstantIni... | Mean subtraction layer . |
34,869 | def prelu ( inp , base_axis = 1 , shared = True , fix_parameters = False ) : shape = tuple ( ) if shared else ( inp . shape [ base_axis ] , ) w = get_parameter_or_create ( "slope" , shape , ConstantInitializer ( - 1 ) , True , not fix_parameters ) return F . prelu ( inp , w , base_axis ) | Parametrized Rectified Linear Unit function defined as |
34,870 | def fixed_point_quantized_affine ( inp , n_outmaps , base_axis = 1 , w_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True , quantize_w = True , sign_w = True , n_w = 8 , delta_w = 2 ** - 4 , ste_fine_grained_w = True , quantize_b = True , sign_b = True , n_b = 8 , delta_b = 2 ** - 4 , ... | Fixed - Point Quantized Affine . |
34,871 | def fixed_point_quantized_convolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , w_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True , quantize_w = True , sign_w = True , n_w = 8 , delta_w = 2 ** - 4 , ste_fine_grained_w = Tru... | Fixed - Point Quantized Convolution . |
34,872 | def pow2_quantized_affine ( inp , n_outmaps , base_axis = 1 , w_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True , quantize_w = True , sign_w = True , with_zero_w = False , n_w = 8 , m_w = 2 , ste_fine_grained_w = True , quantize_b = True , sign_b = True , with_zero_b = False , n_b =... | Pow2 Quantized Affine . |
34,873 | def pow2_quantized_convolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , w_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True , quantize_w = True , with_zero_w = False , sign_w = True , n_w = 8 , m_w = 2 , ste_fine_grained_w =... | Pow2 Quantized Convolution . |
34,874 | def pruned_affine ( inp , n_outmaps , base_axis = 1 , w_init = None , b_init = None , fix_parameters = False , rng = None , with_bias = True , prune_w = True , rate_w = 0.9 , prune_b = True , rate_b = 0.9 ) : if not hasattr ( n_outmaps , '__iter__' ) : n_outmaps = [ n_outmaps ] n_outmaps = list ( n_outmaps ) n_outmap =... | Pruned Affine . |
34,875 | def pruned_convolution ( inp , outmaps , kernel , pad = None , stride = None , dilation = None , group = 1 , w_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True , prune_w = True , rate_w = 0.9 , prune_b = True , rate_b = 0.9 ) : if w_init is None : w_init = UniformInit... | Pruned Convolution . |
34,876 | def lstm_cell ( x , h , c , state_size , w_init = None , b_init = None , fix_parameters = False ) : xh = F . concatenate ( * ( x , h ) , axis = 1 ) iofc = affine ( xh , ( 4 , state_size ) , w_init = w_init , b_init = b_init , fix_parameters = fix_parameters ) i_t , o_t , f_t , gate = F . split ( iofc , axis = 1 ) c_t =... | Long Short - Term Memory . |
34,877 | def spectral_norm ( w , dim = 0 , itr = 1 , eps = 1e-12 , test = False , u_init = None , fix_parameters = True ) : assert ( 0 <= dim and dim < len ( w . shape ) ) , "`dim` must be `0 <= dim and dim < len(w.shape)`." assert 0 < itr , "`itr` must be greater than 0." assert 0 < eps , "`eps` must be greater than 0." if dim... | Spectral Normalization . |
34,878 | def reset_state ( self ) : self . h . data . zero ( ) self . c . data . zero ( ) | Resets states h and c to zero . |
34,879 | def lap ( self ) : now = time . time ( ) lap_time = now - self . lap_time total_time = now - self . start self . lap_time = now return lap_time , total_time | Calculate lap time . |
34,880 | def write ( self , fb ) : print ( '[{}.{}]' . format ( fb . module , fb . func . __name__ ) , file = self . file ) print ( 'class = {}' . format ( fb . func_ins . name ) , file = self . file ) print ( 'inspecs = {}' . format ( repr ( fb . inspecs ) ) , file = self . file ) print ( 'func_args = {}' . format ( repr ( fb ... | Write a single function benchmark . |
34,881 | def _setup ( self , delete = True ) : if delete : self . clear ( ) with nn . context_scope ( self . ctx ) : outputs = self . func ( * ( self . inputs_f + self . func_args ) , ** self . func_kwargs ) if not hasattr ( outputs , '__iter__' ) : self . outputs = [ outputs ] else : self . outputs = outputs self . func_ins = ... | Create a function instance and execute setup . |
34,882 | def benchmark_setup ( self ) : def f ( ) : self . _setup ( ) self . mod_ext . synchronize ( ** self . ext_kwargs ) f ( ) self . setup_stat = self . _calc_benchmark_stat ( f ) | Benchmark setup execution . |
34,883 | def benchmark_forward ( self ) : self . _setup ( ) def f ( ) : self . _forward ( ) self . mod_ext . synchronize ( ** self . ext_kwargs ) f ( ) self . forward_stat = self . _calc_benchmark_stat ( f ) | Benchmark forward execution . |
34,884 | def benchmark_backward ( self ) : try : self . _benchmark_backward ( ) except RuntimeError as e : print ( e ) self . mod_ext . synchronize ( ** self . ext_kwargs ) self . backward_stat = None | Benchmark backward execution . |
34,885 | def context ( type_config = 'float' , ** kw ) : backends = [ 'cpu:float' ] if type_config == 'half' : backends = [ 'cpu:half' , 'cpu:float' ] elif type_config == 'float' : pass else : raise ValueError ( "Unknown data type config is given %s" % type_config ) return nn . Context ( backends , array_classes ( ) [ 0 ] , '' ... | CPU Context . |
34,886 | def revise_buffer_size ( info , settings ) : size_mapping = { 'FLOAT32' : 4 , 'FIXED16' : 2 , 'FIXED8' : 1 } var_dict = settings [ 'variables' ] buffer_index = 0 info . _variable_sizes = [ ] info . _variable_buffer_index = collections . OrderedDict ( ) info . _variable_buffer_size = collections . OrderedDict ( ) info .... | This function is used to revise buffer size use byte as its unit instead of data item . This is only used for nnb not for csrc . When settings contains user customized data type not pure FLOAT32 it affects the memory consumption . |
34,887 | def category_names ( self ) : if hasattr ( self , '_category_names' ) : return self . _category_names with open ( os . path . join ( os . path . dirname ( __file__ ) , 'category_names.txt' ) , 'r' ) as fd : self . _category_names = fd . read ( ) . splitlines ( ) return self . _category_names | Returns category names of 1000 ImageNet classes . |
34,888 | def write ( self ) : writer = csv . writer ( self . file ) for f , b in zip ( self . gb . result [ "forward" ] , self . gb . result [ "backward" ] ) : f = f . _asdict ( ) b = b . _asdict ( ) if not self . check_same ( f , b ) : raise AssertionError ( ) args_info = ", " . join ( [ "{}: {}" . format ( k , v ) for k , v i... | Write result to the file . The output file is specified by file . |
34,889 | def plot_series ( filename , plot_kwargs = None ) : import matplotlib . pyplot as plt if plot_kwargs is None : plot_kwargs = { } data = np . genfromtxt ( filename , dtype = 'i8,f4' , names = [ 'k' , 'v' ] ) index = data [ 'k' ] values = data [ 'v' ] plt . plot ( index , values , ** plot_kwargs ) | Plot series data from MonitorSeries output text file . |
34,890 | def plot_time_elapsed ( filename , elapsed = False , unit = 's' , plot_kwargs = None ) : import matplotlib . pyplot as plt if plot_kwargs is None : plot_kwargs = { } data_column = 3 if elapsed else 1 data = np . genfromtxt ( filename , dtype = 'i8,f4' , usecols = ( 0 , data_column ) , names = [ 'k' , 'v' ] ) index = da... | Plot series data from MonitorTimeElapsed output text file . |
34,891 | def add ( self , index , value ) : self . buf . append ( value ) if ( index - self . flush_at ) < self . interval : return value = np . mean ( self . buf ) if self . verbose : logger . info ( "iter={} {{{}}}={}" . format ( index , self . name , value ) ) if self . fd is not None : print ( "{} {:g}" . format ( index , v... | Add a value to the series . |
34,892 | def add ( self , index ) : if ( index - self . flush_at ) < self . interval : return now = time . time ( ) elapsed = now - self . lap elapsed_total = now - self . start it = index - self . flush_at self . lap = now if self . verbose : logger . info ( "iter={} {{{}}}={}[sec/{}iter] {}[sec]" . format ( index , self . nam... | Calculate time elapsed from the point previously called this method or this object is created to this is called . |
34,893 | def add ( self , index , var ) : import nnabla as nn from nnabla . utils . image_utils import imsave if index != 0 and ( index + 1 ) % self . interval != 0 : return if isinstance ( var , nn . Variable ) : data = var . d . copy ( ) elif isinstance ( var , nn . NdArray ) : data = var . data . copy ( ) else : assert isins... | Add a minibatch of images to the monitor . |
34,894 | def data_iterator_simple ( load_func , num_examples , batch_size , shuffle = False , rng = None , with_memory_cache = True , with_file_cache = True , cache_dir = None , epoch_begin_callbacks = [ ] , epoch_end_callbacks = [ ] ) : return data_iterator ( SimpleDataSource ( load_func , num_examples , shuffle = shuffle , rn... | A generator that yield s minibatch data as a tuple as defined in load_func . It can unlimitedly yield minibatches at your request queried from the provided data . |
34,895 | def data_iterator_csv_dataset ( uri , batch_size , shuffle = False , rng = None , normalize = True , with_memory_cache = True , with_file_cache = True , cache_dir = None , epoch_begin_callbacks = [ ] , epoch_end_callbacks = [ ] ) : ds = CsvDataSource ( uri , shuffle = shuffle , rng = rng , normalize = normalize ) retur... | data_iterator_csv_dataset Get data directly from a dataset provided as a CSV file . |
34,896 | def data_iterator_cache ( uri , batch_size , shuffle = False , rng = None , normalize = True , with_memory_cache = True , epoch_begin_callbacks = [ ] , epoch_end_callbacks = [ ] ) : ds = CacheDataSource ( uri , shuffle = shuffle , rng = rng , normalize = normalize ) return data_iterator ( ds , batch_size = batch_size ,... | data_iterator_cache Get data from the cache directory . |
34,897 | def data_iterator_concat_datasets ( data_source_list , batch_size , shuffle = False , rng = None , with_memory_cache = True , with_file_cache = False , cache_dir = None , epoch_begin_callbacks = [ ] , epoch_end_callbacks = [ ] ) : ds = ConcatDataSource ( data_source_list , shuffle = shuffle , rng = rng ) return data_it... | data_iterator_concat_datasets Get data from multiple datasets . |
34,898 | def slice ( self , rng , num_of_slices = None , slice_pos = None , slice_start = None , slice_end = None , cache_dir = None ) : if num_of_slices is not None and slice_pos is not None and slice_start is None and slice_end is None : size = self . _size // num_of_slices amount = self . _size % num_of_slices slice_start = ... | Slices the data iterator so that newly generated data iterator has access to limited portion of the original data . |
34,899 | def auto_forward ( auto = True ) : global __auto_forward_state prev = __auto_forward_state __auto_forward_state = auto yield __auto_forward_state = prev | Context for dynamic graph execution mode . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.