Search is not available for this dataset
text
stringlengths
75
104k
def get_pdf(article, debug=False): """ Download an article PDF from arXiv. :param article: The ADS article to retrieve. :type article: :class:`ads.search.Article` :returns: The binary content of the requested PDF. """ print('Retrieving {0}'.format(article)) i...
def summarise_pdfs(pdfs): """ Collate the first page from each of the PDFs provided into a single PDF. :param pdfs: The contents of several PDF files. :type pdfs: list of str :returns: The contents of single PDF, which can be written directly to disk. """ # Ignore...
def execute(self): """ Execute the http request to the metrics service """ self.response = MetricsResponse.load_http_response( self.session.post(self.HTTP_ENDPOINT, data=self.json_payload) ) return self.response.metrics
def get_info(cls): """ Print all of the instantiated Singletons """ return '\n'.join( [str(cls._instances[key]) for key in cls._instances] )
def load_http_response(cls, http_response): """ This method should return an instantiated class and set its response to the requests.Response object. """ if not http_response.ok: raise APIResponseError(http_response.text) c = cls(http_response) c.respo...
def token(self): """ 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 ...
def session(self): """ http session interface, transparent proxy to requests.session """ if self._session is None: self._session = requests.session() self._session.headers.update( { "Authorization": "Bearer {}".format(self.token...
def ml(line, cell=None): """Implements the datalab cell magic for MLWorkbench operations. Args: line: the contents of the ml command line. Returns: The results of executing the cell. """ parser = google.datalab.utils.commands.CommandParser( prog='%ml', description=textwrap.dedent("""\ ...
def from_csv(input_csv_pattern, headers=None, schema_file=None): """Create a Metrics instance from csv file pattern. Args: input_csv_pattern: Path to Csv file pattern (with no header). Can be local or GCS path. headers: Csv headers. schema_file: Path to a JSON file containing BigQuery schema....
def from_bigquery(sql): """Create a Metrics instance from a bigquery query or table. Returns: a Metrics instance. Args: sql: A BigQuery table name or a query. """ if isinstance(sql, bq.Query): sql = sql._expanded_sql() parts = sql.split('.') if len(parts) == 1 or len(pa...
def _get_data_from_csv_files(self): """Get data from input csv files.""" 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
def _get_data_from_bigquery(self, queries): """Get data from bigquery table or query.""" all_df = [] for query in queries: all_df.append(query.execute().result().to_dataframe()) df = pd.concat(all_df, ignore_index=True) return df
def accuracy(self): """Get accuracy numbers for each target and overall. Returns: A DataFrame with two columns: 'class' and 'accuracy'. It also contains the overall accuracy with class being '_all'. Raises: Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery ...
def roc(self, num_thresholds, target_class, probability_column=None): """Get true positive rate, false positive rate values from evaluation results. Args: num_thresholds: an integer. Number of thresholds. target_class: a string indciating the target class, i.e. "daisy" in flower classification. ...
def precision_recall(self, num_thresholds, target_class, probability_column=None): """Get precision, recall values from evaluation results. Args: num_thresholds: an integer. Number of thresholds. target_class: a string indciating the target class, i.e. "daisy" in flower classification. probab...
def rmse(self): """Get RMSE for regression model evaluation results. Returns: the RMSE float number. Raises: Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery does not return 'target' or 'predicted' column, or if target or predicted is not number. ...
def mae(self): """Get MAE (Mean Absolute Error) for regression model evaluation results. Returns: the MAE float number. Raises: Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery does not return 'target' or 'predicted' column, or if target or predicted is no...
def percentile_nearest(self, percentile): """Get nearest percentile from regression model evaluation results. Args: percentile: a 0~100 float number. Returns: the percentile float number. Raises: Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery ...
def _expanded_sql(self): """Get the expanded BigQuery SQL string of this UDF Returns The expanded SQL string of this UDF """ if not self._sql: self._sql = UDF._build_udf(self._name, self._code, self._return_type, self._params, self._language, self._imports) ...
def _build_udf(name, code, return_type, params, language, imports): """Creates the UDF part of a BigQuery query using its pieces Args: name: the name of the javascript function code: function body implementing the logic. return_type: BigQuery data type of the function return. See supported da...
def parse_name(name): """ Parse a gs:// URL into the bucket and object names. Args: name: a GCS URL of the form gs://bucket or gs://bucket/object Returns: The bucket name (with no gs:// prefix), and the object name if present. If the name could not be parsed returns None for both. """ bucket = No...
def created_on(self): """The created timestamp of the bucket as a datetime.datetime.""" s = self._info.get('timeCreated', None) return dateutil.parser.parse(s) if s else None
def metadata(self): """Retrieves metadata about the bucket. Returns: A BucketMetadata instance with information about this bucket. Raises: Exception if there was an error requesting the bucket's metadata. """ if self._info is None: try: self._info = self._api.buckets_get(s...
def object(self, key): """Retrieves a Storage Object for the specified key in this bucket. The object need not exist. Args: key: the key of the object within the bucket. Returns: An Object instance representing the specified key. """ return _object.Object(self._name, key, context=s...
def objects(self, prefix=None, delimiter=None): """Get an iterator for the objects within this bucket. Args: prefix: an optional prefix to match objects. delimiter: an optional string to simulate directory-like semantics. The returned objects will be those whose names do not contain the ...
def delete(self): """Deletes the bucket. Raises: Exception if there was an error deleting the bucket. """ if self.exists(): try: self._api.buckets_delete(self._name) except Exception as e: raise e
def contains(self, name): """Checks if the specified bucket exists. Args: name: the name of the bucket to lookup. Returns: True if the bucket exists; False otherwise. Raises: Exception if there was an error requesting information about the bucket. """ try: self._api.buck...
def parse_name(name): """ Parse a gs:// URL into the bucket and item names. Args: name: a GCS URL of the form gs://bucket or gs://bucket/item Returns: The bucket name (with no gs:// prefix), and the item name if present. If the name could not be parsed returns None for both. """ bucket = None i...
def item(self, key): """Retrieves an Item object for the specified key in this bucket. The item need not exist. Args: key: the key of the item within the bucket. Returns: An Item instance representing the specified key. """ return _item.Item(self._name, key, context=self._context)
def items(self, prefix=None, delimiter=None): """Get an iterator for the items within this bucket. Args: prefix: an optional prefix to match items. delimiter: an optional string to simulate directory-like semantics. The returned items will be those whose names do not contain the delimite...
def create(self, project_id=None): """Creates the bucket. Args: project_id: the project in which to create the bucket. Returns: The bucket. Raises: Exception if there was an error creating the bucket. """ if not self.exists(): if project_id is None: project_id = ...
def create(self, name): """Creates a new bucket. Args: name: a unique name for the new bucket. Returns: The newly created bucket. Raises: Exception if there was an error creating the bucket. """ return Bucket(name, context=self._context).create(self._project_id)
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, ...
def train_async(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, ...
def list(self, pattern='*'): """Returns a list of resource descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"aws*"``, ``"*cluster*"``. Returns: A list of ResourceDescriptor ob...
def as_dataframe(self, pattern='*', max_rows=None): """Creates a pandas dataframe from the descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"aws*"``, ``"*cluster*"``. max_rows: The...
def extension(line, cell=None): """ Load an extension. Use %extension --help for more details. """ parser = _commands.CommandParser(prog='%extension', description=""" Load an extension into Datalab. Currently only mathjax is supported. """) subparser = parser.subcommand('mathjax', 'Enabled MathJaX support in Data...
def _extract_gcs_api_response_error(message): """ A helper function to extract user-friendly error messages from service exceptions. Args: message: An error message from an exception. If this is from our HTTP client code, it will actually be a tuple. Returns: A modified version of the message th...
def gcs(line, cell=None): """Implements the gcs cell magic for ipython notebooks. Args: line: the contents of the gcs line. Returns: The results of executing the cell. """ parser = google.datalab.utils.commands.CommandParser(prog='%gcs', description=""" Execute various Google Cloud Storage related op...
def _expand_list(names): """ Do a wildchar name expansion of object names in a list and return expanded list. The objects are expected to exist as this is used for copy sources or delete targets. Currently we support wildchars in the key name only. """ if names is None: names = [] elif isinstance(...
def _gcs_create(args, _): """ Create one or more buckets. """ errs = [] for name in args['bucket']: try: bucket, key = google.datalab.storage._bucket.parse_name(name) if bucket and not key: google.datalab.storage.Bucket(bucket).create(_make_context(args['project'])) else: rai...
def _gcs_delete(args, _): """ Delete one or more buckets or objects. """ objects = _expand_list(args['bucket']) objects.extend(_expand_list(args['object'])) errs = [] for obj in objects: try: bucket, key = google.datalab.storage._bucket.parse_name(obj) if bucket and key: gcs_object = g...
def _gcs_list_buckets(project, pattern): """ List all Google Cloud Storage buckets that match a 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, patte...
def _gcs_get_keys(bucket, pattern): """ Get names of all Google Cloud Storage keys in a specified bucket that match a pattern. """ return [obj for obj in list(bucket.objects()) if fnmatch.fnmatch(obj.metadata.name, pattern)]
def _gcs_get_key_names(bucket, pattern): """ Get names of all Google Cloud Storage keys in a specified bucket that match a pattern. """ return [obj.metadata.name for obj in _gcs_get_keys(bucket, pattern)]
def _gcs_list_keys(bucket, pattern): """ List all Google Cloud Storage keys in a specified bucket that match a pattern. """ data = [{'Name': obj.metadata.name, 'Type': obj.metadata.content_type, 'Size': obj.metadata.size, 'Updated': obj.metadata.updated_on} for obj in _gcs...
def _gcs_list(args, _): """ List the buckets or the contents of a bucket. This command is a bit different in that we allow wildchars in the bucket name and will list the buckets that match. """ target = args['objects'] project = args['project'] if target is None: return _gcs_list_buckets(project, '*'...
def parse_arguments(argv): """Parse command line arguments. Args: argv: list of command line arguments including program name. Returns: The parsed arguments as returned by argparse.ArgumentParser. """ parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, d...
def image_transform_columns(features): """Returns a list of columns that prepare_image_transforms() should run on. Because of beam + pickle, IMAGE_URL_TO_VEC_TRANSFORM cannot be used inside of a beam function, so we extract the columns prepare_image_transforms() should run on outside of beam. """ import s...
def prepare_image_transforms(element, image_columns): """Replace an images url with its jpeg bytes. Args: element: one input row, as a dict image_columns: list of columns that are image paths Return: element, where each image file path has been replaced by a base64 image. """ import base64 im...
def decode_csv(csv_string, column_names): """Parse a csv line into a dict. Args: csv_string: a csv string. May contain missing values "a,,c" column_names: list of column names Returns: Dict of {column_name, value_from_csv}. If there are missing values, value_from_csv will be ''. """ import ...
def encode_csv(data_dict, column_names): """Builds a csv string. Args: data_dict: dict of {column_name: 1 value} column_names: list of column names Returns: A csv string version of data_dict """ import csv import six values = [str(data_dict[x]) for x in column_names] str_buff = six.StringI...
def serialize_example(transformed_json_data, info_dict): """Makes a serialized tf.example. Args: transformed_json_data: dict of transformed data. info_dict: output of feature_transforms.get_transfrormed_feature_info() Returns: The serialized tf.example version of transformed_json_data. """ impor...
def preprocess(pipeline, args): """Transfrom csv data into transfromed tf.example files. Outline: 1) read the input data (as csv or bigquery) into a dict format 2) replace image paths with base64 encoded image files 3) build a csv input string with images paths replaced with base64. This matche...
def main(argv=None): """Run Preprocessing as a Dataflow.""" 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' # Suppress TF warnings. os.environ['TF_CPP_MI...
def start_bundle(self, element=None): """Build the transfromation graph once.""" import tensorflow as tf from trainer import feature_transforms g = tf.Graph() session = tf.Session(graph=g) # Build the transformation graph with g.as_default(): transformed_features, _, placeholders = (...
def process(self, element): """Run the transformation graph on batched input data Args: element: list of csv strings, representing one batch input to the TF graph. Returns: dict containing the transformed data. Results are un-batched. Sparse tensors are converted to lists. """ im...
def parse_row(schema, data): """Parses a row from query results into an equivalent object. Args: schema: the array of fields defining the schema of the data. data: the JSON row from a query result. Returns: The parsed row object. """ def parse_value(data_type, value): """Par...
def _tf_load_model(sess, model_dir): """Load a tf model from model_dir, and return input/output alias maps.""" meta_graph_pb = tf.saved_model.loader.load( sess=sess, tags=[tf.saved_model.tag_constants.SERVING], export_dir=model_dir) signature = meta_graph_pb.signature_def[signature_constants.D...
def _tf_predict(model_dir, input_csvlines): """Prediction with a tf savedmodel. Args: model_dir: directory that contains a saved model input_csvlines: list of csv strings Returns: Dict in the form tensor_name:prediction_list. Note that the value is always a list, even if there was only 1 row...
def _download_images(data, img_cols): """Download images given image columns.""" 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): # If it is already an Image, just copy and continue. ...
def _get_predicton_csv_lines(data, headers, images): """Create CSV lines from list-of-dict data.""" 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), Im...
def _get_display_data_with_images(data, images): """Create display data by converting image urls to base64 strings.""" 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'] ...
def get_model_schema_and_features(model_dir): """Get a local model's schema and features config. Args: model_dir: local or GCS path of a model. Returns: A tuple of schema (list) and features config (dict). """ schema_file = os.path.join(model_dir, 'assets.extra', 'schema.json') schema = json.loads(...
def get_prediction_results(model_dir_or_id, data, headers, img_cols=None, cloud=False, with_source=True, show_image=True): """ Predict with a specified model. It predicts with the model, join source data with prediction results, and formats the results so they can be displayed nicely i...
def get_probs_for_labels(labels, prediction_results): """ Given ML Workbench prediction results, get probs of each label for each instance. The prediction results are like: [ {'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1}, {'predicted': 'sunflower', 'probability':...
def local_batch_predict(model_dir, csv_file_pattern, output_dir, output_format, batch_size=100): """ Batch Predict with a specified model. It does batch prediction, saves results to output files and also creates an output schema file. The output file names are input file names prepended by 'predict_results_'. ...
def _refresh_state(self): """ Refresh the job info. """ self._info = self._api.projects().jobs().get(name=self._name).execute() self._fatal_error = self._info.get('errorMessage', None) state = str(self._info.get('state')) self._is_complete = (state == 'SUCCEEDED' or state == 'FAILED')
def submit_training(job_request, job_id=None): """Submit a training job. Args: job_request: the arguments of the training job in a dict. For example, { 'package_uris': 'gs://my-bucket/iris/trainer-0.1.tar.gz', 'python_module': 'trainer.task', 'scale_tier': '...
def submit_batch_prediction(job_request, job_id=None): """Submit a batch prediction job. Args: job_request: the arguments of the training job in a dict. For example, { 'version_name': 'projects/my-project/models/my-model/versions/my-version', 'data_format': 'TEXT', ...
def parse_arguments(argv): """Parse command line arguments. Args: argv: list of command line arguments, including program name. Returns: An argparse Namespace object. Raises: ValueError: for bad parameters """ parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelp...
def run_cloud_analysis(output_dir, csv_file_pattern, bigquery_table, schema, features): """Use BigQuery to analyze input date. Only one of csv_file_pattern or bigquery_table should be non-None. Args: output_dir: output folder csv_file_pattern: list of csv file paths, may contain w...
def inception_v3_base(inputs, final_endpoint='Mixed_7c', min_depth=16, depth_multiplier=1.0, scope=None): """Inception model from http://arxiv.org/abs/1512.00567. Constructs an Inception v3 network from inputs to the given fina...
def inception_v3(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.8, min_depth=16, depth_multiplier=1.0, prediction_fn=slim.softmax, spatial_squeeze=True, reuse=None, ...
def _reduced_kernel_size_for_small_input(input_tensor, kernel_size): """Define kernel size which is automatically reduced for small input. If the shape of the input images is unknown at graph construction time this function assumes that the input images are is large enough. Args: input_tensor: input tenso...
def inception_v3_arg_scope(weight_decay=0.00004, stddev=0.1, batch_norm_var_collection='moving_vars'): """Defines the default InceptionV3 arg scope. Args: weight_decay: The weight decay to use for regularizing the model. stddev: The standard deviation o...
def preprocess(train_dataset, output_dir, eval_dataset, checkpoint): """Preprocess data locally.""" 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-im...
def train(input_dir, batch_size, max_steps, output_dir, checkpoint): """Train model locally.""" 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) ...
def predict(model_dir, image_files, resize, show_image): """Predict using an model in a local or GCS directory.""" 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...
def batch_predict(dataset, model_dir, output_csv, output_bq_table): """Batch predict running locally.""" 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_b...
def result(self): """ Get the result for a job. This will block if the job is incomplete. Returns: The result for the Job. Raises: An exception if the Job resulted in an exception. """ self.wait() if self._fatal_error: raise self._fatal_error return self._result
def _refresh_state(self): """ Get the state of a job. Must be overridden by derived Job classes for Jobs that don't use a Future. """ if self._is_complete: return if not self._future: raise Exception('Please implement this in the derived class') if self._future.done(): se...
def wait(self, timeout=None): """ Wait for the job to complete, or a timeout to happen. Args: timeout: how long to wait before giving up (in seconds); default None which means no timeout. Returns: The Job """ if self._future: try: # Future.exception() will return rather t...
def state(self): """ Describe the state of a Job. Returns: A string describing the job's state. """ 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-fat...
def wait_any(jobs, timeout=None): """ Return when at least one of the specified jobs has completed or timeout expires. Args: jobs: a Job or list of Jobs to wait on. timeout: a timeout in seconds to wait for. None (the default) means no timeout. Returns: A list of the jobs that have now co...
def wait_all(jobs, timeout=None): """ Return when at all of the specified jobs have completed or timeout expires. Args: jobs: a Job or list of Jobs to wait on. timeout: a timeout in seconds to wait for. None (the default) means no timeout. Returns: A list of the jobs that have now complet...
def evaluate(self, num_eval_batches=None): """Run one round of evaluation, return loss and accuracy.""" 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, ...
def run_training(self): """Runs a Master.""" self.train_path = os.path.join(self.output_path, 'train') self.model_path = os.path.join(self.output_path, 'model') self.is_master = self.task.type != 'worker' log_interval = 15 self.eval_interval = 30 if self.is_master and self.task.index > 0: ...
def log(self, session): """Logs training progress.""" 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_ste...
def eval(self, session): """Runs evaluation loop.""" 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_e...
def _get_lantern_format(self, df): """ Feature slice view browser expects data in the format of: {"metricValues": {"count": 12, "accuracy": 1.0}, "feature": "species:Iris-setosa"} {"metricValues": {"count": 11, "accuracy": 0.72}, "feature": "species:Iris-versicolor"} ... This f...
def plot(self, data): """ Plots a featire slice view on given data. Args: data: Can be one of: A string of sql query. A sql query module defined by "%%sql --module module_name". A pandas DataFrame. Regardless of data type, it must include the following columns: ...
def parse_arguments(argv): """Parse command line arguments. Args: argv: list of command line arguments, includeing programe name. Returns: An argparse Namespace object. Raises: ValueError: for bad parameters """ parser = argparse.ArgumentParser( description='Runs Preprocessing on struct...
def parse_table_name(bigquery_table): """Giving a string a:b.c, returns b.c. Args: bigquery_table: full table name project_id:dataset:table Returns: dataset:table Raises: ValueError: if a, b, or c contain the character ':'. """ id_name = bigquery_table.split(':') if len(id_name) != 2: ...
def run_numerical_analysis(table, schema_list, args): """Find min/max values for the numerical columns and writes a json file. Args: table: Reference to FederatedTable (if bigquery_table is false) or a regular Table (otherwise) schema_list: Bigquery schema json object args: the command line arg...
def run_categorical_analysis(table, schema_list, args): """Find vocab values for the categorical columns and writes a csv file. The vocab files are in the from label1 label2 label3 ... Args: table: Reference to FederatedTable (if bigquery_table is false) or a regular Table (otherwise) sc...
def run_analysis(args): """Builds an analysis file for training. Uses BiqQuery tables to do the analysis. Args: args: command line args Raises: ValueError if schema contains unknown types. """ import google.datalab.bigquery as bq if args.bigquery_table: table = bq.Table(args.bigquery_table)...
def set_project_id(self, project_id): """ Set the project_id for the context. """ self._project_id = project_id if self == Context._global_context: du.save_project_id(self._project_id)
def default(): """Retrieves a default Context object, creating it if necessary. The default Context is a global shared instance used every time the default context is retrieved. Attempting to use a Context with no project_id will raise an exception, so on first use set_project_id must be c...
def from_csv(input_csv, headers=None, schema_file=None): """Create a ConfusionMatrix from a csv file. Args: input_csv: Path to a Csv file (with no header). Can be local or GCS path. headers: Csv headers. If present, it must include 'target' and 'predicted'. schema_file: Path to a JSON file co...