idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
48,800 | 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 . |
48,801 | 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 . |
48,802 | 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 . |
48,803 | 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 . |
48,804 | 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 . |
48,805 | 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 . |
48,806 | 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 . |
48,807 | 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 . |
48,808 | 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 . |
48,809 | 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 . |
48,810 | 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 . |
48,811 | 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 . |
48,812 | 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 . |
48,813 | 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 . |
48,814 | 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 . |
48,815 | 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 . |
48,816 | 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 . |
48,817 | 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 . |
48,818 | 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 . |
48,819 | 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 . |
48,820 | 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 . |
48,821 | 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 . |
48,822 | 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 . |
48,823 | 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 . |
48,824 | 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 . |
48,825 | 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 . |
48,826 | 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 . |
48,827 | 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 . |
48,828 | 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 . |
48,829 | 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 . |
48,830 | 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 . |
48,831 | 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 . |
48,832 | 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 . |
48,833 | 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 . |
48,834 | 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 . |
48,835 | def monitoring ( line , cell = None ) : parser = datalab . utils . commands . CommandParser ( prog = 'monitoring' , description = ( 'Execute various Monitoring-related operations. Use "%monitoring ' '<command> -h" for help on a specific command.' ) ) list_parser = parser . subcommand ( 'list' , 'List the metrics or res... | Implements the monitoring cell magic for ipython notebooks . |
48,836 | def _render_dataframe ( dataframe ) : data = dataframe . to_dict ( orient = 'records' ) fields = dataframe . columns . tolist ( ) return IPython . core . display . HTML ( datalab . utils . commands . HtmlBuilder . render_table ( data , fields ) ) | Helper to render a dataframe as an HTML table . |
48,837 | def _get_job_status ( line ) : try : args = line . strip ( ) . split ( ) job_name = args [ 0 ] job = None if job_name in _local_jobs : job = _local_jobs [ job_name ] else : raise Exception ( 'invalid job %s' % job_name ) if job is not None : error = '' if job . fatal_error is None else str ( job . fatal_error ) data = ... | magic used as an endpoint for client to get job status . |
48,838 | def updated_on ( self ) : s = self . _info . get ( 'updated' , None ) return dateutil . parser . parse ( s ) if s else None | The updated timestamp of the object as a datetime . datetime . |
48,839 | def delete ( self , wait_for_deletion = True ) : if self . exists ( ) : try : self . _api . objects_delete ( self . _bucket , self . _key ) except Exception as e : raise e if wait_for_deletion : for _ in range ( _MAX_POLL_ATTEMPTS ) : objects = Objects ( self . _bucket , prefix = self . key , delimiter = '/' , context ... | Deletes this object from its bucket . |
48,840 | def metadata ( self ) : if self . _info is None : try : self . _info = self . _api . objects_get ( self . _bucket , self . _key ) except Exception as e : raise e return ObjectMetadata ( self . _info ) if self . _info else None | Retrieves metadata about the object . |
48,841 | def read_stream ( self , start_offset = 0 , byte_count = None ) : try : return self . _api . object_download ( self . _bucket , self . _key , start_offset = start_offset , byte_count = byte_count ) except Exception as e : raise e | Reads the content of this object as text . |
48,842 | def read_lines ( self , max_lines = None ) : if max_lines is None : return self . read_stream ( ) . split ( '\n' ) max_to_read = self . metadata . size bytes_to_read = min ( 100 * max_lines , self . metadata . size ) while True : content = self . read_stream ( byte_count = bytes_to_read ) lines = content . split ( '\n'... | Reads the content of this object as text and return a list of lines up to some max . |
48,843 | def sample_to ( self , count , skip_header_rows , strategy , target ) : if sys . version_info . major > 2 : xrange = range if strategy == 'BIGQUERY' : import datalab . bigquery as bq if not self . path . startswith ( 'gs://' ) : raise Exception ( 'Cannot use BIGQUERY if data is not in GCS' ) federated_table = self . _c... | Sample rows from GCS or local file and save results to target file . |
48,844 | def _ParseExample ( self , example_features , example_feature_lists , entries , index ) : features_seen = set ( ) for feature_list , is_feature in zip ( [ example_features , example_feature_lists ] , [ True , False ] ) : sequence_length = None for feature_name in feature_list : if feature_name not in entries : entries ... | Parses data from an example populating a dictionary of feature values . |
48,845 | def _GetEntries ( self , paths , max_entries , iterator_from_file , is_sequence = False ) : entries = { } index = 0 for filepath in paths : reader = iterator_from_file ( filepath ) for record in reader : if is_sequence : sequence_example = tf . train . SequenceExample . FromString ( record ) self . _ParseExample ( sequ... | Extracts examples into a dictionary of feature values . |
48,846 | def _GetTfRecordEntries ( self , path , max_entries , is_sequence , iterator_options ) : return self . _GetEntries ( [ path ] , max_entries , partial ( tf . python_io . tf_record_iterator , options = iterator_options ) , is_sequence ) | Extracts TFRecord examples into a dictionary of feature values . |
48,847 | def buckets_insert ( self , bucket , project_id = None ) : args = { 'project' : project_id if project_id else self . _project_id } data = { 'name' : bucket } url = Api . _ENDPOINT + ( Api . _BUCKET_PATH % '' ) return datalab . utils . Http . request ( url , args = args , data = data , credentials = self . _credentials ... | Issues a request to create a new bucket . |
48,848 | def objects_delete ( self , bucket , key ) : url = Api . _ENDPOINT + ( Api . _OBJECT_PATH % ( bucket , Api . _escape_key ( key ) ) ) datalab . utils . Http . request ( url , method = 'DELETE' , credentials = self . _credentials , raw_response = True ) | Deletes the specified object . |
48,849 | def list ( self , pattern = '*' ) : if self . _descriptors is None : self . _descriptors = self . _client . list_metric_descriptors ( filter_string = self . _filter_string , type_prefix = self . _type_prefix ) return [ metric for metric in self . _descriptors if fnmatch . fnmatch ( metric . type , pattern ) ] | Returns a list of metric descriptors that match the filters . |
48,850 | def _from_dataframe ( dataframe , default_type = 'STRING' ) : type_mapping = { 'i' : 'INTEGER' , 'b' : 'BOOLEAN' , 'f' : 'FLOAT' , 'O' : 'STRING' , 'S' : 'STRING' , 'U' : 'STRING' , 'M' : 'TIMESTAMP' } fields = [ ] for column_name , dtype in dataframe . dtypes . iteritems ( ) : fields . append ( { 'name' : column_name ... | Infer a BigQuery table schema from a Pandas dataframe . Note that if you don t explicitly set the types of the columns in the dataframe they may be of a type that forces coercion to STRING so even though the fields in the dataframe themselves may be numeric the type in the derived schema may not be . Hence it is pruden... |
48,851 | def _from_dict_record ( data ) : return [ Schema . _get_field_entry ( name , value ) for name , value in list ( data . items ( ) ) ] | Infer a BigQuery table schema from a dictionary . If the dictionary has entries that are in turn OrderedDicts these will be turned into RECORD types . Ideally this will be an OrderedDict but it is not required . |
48,852 | def _from_list_record ( data ) : return [ Schema . _get_field_entry ( 'Column%d' % ( i + 1 ) , value ) for i , value in enumerate ( data ) ] | Infer a BigQuery table schema from a list of values . |
48,853 | def _from_record ( data ) : if isinstance ( data , dict ) : return Schema . _from_dict_record ( data ) elif isinstance ( data , list ) : return Schema . _from_list_record ( data ) else : raise Exception ( 'Cannot create a schema from record %s' % str ( data ) ) | Infer a BigQuery table schema from a list of fields or a dictionary . The typeof the elements is used . For a list the field names are simply Column1 Column2 etc . |
48,854 | def create_args ( line , namespace ) : args = [ ] for arg in shlex . split ( line ) : if not arg : continue if arg [ 0 ] == '$' : var_name = arg [ 1 : ] if var_name in namespace : args . append ( ( namespace [ var_name ] ) ) else : raise Exception ( 'Undefined variable referenced in command line: %s' % arg ) else : arg... | Expand any meta - variable references in the argument list . |
48,855 | def parse ( self , line , namespace = None ) : try : if namespace is None : ipy = IPython . get_ipython ( ) namespace = ipy . user_ns args = CommandParser . create_args ( line , namespace ) return self . parse_args ( args ) except Exception as e : print ( str ( e ) ) return None | Parses a line into a dictionary of arguments expanding meta - variables from a namespace . |
48,856 | def subcommand ( self , name , help ) : if self . _subcommands is None : self . _subcommands = self . add_subparsers ( help = 'commands' ) return self . _subcommands . add_parser ( name , description = help , help = help ) | Creates a parser for a sub - command . |
48,857 | def render_text ( text , preformatted = False ) : return IPython . core . display . HTML ( _html . HtmlBuilder . render_text ( text , preformatted ) ) | Return text formatted as a HTML |
48,858 | def _get_cols ( fields , schema ) : typemap = { 'STRING' : 'string' , 'INT64' : 'number' , 'INTEGER' : 'number' , 'FLOAT' : 'number' , 'FLOAT64' : 'number' , 'BOOL' : 'boolean' , 'BOOLEAN' : 'boolean' , 'DATE' : 'date' , 'TIME' : 'timeofday' , 'DATETIME' : 'datetime' , 'TIMESTAMP' : 'datetime' } cols = [ ] for col in f... | Get column metadata for Google Charts based on field list and schema . |
48,859 | def _get_data_from_empty_list ( source , fields = '*' , first_row = 0 , count = - 1 , schema = None ) : fields = get_field_list ( fields , schema ) return { 'cols' : _get_cols ( fields , schema ) , 'rows' : [ ] } , 0 | Helper function for _get_data that handles empty lists . |
48,860 | def _get_data_from_table ( source , fields = '*' , first_row = 0 , count = - 1 , schema = None ) : if not source . exists ( ) : return _get_data_from_empty_list ( source , fields , first_row , count ) if schema is None : schema = source . schema fields = get_field_list ( fields , schema ) gen = source . range ( first_r... | Helper function for _get_data that handles BQ Tables . |
48,861 | def replace_vars ( config , env ) : if isinstance ( config , dict ) : for k , v in list ( config . items ( ) ) : if isinstance ( v , dict ) or isinstance ( v , list ) or isinstance ( v , tuple ) : replace_vars ( v , env ) elif isinstance ( v , basestring ) : config [ k ] = expand_var ( v , env ) elif isinstance ( confi... | Replace variable references in config using the supplied env dictionary . |
48,862 | def parse_config ( config , env , as_dict = True ) : if config is None : return None stripped = config . strip ( ) if len ( stripped ) == 0 : config = { } elif stripped [ 0 ] == '{' : config = json . loads ( config ) else : config = yaml . load ( config ) if as_dict : config = dict ( config ) replace_vars ( config , en... | Parse a config from a magic cell body . This could be JSON or YAML . We turn it into a Python dictionary then recursively replace any variable references using the supplied env dictionary . |
48,863 | def validate_config ( config , required_keys , optional_keys = None ) : if optional_keys is None : optional_keys = [ ] if not isinstance ( config , dict ) : raise Exception ( 'config is not dict type' ) invalid_keys = set ( config ) - set ( required_keys + optional_keys ) if len ( invalid_keys ) > 0 : raise Exception (... | Validate a config dictionary to make sure it includes all required keys and does not include any unexpected keys . |
48,864 | def validate_config_must_have ( config , required_keys ) : missing_keys = set ( required_keys ) - set ( config ) if len ( missing_keys ) > 0 : raise Exception ( 'Invalid config with missing keys "%s"' % ', ' . join ( missing_keys ) ) | Validate a config dictionary to make sure it has all of the specified keys |
48,865 | def validate_config_has_one_of ( config , one_of_keys ) : intersection = set ( config ) . intersection ( one_of_keys ) if len ( intersection ) > 1 : raise Exception ( 'Only one of the values in "%s" is needed' % ', ' . join ( intersection ) ) if len ( intersection ) == 0 : raise Exception ( 'One of the values in "%s" i... | Validate a config dictionary to make sure it has one and only one key in one_of_keys . |
48,866 | def validate_config_value ( value , possible_values ) : if value not in possible_values : raise Exception ( 'Invalid config value "%s". Possible values are ' '%s' % ( value , ', ' . join ( e for e in possible_values ) ) ) | Validate a config value to make sure it is one of the possible values . |
48,867 | def validate_gcs_path ( path , require_object ) : bucket , key = datalab . storage . _bucket . parse_name ( path ) if bucket is None : raise Exception ( 'Invalid GCS path "%s"' % path ) if require_object and key is None : raise Exception ( 'It appears the GCS path "%s" is a bucket path but not an object path' % path ) | Check whether a given path is a valid GCS path . |
48,868 | def profile_df ( df ) : return IPython . core . display . HTML ( pandas_profiling . ProfileReport ( df ) . html . replace ( 'bootstrap' , 'nonexistent' ) ) | Generate a profile of data in a dataframe . |
48,869 | def _package_to_staging ( staging_package_url ) : import google . datalab . ml as ml package_root = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , '../../' ) ) setup_path = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , 'master_setup.py' ) ) tar_gz_path = os . p... | Repackage this package from local installed location and copy it to GCS . |
48,870 | def analyze ( output_dir , dataset , cloud = False , project_id = None ) : job = analyze_async ( output_dir = output_dir , dataset = dataset , cloud = cloud , project_id = project_id ) job . wait ( ) print ( 'Analyze: ' + str ( job . state ) ) | Blocking version of analyze_async . See documentation of analyze_async . |
48,871 | def analyze_async ( output_dir , dataset , cloud = False , project_id = None ) : import google . datalab . utils as du with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) fn = lambda : _analyze ( output_dir , dataset , cloud , project_id ) return du . LambdaJob ( fn , job_id = None ) | Analyze data locally or in the cloud with BigQuery . |
48,872 | def cloud_train ( train_dataset , eval_dataset , analysis_dir , output_dir , features , model_type , max_steps , num_epochs , train_batch_size , eval_batch_size , min_eval_frequency , top_n , layer_sizes , learning_rate , epsilon , job_name , job_name_prefix , config ) : import google . datalab . ml as ml if len ( trai... | Train model using CloudML . |
48,873 | def predict ( data , training_dir = None , model_name = None , model_version = None , cloud = False ) : if cloud : if not model_version or not model_name : raise ValueError ( 'model_version or model_name is not set' ) if training_dir : raise ValueError ( 'training_dir not needed when cloud is True' ) with warnings . ca... | Runs prediction locally or on the cloud . |
48,874 | def local_predict ( training_dir , data ) : from . prediction import predict as predict_module tmp_dir = tempfile . mkdtemp ( ) _ , input_file_path = tempfile . mkstemp ( dir = tmp_dir , suffix = '.csv' , prefix = 'input' ) try : if isinstance ( data , pd . DataFrame ) : data . to_csv ( input_file_path , header = False... | Runs local prediction on the prediction graph . |
48,875 | def cloud_predict ( model_name , model_version , data ) : import google . datalab . ml as ml if isinstance ( data , pd . DataFrame ) : string_buffer = io . StringIO ( ) data . to_csv ( string_buffer , header = None , index = False ) input_data = string_buffer . getvalue ( ) . split ( '\n' ) input_data = [ line for line... | Use Online prediction . |
48,876 | def batch_predict ( training_dir , prediction_input_file , output_dir , mode , batch_size = 16 , shard_files = True , output_format = 'csv' , cloud = False ) : job = batch_predict_async ( training_dir = training_dir , prediction_input_file = prediction_input_file , output_dir = output_dir , mode = mode , batch_size = b... | Blocking versoin of batch_predict . |
48,877 | def batch_predict_async ( training_dir , prediction_input_file , output_dir , mode , batch_size = 16 , shard_files = True , output_format = 'csv' , cloud = False ) : import google . datalab . utils as du with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) if cloud : runner_results = cloud_batch_pr... | Local and cloud batch prediction . |
48,878 | def make_prediction_pipeline ( pipeline , args ) : predicted_values , errors = ( pipeline | 'Read CSV Files' >> beam . io . ReadFromText ( str ( args . predict_data ) , strip_trailing_newlines = True ) | 'Batch Input' >> beam . ParDo ( EmitAsBatchDoFn ( args . batch_size ) ) | 'Run TF Graph on Batches' >> beam . ParDo ... | Builds the prediction pipeline . |
48,879 | def process ( self , element ) : import collections import apache_beam as beam num_in_batch = 0 try : assert self . _session is not None feed_dict = collections . defaultdict ( list ) for line in element : if line . endswith ( '\n' ) : line = line [ : - 1 ] feed_dict [ self . _input_alias_map . values ( ) [ 0 ] ] . app... | Run batch prediciton on a TF graph . |
48,880 | def encode ( self , tf_graph_predictions ) : row = [ ] for col in self . _header : row . append ( str ( tf_graph_predictions [ col ] ) ) return ',' . join ( row ) | Encodes the graph json prediction into csv . |
48,881 | def as_dataframe ( self , max_rows = None ) : max_rows = len ( self . _timeseries_list ) if max_rows is None else max_rows headers = [ { 'resource' : ts . resource . _asdict ( ) , 'metric' : ts . metric . _asdict ( ) } for ts in self . _timeseries_list [ : max_rows ] ] if not headers : return pandas . DataFrame ( ) dat... | Creates a pandas dataframe from the query metadata . |
48,882 | def get_train_eval_files ( input_dir ) : data_dir = _get_latest_data_dir ( input_dir ) train_pattern = os . path . join ( data_dir , 'train*.tfrecord.gz' ) eval_pattern = os . path . join ( data_dir , 'eval*.tfrecord.gz' ) train_files = file_io . get_matching_files ( train_pattern ) eval_files = file_io . get_matching_... | Get preprocessed training and eval files . |
48,883 | def get_labels ( input_dir ) : data_dir = _get_latest_data_dir ( input_dir ) labels_file = os . path . join ( data_dir , 'labels' ) with file_io . FileIO ( labels_file , 'r' ) as f : labels = f . read ( ) . rstrip ( ) . split ( '\n' ) return labels | Get a list of labels from preprocessed output dir . |
48,884 | def override_if_not_in_args ( flag , argument , args ) : if flag not in args : args . extend ( [ flag , argument ] ) | Checks if flags is in args and if not it adds the flag to args . |
48,885 | def loss ( loss_value ) : total_loss = tf . Variable ( 0.0 , False ) loss_count = tf . Variable ( 0 , False ) total_loss_update = tf . assign_add ( total_loss , loss_value ) loss_count_update = tf . assign_add ( loss_count , 1 ) loss_op = total_loss / tf . cast ( loss_count , tf . float32 ) return [ total_loss_update ,... | Calculates aggregated mean loss . |
48,886 | def accuracy ( logits , labels ) : is_correct = tf . nn . in_top_k ( logits , labels , 1 ) correct = tf . reduce_sum ( tf . cast ( is_correct , tf . int32 ) ) incorrect = tf . reduce_sum ( tf . cast ( tf . logical_not ( is_correct ) , tf . int32 ) ) correct_count = tf . Variable ( 0 , False ) incorrect_count = tf . Var... | Calculates aggregated accuracy . |
48,887 | def check_dataset ( dataset , mode ) : names = [ x [ 'name' ] for x in dataset . schema ] types = [ x [ 'type' ] for x in dataset . schema ] if mode == 'train' : if ( set ( [ 'image_url' , 'label' ] ) != set ( names ) or any ( t != 'STRING' for t in types ) ) : raise ValueError ( 'Invalid dataset. Expect only "image_ur... | Validate we have a good dataset . |
48,888 | def get_sources_from_dataset ( p , dataset , mode ) : import apache_beam as beam import csv from google . datalab . ml import CsvDataSet , BigQueryDataSet check_dataset ( dataset , mode ) if type ( dataset ) is CsvDataSet : source_list = [ ] for ii , input_path in enumerate ( dataset . files ) : source_list . append ( ... | get pcollection from dataset . |
48,889 | def decode_and_resize ( image_str_tensor ) : height = 299 width = 299 channels = 3 image = tf . image . decode_jpeg ( image_str_tensor , channels = channels ) image = tf . expand_dims ( image , 0 ) image = tf . image . resize_bilinear ( image , [ height , width ] , align_corners = False ) image = tf . squeeze ( image ,... | Decodes jpeg string resizes it and returns a uint8 tensor . |
48,890 | def resize_image ( image_str_tensor ) : image = decode_and_resize ( image_str_tensor ) image = tf . image . encode_jpeg ( image , quality = 100 ) return image | Decodes jpeg string resizes it and re - encode it to jpeg . |
48,891 | def load_images ( image_files , resize = True ) : images = [ ] for image_file in image_files : with file_io . FileIO ( image_file , 'r' ) as ff : images . append ( ff . read ( ) ) if resize is False : return images image_str_tensor = tf . placeholder ( tf . string , shape = [ None ] ) image = tf . map_fn ( resize_image... | Load images from files and optionally resize it . |
48,892 | def process_prediction_results ( results , show_image ) : import pandas as pd if ( is_in_IPython ( ) and show_image is True ) : import IPython for image_url , image , label_and_score in results : IPython . display . display_html ( '<p style="font-size:28px">%s(%.5f)</p>' % label_and_score , raw = True ) IPython . displ... | Create DataFrames out of prediction results and display images in IPython if requested . |
48,893 | def repackage_to_staging ( output_path ) : import google . datalab . ml as ml package_root = os . path . join ( os . path . dirname ( __file__ ) , '../../../' ) setup_py = os . path . join ( os . path . dirname ( __file__ ) , 'setup.py' ) staging_package_url = os . path . join ( output_path , 'staging' , 'image_classif... | Repackage it from local installed location and copy it to GCS . |
48,894 | def generate_airflow_spec ( name , pipeline_spec ) : task_definitions = '' up_steam_statements = '' parameters = pipeline_spec . get ( 'parameters' ) for ( task_id , task_details ) in sorted ( pipeline_spec [ 'tasks' ] . items ( ) ) : task_def = PipelineGenerator . _get_operator_definition ( task_id , task_details , pa... | Gets the airflow python spec for the Pipeline object . |
48,895 | def _get_dependency_definition ( task_id , dependencies ) : set_upstream_statements = '' for dependency in dependencies : set_upstream_statements = set_upstream_statements + '{0}.set_upstream({1})' . format ( task_id , dependency ) + '\n' return set_upstream_statements | Internal helper collects all the dependencies of the task and returns the Airflow equivalent python sytax for specifying them . |
48,896 | def _get_operator_class_name ( task_detail_type ) : task_type_to_operator_prefix_mapping = { 'pydatalab.bq.execute' : ( 'Execute' , 'google.datalab.contrib.bigquery.operators._bq_execute_operator' ) , 'pydatalab.bq.extract' : ( 'Extract' , 'google.datalab.contrib.bigquery.operators._bq_extract_operator' ) , 'pydatalab.... | Internal helper gets the name of the Airflow operator class . We maintain this in a map so this method really returns the enum name concatenated with the string Operator . |
48,897 | def _get_operator_param_name_and_values ( operator_class_name , task_details ) : operator_task_details = task_details . copy ( ) if 'type' in operator_task_details . keys ( ) : del operator_task_details [ 'type' ] if 'up_stream' in operator_task_details . keys ( ) : del operator_task_details [ 'up_stream' ] if ( operat... | Internal helper gets the name of the python parameter for the Airflow operator class . In some cases we do not expose the airflow parameter name in its native form but choose to expose a name that s more standard for Datalab or one that s more friendly . For example Airflow s BigQueryOperator uses bql for the query str... |
48,898 | def sample ( self , n ) : total = bq . Query ( 'select count(*) from %s' % self . _get_source ( ) ) . execute ( ) . result ( ) [ 0 ] . values ( ) [ 0 ] if n > total : raise ValueError ( 'sample larger than population' ) sampling = bq . Sampling . random ( percent = n * 100.0 / float ( total ) ) if self . _query is not ... | Samples data into a Pandas DataFrame . Note that it calls BigQuery so it will incur cost . |
48,899 | def size ( self ) : import tensorflow as tf if self . _size is None : self . _size = 0 options = tf . python_io . TFRecordOptions ( tf . python_io . TFRecordCompressionType . GZIP ) for tfexample_file in self . files : self . _size += sum ( 1 for x in tf . python_io . tf_record_iterator ( tfexample_file , options = opt... | The number of instances in the data . If the underlying data source changes it may be outdated . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.