idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
237,600
def createNetcon ( self , thresh = 10 ) : nc = h . NetCon ( self . soma ( 0.5 ) . _ref_v , None , sec = self . soma ) nc . threshold = thresh return nc
created netcon to record spikes
237,601
def createSections ( self ) : self . soma = h . Section ( name = 'soma' , cell = self ) self . dend = h . Section ( name = 'dend' , cell = self )
Create the sections of the cell .
237,602
def defineGeometry ( self ) : self . soma . L = 18.8 self . soma . diam = 18.8 self . soma . Ra = 123.0 self . dend . L = 200.0 self . dend . diam = 1.0 self . dend . Ra = 100.0
Set the 3D geometry of the cell .
237,603
def defineBiophysics ( self ) : self . soma . insert ( 'hh' ) self . soma . gnabar_hh = 0.12 self . soma . gkbar_hh = 0.036 self . soma . gl_hh = 0.003 self . soma . el_hh = - 70 self . dend . insert ( 'pas' ) self . dend . g_pas = 0.001 self . dend . e_pas = - 65 self . dend . nseg = 1000
Assign the membrane properties across the cell .
237,604
def shapeplot ( h , ax , sections = None , order = 'pre' , cvals = None , clim = None , cmap = cm . YlOrBr_r , legend = True , ** kwargs ) : if sections is None : if order == 'pre' : sections = allsec_preorder ( h ) else : sections = list ( h . allsec ( ) ) if cvals is not None and clim is None : clim = [ np . nanmin (...
Plots a 3D shapeplot
237,605
def shapeplot_animate ( v , lines , nframes = None , tscale = 'linear' , clim = [ - 80 , 50 ] , cmap = cm . YlOrBr_r ) : if nframes is None : nframes = v . shape [ 0 ] if tscale == 'linear' : def animate ( i ) : i_t = int ( ( i / nframes ) * v . shape [ 0 ] ) for i_seg in range ( v . shape [ 1 ] ) : lines [ i_seg ] . s...
Returns animate function which updates color of shapeplot
237,606
def mark_locations ( h , section , locs , markspec = 'or' , ** kwargs ) : xyz = get_section_path ( h , section ) ( r , theta , phi ) = sequential_spherical ( xyz ) rcum = np . append ( 0 , np . cumsum ( r ) ) if type ( locs ) is float or type ( locs ) is np . float64 : locs = np . array ( [ locs ] ) if type ( locs ) is...
Marks one or more locations on along a section . Could be used to mark the location of a recording or electrical stimulation .
237,607
def root_sections ( h ) : roots = [ ] for section in h . allsec ( ) : sref = h . SectionRef ( sec = section ) if sref . has_parent ( ) < 0.9 : roots . append ( section ) return roots
Returns a list of all sections that have no parent .
237,608
def leaf_sections ( h ) : leaves = [ ] for section in h . allsec ( ) : sref = h . SectionRef ( sec = section ) if sref . nchild ( ) < 0.9 : leaves . append ( section ) return leaves
Returns a list of all sections that have no children .
237,609
def root_indices ( sec_list ) : roots = [ ] for i , section in enumerate ( sec_list ) : sref = h . SectionRef ( sec = section ) if sref . has_parent ( ) < 0.9 : roots . append ( i ) return roots
Returns the index of all sections without a parent .
237,610
def branch_order ( h , section , path = [ ] ) : path . append ( section ) sref = h . SectionRef ( sec = section ) if sref . has_parent ( ) < 0.9 : return 0 else : nchild = len ( list ( h . SectionRef ( sec = sref . parent ) . child ) ) if nchild <= 1.1 : return branch_order ( h , sref . parent , path ) else : return 1 ...
Returns the branch order of a section
237,611
def createCells ( self ) : if 'cellsList' in self . tags : cells = self . createCellsList ( ) elif 'numCells' in self . tags : cells = self . createCellsFixedNum ( ) elif 'density' in self . tags : cells = self . createCellsDensity ( ) elif 'gridSpacing' in self . tags : cells = self . createCellsGrid ( ) else : self ....
Function to instantiate Cell objects based on the characteristics of this population
237,612
def createCellsList ( self ) : from . . import sim cells = [ ] self . tags [ 'numCells' ] = len ( self . tags [ 'cellsList' ] ) for i in self . _distributeCells ( len ( self . tags [ 'cellsList' ] ) ) [ sim . rank ] : gid = sim . net . lastGid + i self . cellGids . append ( gid ) cellTags = { k : v for ( k , v ) in sel...
Create population cells based on list of individual cells
237,613
def create ( netParams = None , simConfig = None , output = False ) : from . . import sim import __main__ as top if not netParams : netParams = top . netParams if not simConfig : simConfig = top . simConfig sim . initialize ( netParams , simConfig ) pops = sim . net . createPops ( ) cells = sim . net . createCells ( ) ...
Sequence of commands to create network
237,614
def intervalSimulate ( interval ) : from . . import sim sim . runSimWithIntervalFunc ( interval , sim . intervalSave ) sim . fileGather ( )
Sequence of commands to simulate network
237,615
def load ( filename , simConfig = None , output = False , instantiate = True , createNEURONObj = True ) : from . . import sim sim . initialize ( ) sim . cfg . createNEURONObj = createNEURONObj sim . loadAll ( filename , instantiate = instantiate , createNEURONObj = createNEURONObj ) if simConfig : sim . setSimCfg ( sim...
Sequence of commands load simulate and analyse network
237,616
def createExportNeuroML2 ( netParams = None , simConfig = None , reference = None , connections = True , stimulations = True , output = False , format = 'xml' ) : from . . import sim import __main__ as top if not netParams : netParams = top . netParams if not simConfig : simConfig = top . simConfig sim . initialize ( n...
Sequence of commands to create and export network to NeuroML2
237,617
def exception ( function ) : @ functools . wraps ( function ) def wrapper ( * args , ** kwargs ) : try : return function ( * args , ** kwargs ) except Exception as e : err = "There was an exception in %s():" % ( function . __name__ ) print ( ( "%s \n %s \n%s" % ( err , e , sys . exc_info ( ) ) ) ) return - 1 return wra...
A decorator that wraps the passed in function and prints exception should one occur
237,618
def getSpktSpkid ( cellGids = [ ] , timeRange = None , allCells = False ) : from . . import sim import pandas as pd try : from pandas import _lib as pandaslib except : from pandas import lib as pandaslib df = pd . DataFrame ( pandaslib . to_object_array ( [ sim . allSimData [ 'spkt' ] , sim . allSimData [ 'spkid' ] ] )...
return spike ids and times ; with allCells = True just need to identify slice of time so can omit cellGids
237,619
def calcTransferResistance ( self , gid , seg_coords ) : sigma = 0.3 r05 = ( seg_coords [ 'p0' ] + seg_coords [ 'p1' ] ) / 2 dl = seg_coords [ 'p1' ] - seg_coords [ 'p0' ] nseg = r05 . shape [ 1 ] tr = np . zeros ( ( self . nsites , nseg ) ) for j in range ( self . nsites ) : rel = np . expand_dims ( self . pos [ : , j...
Precompute mapping from segment to electrode locations
237,620
def importConnFromExcel ( fileName , sheetName ) : import openpyxl as xl colPreTags = 0 colPostTags = 1 colConnFunc = 2 colSyn = 3 colProb = 5 colWeight = 6 colAnnot = 8 outFileName = fileName [ : - 5 ] + '_' + sheetName + '.py' connText = wb = xl . load_workbook ( fileName ) sheet = wb . get_sheet_by_name ( sheetName ...
Import connectivity rules from Excel sheet
237,621
def safe_dump ( data , stream = None , ** kwds ) : return yaml . dump ( data , stream = stream , Dumper = ODYD , ** kwds )
implementation of safe dumper using Ordered Dict Yaml Dumper
237,622
def dump ( data , ** kwds ) : if _usedefaultyamlloader : return yaml . safe_dump ( data , ** kwds ) else : return odyldo . safe_dump ( data , ** kwds )
dump the data as YAML
237,623
def bibtex ( self ) : warnings . warn ( "bibtex should be queried with ads.ExportQuery(); You will " "hit API ratelimits very quickly otherwise." , UserWarning ) return ExportQuery ( bibcodes = self . bibcode , format = "bibtex" ) . execute ( )
Return a BiBTeX entry for the current article .
237,624
def get_pdf ( article , debug = False ) : print ( 'Retrieving {0}' . format ( article ) ) identifier = [ _ for _ in article . identifier if 'arXiv' in _ ] if identifier : url = 'http://arXiv.org/pdf/{0}.{1}' . format ( identifier [ 0 ] [ 9 : 13 ] , '' . join ( _ for _ in identifier [ 0 ] [ 14 : ] if _ . isdigit ( ) ) )...
Download an article PDF from arXiv .
237,625
def summarise_pdfs ( pdfs ) : print ( 'Summarising {0} articles ({1} had errors)' . format ( len ( pdfs ) , pdfs . count ( None ) ) ) pdfs = [ _ for _ in pdfs if _ is not None ] summary = PdfFileWriter ( ) for pdf in pdfs : summary . addPage ( PdfFileReader ( StringIO ( pdf ) ) . getPage ( 0 ) ) return summary
Collate the first page from each of the PDFs provided into a single PDF .
237,626
def execute ( self ) : self . response = MetricsResponse . load_http_response ( self . session . post ( self . HTTP_ENDPOINT , data = self . json_payload ) ) return self . response . metrics
Execute the http request to the metrics service
237,627
def get_info ( cls ) : return '\n' . join ( [ str ( cls . _instances [ key ] ) for key in cls . _instances ] )
Print all of the instantiated Singletons
237,628
def load_http_response ( cls , http_response ) : if not http_response . ok : raise APIResponseError ( http_response . text ) c = cls ( http_response ) c . response = http_response RateLimits . getRateLimits ( cls . __name__ ) . set ( c . response . headers ) return c
This method should return an instantiated class and set its response to the requests . Response object .
237,629
def token ( self ) : if self . _token is None : for v in map ( os . environ . get , TOKEN_ENVIRON_VARS ) : if v is not None : self . _token = v return self . _token for f in TOKEN_FILES : try : with open ( f ) as fp : self . _token = fp . read ( ) . strip ( ) return self . _token except IOError : pass if ads . config ....
set the instance attribute token following the following logic stopping whenever a token is found . Raises NoTokenFound is no token is found - environment variables TOKEN_ENVIRON_VARS - file containing plaintext as the contents in TOKEN_FILES - ads . config . token
237,630
def session ( self ) : if self . _session is None : self . _session = requests . session ( ) self . _session . headers . update ( { "Authorization" : "Bearer {}" . format ( self . token ) , "User-Agent" : "ads-api-client/{}" . format ( __version__ ) , "Content-Type" : "application/json" , } ) return self . _session
http session interface transparent proxy to requests . session
237,631
def from_csv ( input_csv_pattern , headers = None , schema_file = None ) : if headers is not None : names = headers elif schema_file is not None : with _util . open_local_or_gcs ( schema_file , mode = 'r' ) as f : schema = json . load ( f ) names = [ x [ 'name' ] for x in schema ] else : raise ValueError ( 'Either head...
Create a Metrics instance from csv file pattern .
237,632
def from_bigquery ( sql ) : if isinstance ( sql , bq . Query ) : sql = sql . _expanded_sql ( ) parts = sql . split ( '.' ) if len ( parts ) == 1 or len ( parts ) > 3 or any ( ' ' in x for x in parts ) : sql = '(' + sql + ')' else : sql = '`' + sql + '`' metrics = Metrics ( bigquery = sql ) return metrics
Create a Metrics instance from a bigquery query or table .
237,633
def _get_data_from_csv_files ( self ) : all_df = [ ] for file_name in self . _input_csv_files : with _util . open_local_or_gcs ( file_name , mode = 'r' ) as f : all_df . append ( pd . read_csv ( f , names = self . _headers ) ) df = pd . concat ( all_df , ignore_index = True ) return df
Get data from input csv files .
237,634
def _get_data_from_bigquery ( self , queries ) : all_df = [ ] for query in queries : all_df . append ( query . execute ( ) . result ( ) . to_dataframe ( ) ) df = pd . concat ( all_df , ignore_index = True ) return df
Get data from bigquery table or query .
237,635
def _expanded_sql ( self ) : if not self . _sql : self . _sql = UDF . _build_udf ( self . _name , self . _code , self . _return_type , self . _params , self . _language , self . _imports ) return self . _sql
Get the expanded BigQuery SQL string of this UDF
237,636
def _build_udf ( name , code , return_type , params , language , imports ) : params = ',' . join ( [ '%s %s' % named_param for named_param in params ] ) imports = ',' . join ( [ 'library="%s"' % i for i in imports ] ) if language . lower ( ) == 'sql' : udf = 'CREATE TEMPORARY FUNCTION {name} ({params})\n' + 'RETURNS {r...
Creates the UDF part of a BigQuery query using its pieces
237,637
def created_on ( self ) : s = self . _info . get ( 'timeCreated' , None ) return dateutil . parser . parse ( s ) if s else None
The created timestamp of the bucket as a datetime . datetime .
237,638
def metadata ( self ) : if self . _info is None : try : self . _info = self . _api . buckets_get ( self . _name ) except Exception as e : raise e return BucketMetadata ( self . _info ) if self . _info else None
Retrieves metadata about the bucket .
237,639
def object ( self , key ) : return _object . Object ( self . _name , key , context = self . _context )
Retrieves a Storage Object for the specified key in this bucket .
237,640
def objects ( self , prefix = None , delimiter = None ) : return _object . Objects ( self . _name , prefix , delimiter , context = self . _context )
Get an iterator for the objects within this bucket .
237,641
def delete ( self ) : if self . exists ( ) : try : self . _api . buckets_delete ( self . _name ) except Exception as e : raise e
Deletes the bucket .
237,642
def contains ( self , name ) : try : self . _api . buckets_get ( name ) except google . datalab . utils . RequestException as e : if e . status == 404 : return False raise e except Exception as e : raise e return True
Checks if the specified bucket exists .
237,643
def item ( self , key ) : return _item . Item ( self . _name , key , context = self . _context )
Retrieves an Item object for the specified key in this bucket .
237,644
def items ( self , prefix = None , delimiter = None ) : return _item . Items ( self . _name , prefix , delimiter , context = self . _context )
Get an iterator for the items within this bucket .
237,645
def create ( self , project_id = None ) : if not self . exists ( ) : if project_id is None : project_id = self . _api . project_id try : self . _info = self . _api . buckets_insert ( self . _name , project_id = project_id ) except Exception as e : raise e return self
Creates the bucket .
237,646
def create ( self , name ) : return Bucket ( name , context = self . _context ) . create ( self . _project_id )
Creates a new bucket .
237,647
def train ( train_dataset , eval_dataset , analysis_dir , output_dir , features , layer_sizes , max_steps = 5000 , num_epochs = None , train_batch_size = 100 , eval_batch_size = 16 , min_eval_frequency = 100 , learning_rate = 0.01 , epsilon = 0.0005 , job_name = None , cloud = None , ) : job = train_async ( train_datas...
Blocking version of train_async . See documentation for train_async .
237,648
def list ( self , pattern = '*' ) : if self . _descriptors is None : self . _descriptors = self . _client . list_resource_descriptors ( filter_string = self . _filter_string ) return [ resource for resource in self . _descriptors if fnmatch . fnmatch ( resource . type , pattern ) ]
Returns a list of resource descriptors that match the filters .
237,649
def _gcs_list_buckets ( project , pattern ) : data = [ { 'Bucket' : 'gs://' + bucket . name , 'Created' : bucket . metadata . created_on } for bucket in google . datalab . storage . Buckets ( _make_context ( project ) ) if fnmatch . fnmatch ( bucket . name , pattern ) ] return google . datalab . utils . commands . rend...
List all Google Cloud Storage buckets that match a pattern .
237,650
def _gcs_list_keys ( bucket , pattern ) : data = [ { 'Name' : obj . metadata . name , 'Type' : obj . metadata . content_type , 'Size' : obj . metadata . size , 'Updated' : obj . metadata . updated_on } for obj in _gcs_get_keys ( bucket , pattern ) ] return google . datalab . utils . commands . render_dictionary ( data ...
List all Google Cloud Storage keys in a specified bucket that match a pattern .
237,651
def prepare_image_transforms ( element , image_columns ) : import base64 import cStringIO from PIL import Image from tensorflow . python . lib . io import file_io as tf_file_io from apache_beam . metrics import Metrics img_error_count = Metrics . counter ( 'main' , 'ImgErrorCount' ) img_missing_count = Metrics . counte...
Replace an images url with its jpeg bytes .
237,652
def decode_csv ( csv_string , column_names ) : import csv r = next ( csv . reader ( [ csv_string ] ) ) if len ( r ) != len ( column_names ) : raise ValueError ( 'csv line %s does not have %d columns' % ( csv_string , len ( column_names ) ) ) return { k : v for k , v in zip ( column_names , r ) }
Parse a csv line into a dict .
237,653
def encode_csv ( data_dict , column_names ) : import csv import six values = [ str ( data_dict [ x ] ) for x in column_names ] str_buff = six . StringIO ( ) writer = csv . writer ( str_buff , lineterminator = '' ) writer . writerow ( values ) return str_buff . getvalue ( )
Builds a csv string .
237,654
def serialize_example ( transformed_json_data , info_dict ) : import six import tensorflow as tf def _make_int64_list ( x ) : return tf . train . Feature ( int64_list = tf . train . Int64List ( value = x ) ) def _make_bytes_list ( x ) : return tf . train . Feature ( bytes_list = tf . train . BytesList ( value = x ) ) d...
Makes a serialized tf . example .
237,655
def preprocess ( pipeline , args ) : from tensorflow . python . lib . io import file_io from trainer import feature_transforms schema = json . loads ( file_io . read_file_to_string ( os . path . join ( args . analysis , feature_transforms . SCHEMA_FILE ) ) . decode ( ) ) features = json . loads ( file_io . read_file_to...
Transfrom csv data into transfromed tf . example files .
237,656
def main ( argv = None ) : args = parse_arguments ( sys . argv if argv is None else argv ) temp_dir = os . path . join ( args . output , 'tmp' ) if args . cloud : pipeline_name = 'DataflowRunner' else : pipeline_name = 'DirectRunner' os . environ [ 'TF_CPP_MIN_LOG_LEVEL' ] = '3' options = { 'job_name' : args . job_name...
Run Preprocessing as a Dataflow .
237,657
def start_bundle ( self , element = None ) : import tensorflow as tf from trainer import feature_transforms g = tf . Graph ( ) session = tf . Session ( graph = g ) with g . as_default ( ) : transformed_features , _ , placeholders = ( feature_transforms . build_csv_serving_tensors_for_transform_step ( analysis_path = se...
Build the transfromation graph once .
237,658
def process ( self , element ) : import apache_beam as beam import six import tensorflow as tf tf . logging . set_verbosity ( tf . logging . ERROR ) try : clean_element = [ ] for line in element : clean_element . append ( line . rstrip ( ) ) batch_result = self . _session . run ( fetches = self . _transformed_features ...
Run the transformation graph on batched input data
237,659
def parse_row ( schema , data ) : def parse_value ( data_type , value ) : if value is not None : if value == 'null' : value = None elif data_type == 'INTEGER' : value = int ( value ) elif data_type == 'FLOAT' : value = float ( value ) elif data_type == 'TIMESTAMP' : value = datetime . datetime . utcfromtimestamp ( floa...
Parses a row from query results into an equivalent object .
237,660
def _tf_predict ( model_dir , input_csvlines ) : with tf . Graph ( ) . as_default ( ) , tf . Session ( ) as sess : input_alias_map , output_alias_map = _tf_load_model ( sess , model_dir ) csv_tensor_name = list ( input_alias_map . values ( ) ) [ 0 ] results = sess . run ( fetches = output_alias_map , feed_dict = { csv_...
Prediction with a tf savedmodel .
237,661
def _download_images ( data , img_cols ) : images = collections . defaultdict ( list ) for d in data : for img_col in img_cols : if d . get ( img_col , None ) : if isinstance ( d [ img_col ] , Image . Image ) : images [ img_col ] . append ( d [ img_col ] ) else : with file_io . FileIO ( d [ img_col ] , 'rb' ) as fi : i...
Download images given image columns .
237,662
def _get_predicton_csv_lines ( data , headers , images ) : if images : data = copy . deepcopy ( data ) for img_col in images : for d , im in zip ( data , images [ img_col ] ) : if im == '' : continue im = im . copy ( ) im . thumbnail ( ( 299 , 299 ) , Image . ANTIALIAS ) buf = BytesIO ( ) im . save ( buf , "JPEG" ) con...
Create CSV lines from list - of - dict data .
237,663
def _get_display_data_with_images ( data , images ) : if not images : return data display_data = copy . deepcopy ( data ) for img_col in images : for d , im in zip ( display_data , images [ img_col ] ) : if im == '' : d [ img_col + '_image' ] = '' else : im = im . copy ( ) im . thumbnail ( ( 128 , 128 ) , Image . ANTIA...
Create display data by converting image urls to base64 strings .
237,664
def get_model_schema_and_features ( model_dir ) : schema_file = os . path . join ( model_dir , 'assets.extra' , 'schema.json' ) schema = json . loads ( file_io . read_file_to_string ( schema_file ) ) features_file = os . path . join ( model_dir , 'assets.extra' , 'features.json' ) features_config = json . loads ( file_...
Get a local model s schema and features config .
237,665
def get_prediction_results ( model_dir_or_id , data , headers , img_cols = None , cloud = False , with_source = True , show_image = True ) : if img_cols is None : img_cols = [ ] if isinstance ( data , pd . DataFrame ) : data = list ( data . T . to_dict ( ) . values ( ) ) elif isinstance ( data [ 0 ] , six . string_type...
Predict with a specified model .
237,666
def get_probs_for_labels ( labels , prediction_results ) : probs = [ ] if 'probability' in prediction_results : for i , r in prediction_results . iterrows ( ) : probs_one = [ 0.0 ] * len ( labels ) for k , v in six . iteritems ( r ) : if v in labels and k . startswith ( 'predicted' ) : if k == 'predict' : prob_name = '...
Given ML Workbench prediction results get probs of each label for each instance .
237,667
def local_batch_predict ( model_dir , csv_file_pattern , output_dir , output_format , batch_size = 100 ) : file_io . recursive_create_dir ( output_dir ) csv_files = file_io . get_matching_files ( csv_file_pattern ) if len ( csv_files ) == 0 : raise ValueError ( 'No files found given ' + csv_file_pattern ) with tf . Gra...
Batch Predict with a specified model .
237,668
def submit_training ( job_request , job_id = None ) : new_job_request = dict ( job_request ) if 'args' in job_request and isinstance ( job_request [ 'args' ] , dict ) : job_args = job_request [ 'args' ] args = [ ] for k , v in six . iteritems ( job_args ) : if isinstance ( v , list ) : for item in v : args . append ( '...
Submit a training job .
237,669
def submit_batch_prediction ( job_request , job_id = None ) : if job_id is None : job_id = 'prediction_' + datetime . datetime . now ( ) . strftime ( '%y%m%d_%H%M%S' ) job = { 'job_id' : job_id , 'prediction_input' : job_request , } context = datalab . Context . default ( ) cloudml = discovery . build ( 'ml' , 'v1' , c...
Submit a batch prediction job .
237,670
def _reduced_kernel_size_for_small_input ( input_tensor , kernel_size ) : shape = input_tensor . get_shape ( ) . as_list ( ) if shape [ 1 ] is None or shape [ 2 ] is None : kernel_size_out = kernel_size else : kernel_size_out = [ min ( shape [ 1 ] , kernel_size [ 0 ] ) , min ( shape [ 2 ] , kernel_size [ 1 ] ) ] return...
Define kernel size which is automatically reduced for small input .
237,671
def inception_v3_arg_scope ( weight_decay = 0.00004 , stddev = 0.1 , batch_norm_var_collection = 'moving_vars' ) : batch_norm_params = { 'decay' : 0.9997 , 'epsilon' : 0.001 , 'updates_collections' : tf . GraphKeys . UPDATE_OPS , 'variables_collections' : { 'beta' : None , 'gamma' : None , 'moving_mean' : [ batch_norm_...
Defines the default InceptionV3 arg scope .
237,672
def preprocess ( train_dataset , output_dir , eval_dataset , checkpoint ) : import apache_beam as beam from google . datalab . utils import LambdaJob from . import _preprocess if checkpoint is None : checkpoint = _util . _DEFAULT_CHECKPOINT_GSURL job_id = ( 'preprocess-image-classification-' + datetime . datetime . now...
Preprocess data locally .
237,673
def train ( input_dir , batch_size , max_steps , output_dir , checkpoint ) : from google . datalab . utils import LambdaJob if checkpoint is None : checkpoint = _util . _DEFAULT_CHECKPOINT_GSURL labels = _util . get_labels ( input_dir ) model = _model . Model ( labels , 0.5 , checkpoint ) task_data = { 'type' : 'master...
Train model locally .
237,674
def predict ( model_dir , image_files , resize , show_image ) : from . import _predictor images = _util . load_images ( image_files , resize = resize ) labels_and_scores = _predictor . predict ( model_dir , images ) results = zip ( image_files , images , labels_and_scores ) ret = _util . process_prediction_results ( re...
Predict using an model in a local or GCS directory .
237,675
def batch_predict ( dataset , model_dir , output_csv , output_bq_table ) : import apache_beam as beam from google . datalab . utils import LambdaJob from . import _predictor if output_csv is None and output_bq_table is None : raise ValueError ( 'output_csv and output_bq_table cannot both be None.' ) job_id = ( 'batch-p...
Batch predict running locally .
237,676
def result ( self ) : self . wait ( ) if self . _fatal_error : raise self . _fatal_error return self . _result
Get the result for a job . This will block if the job is incomplete .
237,677
def _refresh_state ( self ) : if self . _is_complete : return if not self . _future : raise Exception ( 'Please implement this in the derived class' ) if self . _future . done ( ) : self . _is_complete = True self . _end_time = datetime . datetime . utcnow ( ) try : self . _result = self . _future . result ( ) except E...
Get the state of a job . Must be overridden by derived Job classes for Jobs that don t use a Future .
237,678
def state ( self ) : state = 'in progress' if self . is_complete : if self . failed : state = 'failed with error: %s' % str ( self . _fatal_error ) elif self . _errors : state = 'completed with some non-fatal errors' else : state = 'completed' return state
Describe the state of a Job .
237,679
def wait_any ( jobs , timeout = None ) : return Job . _wait ( jobs , timeout , concurrent . futures . FIRST_COMPLETED )
Return when at least one of the specified jobs has completed or timeout expires .
237,680
def wait_all ( jobs , timeout = None ) : return Job . _wait ( jobs , timeout , concurrent . futures . ALL_COMPLETED )
Return when at all of the specified jobs have completed or timeout expires .
237,681
def evaluate ( self , num_eval_batches = None ) : num_eval_batches = num_eval_batches or self . num_eval_batches with tf . Graph ( ) . as_default ( ) as graph : self . tensors = self . model . build_eval_graph ( self . eval_data_paths , self . batch_size ) self . summary = tf . summary . merge_all ( ) self . saver = tf...
Run one round of evaluation return loss and accuracy .
237,682
def log ( self , session ) : logging . info ( 'Train [%s/%d], step %d (%.3f sec) %.1f ' 'global steps/s, %.1f local steps/s' , self . task . type , self . task . index , self . global_step , ( self . now - self . start_time ) , ( self . global_step - self . last_global_step ) / ( self . now - self . last_global_time ) ...
Logs training progress .
237,683
def eval ( self , session ) : eval_start = time . time ( ) self . saver . save ( session , self . sv . save_path , self . tensors . global_step ) logging . info ( 'Eval, step %d:\n- on train set %s\n-- on eval set %s' , self . global_step , self . model . format_metric_values ( self . train_evaluator . evaluate ( ) ) ,...
Runs evaluation loop .
237,684
def plot ( self , data ) : import IPython if ( ( sys . version_info . major > 2 and isinstance ( data , str ) ) or ( sys . version_info . major <= 2 and isinstance ( data , basestring ) ) ) : data = bq . Query ( data ) if isinstance ( data , bq . Query ) : df = data . execute ( ) . result ( ) . to_dataframe ( ) data = ...
Plots a featire slice view on given data .
237,685
def run_analysis ( args ) : import google . datalab . bigquery as bq if args . bigquery_table : table = bq . Table ( args . bigquery_table ) schema_list = table . schema . _bq_schema else : schema_list = json . loads ( file_io . read_file_to_string ( args . schema_file ) . decode ( ) ) table = bq . ExternalDataSource (...
Builds an analysis file for training .
237,686
def from_csv ( input_csv , headers = None , schema_file = None ) : if headers is not None : names = headers elif schema_file is not None : with _util . open_local_or_gcs ( schema_file , mode = 'r' ) as f : schema = json . load ( f ) names = [ x [ 'name' ] for x in schema ] else : raise ValueError ( 'Either headers or s...
Create a ConfusionMatrix from a csv file .
237,687
def from_bigquery ( sql ) : if isinstance ( sql , bq . Query ) : sql = sql . _expanded_sql ( ) parts = sql . split ( '.' ) if len ( parts ) == 1 or len ( parts ) > 3 or any ( ' ' in x for x in parts ) : sql = '(' + sql + ')' else : sql = '`' + sql + '`' query = bq . Query ( 'SELECT target, predicted, count(*) as count ...
Create a ConfusionMatrix from a BigQuery table or query .
237,688
def to_dataframe ( self ) : data = [ ] for target_index , target_row in enumerate ( self . _cm ) : for predicted_index , count in enumerate ( target_row ) : data . append ( ( self . _labels [ target_index ] , self . _labels [ predicted_index ] , count ) ) return pd . DataFrame ( data , columns = [ 'target' , 'predicted...
Convert the confusion matrix to a dataframe .
237,689
def plot ( self , figsize = None , rotation = 45 ) : fig , ax = plt . subplots ( figsize = figsize ) plt . imshow ( self . _cm , interpolation = 'nearest' , cmap = plt . cm . Blues , aspect = 'auto' ) plt . title ( 'Confusion matrix' ) plt . colorbar ( ) tick_marks = np . arange ( len ( self . _labels ) ) plt . xticks ...
Plot the confusion matrix .
237,690
def get_environment_details ( zone , environment ) : default_context = google . datalab . Context . default ( ) url = ( Api . _ENDPOINT + ( Api . _ENVIRONMENTS_PATH_FORMAT % ( default_context . project_id , zone , environment ) ) ) return google . datalab . utils . Http . request ( url , credentials = default_context ....
Issues a request to Composer to get the environment details .
237,691
def buckets_delete ( self , bucket ) : url = Api . _ENDPOINT + ( Api . _BUCKET_PATH % bucket ) google . datalab . utils . Http . request ( url , method = 'DELETE' , credentials = self . _credentials , raw_response = True )
Issues a request to delete a bucket .
237,692
def buckets_get ( self , bucket , projection = 'noAcl' ) : args = { 'projection' : projection } url = Api . _ENDPOINT + ( Api . _BUCKET_PATH % bucket ) return google . datalab . utils . Http . request ( url , credentials = self . _credentials , args = args )
Issues a request to retrieve information about a bucket .
237,693
def buckets_list ( self , projection = 'noAcl' , max_results = 0 , page_token = None , project_id = None ) : if max_results == 0 : max_results = Api . _MAX_RESULTS args = { 'project' : project_id if project_id else self . _project_id , 'maxResults' : max_results } if projection is not None : args [ 'projection' ] = pro...
Issues a request to retrieve the list of buckets .
237,694
def object_download ( self , bucket , key , start_offset = 0 , byte_count = None ) : args = { 'alt' : 'media' } headers = { } if start_offset > 0 or byte_count is not None : header = 'bytes=%d-' % start_offset if byte_count is not None : header += '%d' % byte_count headers [ 'Range' ] = header url = Api . _DOWNLOAD_END...
Reads the contents of an object as text .
237,695
def object_upload ( self , bucket , key , content , content_type ) : args = { 'uploadType' : 'media' , 'name' : key } headers = { 'Content-Type' : content_type } url = Api . _UPLOAD_ENDPOINT + ( Api . _OBJECT_PATH % ( bucket , '' ) ) return google . datalab . utils . Http . request ( url , args = args , data = content ...
Writes text content to the object .
237,696
def preprocess_async ( train_dataset , output_dir , eval_dataset = None , checkpoint = None , cloud = None ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) if cloud is None : return _local . Local . preprocess ( train_dataset , output_dir , eval_dataset , checkpoint ) if not isinstance ( cl...
Preprocess data . Produce output that can be used by training efficiently .
237,697
def train_async ( input_dir , batch_size , max_steps , output_dir , checkpoint = None , cloud = None ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) if cloud is None : return _local . Local . train ( input_dir , batch_size , max_steps , output_dir , checkpoint ) return _cloud . Cloud . tra...
Train model . The output can be used for batch prediction or online deployment .
237,698
def batch_predict_async ( dataset , model_dir , output_csv = None , output_bq_table = None , cloud = None ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) if cloud is None : return _local . Local . batch_predict ( dataset , model_dir , output_csv , output_bq_table ) if not isinstance ( clou...
Batch prediction with an offline model .
237,699
def _refresh_state ( self ) : if self . _is_complete : return try : response = self . _api . jobs_get ( self . _job_id ) except Exception as e : raise e if 'status' in response : status = response [ 'status' ] if 'state' in status and status [ 'state' ] == 'DONE' : self . _end_time = datetime . datetime . utcnow ( ) se...
Get the state of a job . If the job is complete this does nothing ; otherwise it gets a refreshed copy of the job resource .