repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
andycasey/ads
examples/monthly-institute-publications/stromlo.py
get_pdf
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...
python
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", "get_pdf", "(", "article", ",", "debug", "=", "False", ")", ":", "print", "(", "'Retrieving {0}'", ".", "format", "(", "article", ")", ")", "identifier", "=", "[", "_", "for", "_", "in", "article", ".", "identifier", "if", "'arXiv'", "in", "_", ...
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.
[ "Download", "an", "article", "PDF", "from", "arXiv", "." ]
train
https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/examples/monthly-institute-publications/stromlo.py#L22-L64
andycasey/ads
examples/monthly-institute-publications/stromlo.py
summarise_pdfs
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...
python
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", "summarise_pdfs", "(", "pdfs", ")", ":", "# Ignore None.", "print", "(", "'Summarising {0} articles ({1} had errors)'", ".", "format", "(", "len", "(", "pdfs", ")", ",", "pdfs", ".", "count", "(", "None", ")", ")", ")", "pdfs", "=", "[", "_", "for",...
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.
[ "Collate", "the", "first", "page", "from", "each", "of", "the", "PDFs", "provided", "into", "a", "single", "PDF", "." ]
train
https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/examples/monthly-institute-publications/stromlo.py#L67-L89
andycasey/ads
ads/metrics.py
MetricsQuery.execute
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
python
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", "execute", "(", "self", ")", ":", "self", ".", "response", "=", "MetricsResponse", ".", "load_http_response", "(", "self", ".", "session", ".", "post", "(", "self", ".", "HTTP_ENDPOINT", ",", "data", "=", "self", ".", "json_payload", ")", ")", "re...
Execute the http request to the metrics service
[ "Execute", "the", "http", "request", "to", "the", "metrics", "service" ]
train
https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/ads/metrics.py#L47-L54
andycasey/ads
ads/base.py
_Singleton.get_info
def get_info(cls): """ Print all of the instantiated Singletons """ return '\n'.join( [str(cls._instances[key]) for key in cls._instances] )
python
def get_info(cls): """ Print all of the instantiated Singletons """ return '\n'.join( [str(cls._instances[key]) for key in cls._instances] )
[ "def", "get_info", "(", "cls", ")", ":", "return", "'\\n'", ".", "join", "(", "[", "str", "(", "cls", ".", "_instances", "[", "key", "]", ")", "for", "key", "in", "cls", ".", "_instances", "]", ")" ]
Print all of the instantiated Singletons
[ "Print", "all", "of", "the", "instantiated", "Singletons" ]
train
https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/ads/base.py#L25-L31
andycasey/ads
ads/base.py
APIResponse.load_http_response
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...
python
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", "load_http_response", "(", "cls", ",", "http_response", ")", ":", "if", "not", "http_response", ".", "ok", ":", "raise", "APIResponseError", "(", "http_response", ".", "text", ")", "c", "=", "cls", "(", "http_response", ")", "c", ".", "response", "=...
This method should return an instantiated class and set its response to the requests.Response object.
[ "This", "method", "should", "return", "an", "instantiated", "class", "and", "set", "its", "response", "to", "the", "requests", ".", "Response", "object", "." ]
train
https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/ads/base.py#L88-L100
andycasey/ads
ads/base.py
BaseQuery.token
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 ...
python
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", "token", "(", "self", ")", ":", "if", "self", ".", "_token", "is", "None", ":", "for", "v", "in", "map", "(", "os", ".", "environ", ".", "get", ",", "TOKEN_ENVIRON_VARS", ")", ":", "if", "v", "is", "not", "None", ":", "self", ".", "_token"...
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
[ "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",...
train
https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/ads/base.py#L111-L136
andycasey/ads
ads/base.py
BaseQuery.session
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...
python
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", "session", "(", "self", ")", ":", "if", "self", ".", "_session", "is", "None", ":", "self", ".", "_session", "=", "requests", ".", "session", "(", ")", "self", ".", "_session", ".", "headers", ".", "update", "(", "{", "\"Authorization\"", ":", ...
http session interface, transparent proxy to requests.session
[ "http", "session", "interface", "transparent", "proxy", "to", "requests", ".", "session" ]
train
https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/ads/base.py#L143-L156
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/commands/_ml.py
ml
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("""\ ...
python
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", "ml", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "CommandParser", "(", "prog", "=", "'%ml'", ",", "description", "=", "textwrap", ".", "dedent", "(", "\"\"\"\\\n ...
Implements the datalab cell magic for MLWorkbench operations. Args: line: the contents of the ml command line. Returns: The results of executing the cell.
[ "Implements", "the", "datalab", "cell", "magic", "for", "MLWorkbench", "operations", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/commands/_ml.py#L57-L570
googledatalab/pydatalab
google/datalab/ml/_metrics.py
Metrics.from_csv
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....
python
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_csv", "(", "input_csv_pattern", ",", "headers", "=", "None", ",", "schema_file", "=", "None", ")", ":", "if", "headers", "is", "not", "None", ":", "names", "=", "headers", "elif", "schema_file", "is", "not", "None", ":", "with", "_util", "."...
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. Used if "headers" is None. Returns: a Metrics instance. ...
[ "Create", "a", "Metrics", "instance", "from", "csv", "file", "pattern", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L56-L81
googledatalab/pydatalab
google/datalab/ml/_metrics.py
Metrics.from_bigquery
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...
python
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", "from_bigquery", "(", "sql", ")", ":", "if", "isinstance", "(", "sql", ",", "bq", ".", "Query", ")", ":", "sql", "=", "sql", ".", "_expanded_sql", "(", ")", "parts", "=", "sql", ".", "split", "(", "'.'", ")", "if", "len", "(", "parts", ")"...
Create a Metrics instance from a bigquery query or table. Returns: a Metrics instance. Args: sql: A BigQuery table name or a query.
[ "Create", "a", "Metrics", "instance", "from", "a", "bigquery", "query", "or", "table", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L84-L104
googledatalab/pydatalab
google/datalab/ml/_metrics.py
Metrics._get_data_from_csv_files
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
python
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_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", ":", ...
Get data from input csv files.
[ "Get", "data", "from", "input", "csv", "files", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L106-L114
googledatalab/pydatalab
google/datalab/ml/_metrics.py
Metrics._get_data_from_bigquery
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
python
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", "_get_data_from_bigquery", "(", "self", ",", "queries", ")", ":", "all_df", "=", "[", "]", "for", "query", "in", "queries", ":", "all_df", ".", "append", "(", "query", ".", "execute", "(", ")", ".", "result", "(", ")", ".", "to_dataframe", "(", ...
Get data from bigquery table or query.
[ "Get", "data", "from", "bigquery", "table", "or", "query", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L116-L123
googledatalab/pydatalab
google/datalab/ml/_metrics.py
Metrics.accuracy
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 ...
python
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", "accuracy", "(", "self", ")", ":", "if", "self", ".", "_input_csv_files", ":", "df", "=", "self", ".", "_get_data_from_csv_files", "(", ")", "if", "'target'", "not", "in", "df", "or", "'predicted'", "not", "in", "df", ":", "raise", "ValueError", "...
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 does not return 'targ...
[ "Get", "accuracy", "numbers", "for", "each", "target", "and", "overall", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L125-L178
googledatalab/pydatalab
google/datalab/ml/_metrics.py
Metrics.roc
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. ...
python
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", "roc", "(", "self", ",", "num_thresholds", ",", "target_class", ",", "probability_column", "=", "None", ")", ":", "if", "not", "probability_column", ":", "probability_column", "=", "target_class", "thresholds", "=", "np", ".", "linspace", "(", "0", ",",...
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. probability_column: the name of the probability column. If None, defaults ...
[ "Get", "true", "positive", "rate", "false", "positive", "rate", "values", "from", "evaluation", "results", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L180-L280
googledatalab/pydatalab
google/datalab/ml/_metrics.py
Metrics.precision_recall
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...
python
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", "precision_recall", "(", "self", ",", "num_thresholds", ",", "target_class", ",", "probability_column", "=", "None", ")", ":", "if", "not", "probability_column", ":", "probability_column", "=", "target_class", "# threshold = 1.0 is excluded.", "thresholds", "=", ...
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. probability_column: the name of the probability column. If None, defaults to value of ...
[ "Get", "precision", "recall", "values", "from", "evaluation", "results", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L282-L372
googledatalab/pydatalab
google/datalab/ml/_metrics.py
Metrics.rmse
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. ...
python
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", "rmse", "(", "self", ")", ":", "if", "self", ".", "_input_csv_files", ":", "df", "=", "self", ".", "_get_data_from_csv_files", "(", ")", "if", "'target'", "not", "in", "df", "or", "'predicted'", "not", "in", "df", ":", "raise", "ValueError", "(", ...
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.
[ "Get", "RMSE", "for", "regression", "model", "evaluation", "results", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L374-L404
googledatalab/pydatalab
google/datalab/ml/_metrics.py
Metrics.mae
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...
python
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", "mae", "(", "self", ")", ":", "if", "self", ".", "_input_csv_files", ":", "df", "=", "self", ".", "_get_data_from_csv_files", "(", ")", "if", "'target'", "not", "in", "df", "or", "'predicted'", "not", "in", "df", ":", "raise", "ValueError", "(", ...
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 not number.
[ "Get", "MAE", "(", "Mean", "Absolute", "Error", ")", "for", "regression", "model", "evaluation", "results", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L406-L435
googledatalab/pydatalab
google/datalab/ml/_metrics.py
Metrics.percentile_nearest
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 ...
python
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", "percentile_nearest", "(", "self", ",", "percentile", ")", ":", "if", "self", ".", "_input_csv_files", ":", "df", "=", "self", ".", "_get_data_from_csv_files", "(", ")", "if", "'target'", "not", "in", "df", "or", "'predicted'", "not", "in", "df", ":...
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 does not return 'target' or 'predicted' column, o...
[ "Get", "nearest", "percentile", "from", "regression", "model", "evaluation", "results", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_metrics.py#L437-L470
googledatalab/pydatalab
google/datalab/bigquery/_udf.py
UDF._expanded_sql
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) ...
python
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", "_expanded_sql", "(", "self", ")", ":", "if", "not", "self", ".", "_sql", ":", "self", ".", "_sql", "=", "UDF", ".", "_build_udf", "(", "self", ".", "_name", ",", "self", ".", "_code", ",", "self", ".", "_return_type", ",", "self", ".", "_pa...
Get the expanded BigQuery SQL string of this UDF Returns The expanded SQL string of this UDF
[ "Get", "the", "expanded", "BigQuery", "SQL", "string", "of", "this", "UDF" ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_udf.py#L65-L74
googledatalab/pydatalab
google/datalab/bigquery/_udf.py
UDF._build_udf
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...
python
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", "_build_udf", "(", "name", ",", "code", ",", "return_type", ",", "params", ",", "language", ",", "imports", ")", ":", "params", "=", "','", ".", "join", "(", "[", "'%s %s'", "%", "named_param", "for", "named_param", "in", "params", "]", ")", "im...
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 data types in the BigQuery docs params: dictionary of parameter...
[ "Creates", "the", "UDF", "part", "of", "a", "BigQuery", "query", "using", "its", "pieces" ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_udf.py#L83-L116
googledatalab/pydatalab
google/datalab/storage/_bucket.py
parse_name
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...
python
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", "parse_name", "(", "name", ")", ":", "bucket", "=", "None", "obj", "=", "None", "m", "=", "re", ".", "match", "(", "_STORAGE_NAME", ",", "name", ")", "if", "m", ":", "# We want to return the last two groups as first group is the optional 'gs://'", "bucket",...
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.
[ "Parse", "a", "gs", ":", "//", "URL", "into", "the", "bucket", "and", "object", "names", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L34-L56
googledatalab/pydatalab
google/datalab/storage/_bucket.py
BucketMetadata.created_on
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
python
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", "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.
[ "The", "created", "timestamp", "of", "the", "bucket", "as", "a", "datetime", ".", "datetime", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L71-L74
googledatalab/pydatalab
google/datalab/storage/_bucket.py
Bucket.metadata
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...
python
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", "metadata", "(", "self", ")", ":", "if", "self", ".", "_info", "is", "None", ":", "try", ":", "self", ".", "_info", "=", "self", ".", "_api", ".", "buckets_get", "(", "self", ".", "_name", ")", "except", "Exception", "as", "e", ":", "raise",...
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.
[ "Retrieves", "metadata", "about", "the", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L118-L132
googledatalab/pydatalab
google/datalab/storage/_bucket.py
Bucket.object
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...
python
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", "object", "(", "self", ",", "key", ")", ":", "return", "_object", ".", "Object", "(", "self", ".", "_name", ",", "key", ",", "context", "=", "self", ".", "_context", ")" ]
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.
[ "Retrieves", "a", "Storage", "Object", "for", "the", "specified", "key", "in", "this", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L134-L144
googledatalab/pydatalab
google/datalab/storage/_bucket.py
Bucket.objects
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 ...
python
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", "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. 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 delimiter after the prefix. For the remainin...
[ "Get", "an", "iterator", "for", "the", "objects", "within", "this", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L146-L158
googledatalab/pydatalab
google/datalab/storage/_bucket.py
Bucket.delete
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
python
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", "delete", "(", "self", ")", ":", "if", "self", ".", "exists", "(", ")", ":", "try", ":", "self", ".", "_api", ".", "buckets_delete", "(", "self", ".", "_name", ")", "except", "Exception", "as", "e", ":", "raise", "e" ]
Deletes the bucket. Raises: Exception if there was an error deleting the bucket.
[ "Deletes", "the", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L185-L195
googledatalab/pydatalab
google/datalab/storage/_bucket.py
Buckets.contains
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...
python
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", "contains", "(", "self", ",", "name", ")", ":", "try", ":", "self", ".", "_api", ".", "buckets_get", "(", "name", ")", "except", "google", ".", "datalab", ".", "utils", ".", "RequestException", "as", "e", ":", "if", "e", ".", "status", "==", ...
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.
[ "Checks", "if", "the", "specified", "bucket", "exists", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_bucket.py#L215-L233
googledatalab/pydatalab
datalab/storage/_bucket.py
parse_name
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...
python
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", "parse_name", "(", "name", ")", ":", "bucket", "=", "None", "item", "=", "None", "m", "=", "re", ".", "match", "(", "_STORAGE_NAME", ",", "name", ")", "if", "m", ":", "# We want to return the last two groups as first group is the optional 'gs://'", "bucket"...
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.
[ "Parse", "a", "gs", ":", "//", "URL", "into", "the", "bucket", "and", "item", "names", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_bucket.py#L34-L56
googledatalab/pydatalab
datalab/storage/_bucket.py
Bucket.item
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)
python
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", "item", "(", "self", ",", "key", ")", ":", "return", "_item", ".", "Item", "(", "self", ".", "_name", ",", "key", ",", "context", "=", "self", ".", "_context", ")" ]
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.
[ "Retrieves", "an", "Item", "object", "for", "the", "specified", "key", "in", "this", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_bucket.py#L134-L144
googledatalab/pydatalab
datalab/storage/_bucket.py
Bucket.items
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...
python
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", "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. 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 delimiter after the prefix. For the remaining item...
[ "Get", "an", "iterator", "for", "the", "items", "within", "this", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_bucket.py#L146-L158
googledatalab/pydatalab
datalab/storage/_bucket.py
Bucket.create
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 = ...
python
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", ",", "project_id", "=", "None", ")", ":", "if", "not", "self", ".", "exists", "(", ")", ":", "if", "project_id", "is", "None", ":", "project_id", "=", "self", ".", "_api", ".", "project_id", "try", ":", "self", ".", "_...
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.
[ "Creates", "the", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_bucket.py#L167-L184
googledatalab/pydatalab
datalab/storage/_bucket.py
Buckets.create
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)
python
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", "create", "(", "self", ",", "name", ")", ":", "return", "Bucket", "(", "name", ",", "context", "=", "self", ".", "_context", ")", ".", "create", "(", "self", ".", "_project_id", ")" ]
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.
[ "Creates", "a", "new", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_bucket.py#L238-L248
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/regression/dnn/_regression_dnn.py
train
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, ...
python
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", "(", "train_dataset", ",", "eval_dataset", ",", "analysis_dir", ",", "output_dir", ",", "features", ",", "layer_sizes", ",", "max_steps", "=", "5000", ",", "num_epochs", "=", "None", ",", "train_batch_size", "=", "100", ",", "eval_batch_size", ...
Blocking version of train_async. See documentation for train_async.
[ "Blocking", "version", "of", "train_async", ".", "See", "documentation", "for", "train_async", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/regression/dnn/_regression_dnn.py#L4-L39
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/regression/dnn/_regression_dnn.py
train_async
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, ...
python
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", "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_siz...
Train model locally or in the cloud. Local Training: Args: train_dataset: CsvDataSet eval_dataset: CsvDataSet analysis_dir: The output directory from local_analysis output_dir: Output directory of training. features: file path or features object. Example: { "col_A": {"trans...
[ "Train", "model", "locally", "or", "in", "the", "cloud", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/regression/dnn/_regression_dnn.py#L42-L142
googledatalab/pydatalab
datalab/stackdriver/monitoring/_resource.py
ResourceDescriptors.list
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...
python
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", "list", "(", "self", ",", "pattern", "=", "'*'", ")", ":", "if", "self", ".", "_descriptors", "is", "None", ":", "self", ".", "_descriptors", "=", "self", ".", "_client", ".", "list_resource_descriptors", "(", "filter_string", "=", "self", ".", "_...
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 objects that match the filters.
[ "Returns", "a", "list", "of", "resource", "descriptors", "that", "match", "the", "filters", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/stackdriver/monitoring/_resource.py#L43-L57
googledatalab/pydatalab
datalab/stackdriver/monitoring/_resource.py
ResourceDescriptors.as_dataframe
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...
python
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", "as_dataframe", "(", "self", ",", "pattern", "=", "'*'", ",", "max_rows", "=", "None", ")", ":", "data", "=", "[", "]", "for", "i", ",", "resource", "in", "enumerate", "(", "self", ".", "list", "(", "pattern", ")", ")", ":", "if", "max_rows"...
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 maximum number of descriptors to return. If None, return ...
[ "Creates", "a", "pandas", "dataframe", "from", "the", "descriptors", "that", "match", "the", "filters", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/stackdriver/monitoring/_resource.py#L59-L78
googledatalab/pydatalab
datalab/utils/commands/_extension.py
extension
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...
python
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", "extension", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "_commands", ".", "CommandParser", "(", "prog", "=", "'%extension'", ",", "description", "=", "\"\"\"\nLoad an extension into Datalab. Currently only mathjax is supported.\n\"\"\"", ")",...
Load an extension. Use %extension --help for more details.
[ "Load", "an", "extension", ".", "Use", "%extension", "--", "help", "for", "more", "details", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_extension.py#L29-L37
googledatalab/pydatalab
google/datalab/storage/commands/_storage.py
_extract_gcs_api_response_error
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...
python
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", "_extract_gcs_api_response_error", "(", "message", ")", ":", "try", ":", "if", "len", "(", "message", ")", "==", "3", ":", "# Try treat the last part as JSON", "data", "=", "json", ".", "loads", "(", "message", "[", "2", "]", ")", "return", "data", ...
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 that is less cryptic.
[ "A", "helper", "function", "to", "extract", "user", "-", "friendly", "error", "messages", "from", "service", "exceptions", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L34-L51
googledatalab/pydatalab
google/datalab/storage/commands/_storage.py
gcs
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...
python
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", "gcs", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "CommandParser", "(", "prog", "=", "'%gcs'", ",", "description", "=", "\"\"\"\nExecute various Google Cloud Storage rela...
Implements the gcs cell magic for ipython notebooks. Args: line: the contents of the gcs line. Returns: The results of executing the cell.
[ "Implements", "the", "gcs", "cell", "magic", "for", "ipython", "notebooks", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L55-L131
googledatalab/pydatalab
google/datalab/storage/commands/_storage.py
_expand_list
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(...
python
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", "_expand_list", "(", "names", ")", ":", "if", "names", "is", "None", ":", "names", "=", "[", "]", "elif", "isinstance", "(", "names", ",", "basestring", ")", ":", "names", "=", "[", "names", "]", "results", "=", "[", "]", "# The expanded list.",...
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.
[ "Do", "a", "wildchar", "name", "expansion", "of", "object", "names", "in", "a", "list", "and", "return", "expanded", "list", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L141-L193
googledatalab/pydatalab
google/datalab/storage/commands/_storage.py
_gcs_create
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...
python
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_create", "(", "args", ",", "_", ")", ":", "errs", "=", "[", "]", "for", "name", "in", "args", "[", "'bucket'", "]", ":", "try", ":", "bucket", ",", "key", "=", "google", ".", "datalab", ".", "storage", ".", "_bucket", ".", "parse_name"...
Create one or more buckets.
[ "Create", "one", "or", "more", "buckets", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L226-L240
googledatalab/pydatalab
google/datalab/storage/commands/_storage.py
_gcs_delete
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...
python
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_delete", "(", "args", ",", "_", ")", ":", "objects", "=", "_expand_list", "(", "args", "[", "'bucket'", "]", ")", "objects", ".", "extend", "(", "_expand_list", "(", "args", "[", "'object'", "]", ")", ")", "errs", "=", "[", "]", "for", ...
Delete one or more buckets or objects.
[ "Delete", "one", "or", "more", "buckets", "or", "objects", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L243-L269
googledatalab/pydatalab
google/datalab/storage/commands/_storage.py
_gcs_list_buckets
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...
python
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_list_buckets", "(", "project", ",", "pattern", ")", ":", "data", "=", "[", "{", "'Bucket'", ":", "'gs://'", "+", "bucket", ".", "name", ",", "'Created'", ":", "bucket", ".", "metadata", ".", "created_on", "}", "for", "bucket", "in", "google"...
List all Google Cloud Storage buckets that match a pattern.
[ "List", "all", "Google", "Cloud", "Storage", "buckets", "that", "match", "a", "pattern", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L278-L283
googledatalab/pydatalab
google/datalab/storage/commands/_storage.py
_gcs_get_keys
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)]
python
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_keys", "(", "bucket", ",", "pattern", ")", ":", "return", "[", "obj", "for", "obj", "in", "list", "(", "bucket", ".", "objects", "(", ")", ")", "if", "fnmatch", ".", "fnmatch", "(", "obj", ".", "metadata", ".", "name", ",", "pattern"...
Get names of all Google Cloud Storage keys in a specified bucket that match a pattern.
[ "Get", "names", "of", "all", "Google", "Cloud", "Storage", "keys", "in", "a", "specified", "bucket", "that", "match", "a", "pattern", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L286-L288
googledatalab/pydatalab
google/datalab/storage/commands/_storage.py
_gcs_get_key_names
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)]
python
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_get_key_names", "(", "bucket", ",", "pattern", ")", ":", "return", "[", "obj", ".", "metadata", ".", "name", "for", "obj", "in", "_gcs_get_keys", "(", "bucket", ",", "pattern", ")", "]" ]
Get names of all Google Cloud Storage keys in a specified bucket that match a pattern.
[ "Get", "names", "of", "all", "Google", "Cloud", "Storage", "keys", "in", "a", "specified", "bucket", "that", "match", "a", "pattern", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L291-L293
googledatalab/pydatalab
google/datalab/storage/commands/_storage.py
_gcs_list_keys
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...
python
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_keys", "(", "bucket", ",", "pattern", ")", ":", "data", "=", "[", "{", "'Name'", ":", "obj", ".", "metadata", ".", "name", ",", "'Type'", ":", "obj", ".", "metadata", ".", "content_type", ",", "'Size'", ":", "obj", ".", "metadata", ...
List all Google Cloud Storage keys in a specified bucket that match a pattern.
[ "List", "all", "Google", "Cloud", "Storage", "keys", "in", "a", "specified", "bucket", "that", "match", "a", "pattern", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L296-L303
googledatalab/pydatalab
google/datalab/storage/commands/_storage.py
_gcs_list
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, '*'...
python
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", "_gcs_list", "(", "args", ",", "_", ")", ":", "target", "=", "args", "[", "'objects'", "]", "project", "=", "args", "[", "'project'", "]", "if", "target", "is", "None", ":", "return", "_gcs_list_buckets", "(", "project", ",", "'*'", ")", "# List...
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.
[ "List", "the", "buckets", "or", "the", "contents", "of", "a", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/commands/_storage.py#L306-L345
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/transform.py
parse_arguments
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...
python
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", "parse_arguments", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ",", "description", "=", "textwrap", ".", "dedent", "(", "\"\"\"\\\n Runs preproces...
Parse command line arguments. Args: argv: list of command line arguments including program name. Returns: The parsed arguments as returned by argparse.ArgumentParser.
[ "Parse", "command", "line", "arguments", ".", "Args", ":", "argv", ":", "list", "of", "command", "line", "arguments", "including", "program", "name", ".", "Returns", ":", "The", "parsed", "arguments", "as", "returned", "by", "argparse", ".", "ArgumentParser", ...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L33-L167
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/transform.py
image_transform_columns
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...
python
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", "image_transform_columns", "(", "features", ")", ":", "import", "six", "from", "trainer", "import", "feature_transforms", "img_cols", "=", "[", "]", "for", "name", ",", "transform", "in", "six", ".", "iteritems", "(", "features", ")", ":", "if", "tran...
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.
[ "Returns", "a", "list", "of", "columns", "that", "prepare_image_transforms", "()", "should", "run", "on", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L179-L194
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/transform.py
prepare_image_transforms
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...
python
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", "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", ...
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.
[ "Replace", "an", "images", "url", "with", "its", "jpeg", "bytes", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L197-L238
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/transform.py
decode_csv
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 ...
python
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", "decode_csv", "(", "csv_string", ",", "column_names", ")", ":", "import", "csv", "r", "=", "next", "(", "csv", ".", "reader", "(", "[", "csv_string", "]", ")", ")", "if", "len", "(", "r", ")", "!=", "len", "(", "column_names", ")", ":", "rai...
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 ''.
[ "Parse", "a", "csv", "line", "into", "a", "dict", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L355-L370
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/transform.py
encode_csv
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...
python
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", "encode_csv", "(", "data_dict", ",", "column_names", ")", ":", "import", "csv", "import", "six", "values", "=", "[", "str", "(", "data_dict", "[", "x", "]", ")", "for", "x", "in", "column_names", "]", "str_buff", "=", "six", ".", "StringIO", "("...
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
[ "Builds", "a", "csv", "string", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L373-L389
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/transform.py
serialize_example
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...
python
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", "serialize_example", "(", "transformed_json_data", ",", "info_dict", ")", ":", "import", "six", "import", "tensorflow", "as", "tf", "def", "_make_int64_list", "(", "x", ")", ":", "return", "tf", ".", "train", ".", "Feature", "(", "int64_list", "=", "t...
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.
[ "Makes", "a", "serialized", "tf", ".", "example", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L392-L428
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/transform.py
preprocess
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...
python
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", "preprocess", "(", "pipeline", ",", "args", ")", ":", "from", "tensorflow", ".", "python", ".", "lib", ".", "io", "import", "file_io", "from", "trainer", "import", "feature_transforms", "schema", "=", "json", ".", "loads", "(", "file_io", ".", "read...
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 matches the serving csv that a trained mode...
[ "Transfrom", "csv", "data", "into", "transfromed", "tf", ".", "example", "files", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L431-L506
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/transform.py
main
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...
python
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", "main", "(", "argv", "=", "None", ")", ":", "args", "=", "parse_arguments", "(", "sys", ".", "argv", "if", "argv", "is", "None", "else", "argv", ")", "temp_dir", "=", "os", ".", "path", ".", "join", "(", "args", ".", "output", ",", "'tmp'", ...
Run Preprocessing as a Dataflow.
[ "Run", "Preprocessing", "as", "a", "Dataflow", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L509-L545
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/transform.py
TransformFeaturesDoFn.start_bundle
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 = (...
python
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", "start_bundle", "(", "self", ",", "element", "=", "None", ")", ":", "import", "tensorflow", "as", "tf", "from", "trainer", "import", "feature_transforms", "g", "=", "tf", ".", "Graph", "(", ")", "session", "=", "tf", ".", "Session", "(", "graph", ...
Build the transfromation graph once.
[ "Build", "the", "transfromation", "graph", "once", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L278-L299
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/transform.py
TransformFeaturesDoFn.process
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...
python
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", "process", "(", "self", ",", "element", ")", ":", "import", "apache_beam", "as", "beam", "import", "six", "import", "tensorflow", "as", "tf", "# This function is invoked by a separate sub-process so setting the logging level", "# does not affect Datalab's kernel process....
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.
[ "Run", "the", "transformation", "graph", "on", "batched", "input", "data" ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/transform.py#L304-L352
googledatalab/pydatalab
google/datalab/bigquery/_parser.py
Parser.parse_row
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...
python
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", "parse_row", "(", "schema", ",", "data", ")", ":", "def", "parse_value", "(", "data_type", ",", "value", ")", ":", "\"\"\"Parses a value returned from a BigQuery response.\n\n Args:\n data_type: the type of the value as specified by the schema.\n value: the ...
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.
[ "Parses", "a", "row", "from", "query", "results", "into", "an", "equivalent", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_parser.py#L31-L89
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_local_predict.py
_tf_load_model
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...
python
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_load_model", "(", "sess", ",", "model_dir", ")", ":", "meta_graph_pb", "=", "tf", ".", "saved_model", ".", "loader", ".", "load", "(", "sess", "=", "sess", ",", "tags", "=", "[", "tf", ".", "saved_model", ".", "tag_constants", ".", "SERVING",...
Load a tf model from model_dir, and return input/output alias maps.
[ "Load", "a", "tf", "model", "from", "model_dir", "and", "return", "input", "/", "output", "alias", "maps", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L39-L53
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_local_predict.py
_tf_predict
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...
python
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", "_tf_predict", "(", "model_dir", ",", "input_csvlines", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ",", "tf", ".", "Session", "(", ")", "as", "sess", ":", "input_alias_map", ",", "output_alias_map", "=", "_tf_load...
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 in input_csvlines.
[ "Prediction", "with", "a", "tf", "savedmodel", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L56-L87
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_local_predict.py
_download_images
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. ...
python
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", "_download_images", "(", "data", ",", "img_cols", ")", ":", "images", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "d", "in", "data", ":", "for", "img_col", "in", "img_cols", ":", "if", "d", ".", "get", "(", "img_col", ",", ...
Download images given image columns.
[ "Download", "images", "given", "image", "columns", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L90-L108
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_local_predict.py
_get_predicton_csv_lines
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...
python
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_predicton_csv_lines", "(", "data", ",", "headers", ",", "images", ")", ":", "if", "images", ":", "data", "=", "copy", ".", "deepcopy", "(", "data", ")", "for", "img_col", "in", "images", ":", "for", "d", ",", "im", "in", "zip", "(", "dat...
Create CSV lines from list-of-dict data.
[ "Create", "CSV", "lines", "from", "list", "-", "of", "-", "dict", "data", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L111-L135
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_local_predict.py
_get_display_data_with_images
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'] ...
python
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_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"...
Create display data by converting image urls to base64 strings.
[ "Create", "display", "data", "by", "converting", "image", "urls", "to", "base64", "strings", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L138-L157
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_local_predict.py
get_model_schema_and_features
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(...
python
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_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_...
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).
[ "Get", "a", "local", "model", "s", "schema", "and", "features", "config", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L160-L172
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_local_predict.py
get_prediction_results
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...
python
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_prediction_results", "(", "model_dir_or_id", ",", "data", ",", "headers", ",", "img_cols", "=", "None", ",", "cloud", "=", "False", ",", "with_source", "=", "True", ",", "show_image", "=", "True", ")", ":", "if", "img_cols", "is", "None", ":", ...
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 in Datalab. Args: model_dir_or_id: The model directory if cloud is False, or model.version if cloud is True. data: Can be a list of dictionaries, ...
[ "Predict", "with", "a", "specified", "model", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L175-L239
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_local_predict.py
get_probs_for_labels
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':...
python
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", "get_probs_for_labels", "(", "labels", ",", "prediction_results", ")", ":", "probs", "=", "[", "]", "if", "'probability'", "in", "prediction_results", ":", "# 'probability' exists so top-n is set to none zero, and results are like", "# \"predicted, predicted_2,...,probabil...
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': 0.9, 'predicted_2': 'daisy', 'probability_2': 0.01}, .....
[ "Given", "ML", "Workbench", "prediction", "results", "get", "probs", "of", "each", "label", "for", "each", "instance", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L242-L297
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_local_predict.py
local_batch_predict
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_'. ...
python
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", "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_matchi...
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_'. Args: model_dir: The model directory containing a SavedModel (usually saved_model.pb). csv_fil...
[ "Batch", "Predict", "with", "a", "specified", "model", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_local_predict.py#L359-L397
googledatalab/pydatalab
google/datalab/ml/_job.py
Job._refresh_state
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')
python
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", "_refresh_state", "(", "self", ")", ":", "self", ".", "_info", "=", "self", ".", "_api", ".", "projects", "(", ")", ".", "jobs", "(", ")", ".", "get", "(", "name", "=", "self", ".", "_name", ")", ".", "execute", "(", ")", "self", ".", "_...
Refresh the job info.
[ "Refresh", "the", "job", "info", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_job.py#L44-L49
googledatalab/pydatalab
google/datalab/ml/_job.py
Job.submit_training
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': '...
python
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_training", "(", "job_request", ",", "job_id", "=", "None", ")", ":", "new_job_request", "=", "dict", "(", "job_request", ")", "# convert job_args from dict to list as service required.", "if", "'args'", "in", "job_request", "and", "isinstance", "(", "jo...
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': 'BASIC', 'region': 'us-central1', ...
[ "Submit", "a", "training", "job", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_job.py#L62-L116
googledatalab/pydatalab
google/datalab/ml/_job.py
Job.submit_batch_prediction
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', ...
python
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", "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'", ...
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', 'input_paths': ['gs://my_bucket/my_file.csv'], ...
[ "Submit", "a", "batch", "prediction", "job", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_job.py#L119-L151
googledatalab/pydatalab
solutionbox/ml_workbench/xgboost/analyze.py
parse_arguments
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...
python
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", "parse_arguments", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ",", "description", "=", "textwrap", ".", "dedent", "(", "\"\"\"\\\n Runs analysis ...
Parse command line arguments. Args: argv: list of command line arguments, including program name. Returns: An argparse Namespace object. Raises: ValueError: for bad parameters
[ "Parse", "command", "line", "arguments", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/xgboost/analyze.py#L32-L170
googledatalab/pydatalab
solutionbox/ml_workbench/xgboost/analyze.py
run_cloud_analysis
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...
python
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", "run_cloud_analysis", "(", "output_dir", ",", "csv_file_pattern", ",", "bigquery_table", ",", "schema", ",", "features", ")", ":", "def", "_execute_sql", "(", "sql", ",", "table", ")", ":", "\"\"\"Runs a BigQuery job and dowloads the results into local memeory.\n\n...
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 wildcards bigquery_table: project_id.dataset_name.table_name schema: schema list features: features confi...
[ "Use", "BigQuery", "to", "analyze", "input", "date", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/xgboost/analyze.py#L173-L307
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py
inception_v3_base
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...
python
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_base", "(", "inputs", ",", "final_endpoint", "=", "'Mixed_7c'", ",", "min_depth", "=", "16", ",", "depth_multiplier", "=", "1.0", ",", "scope", "=", "None", ")", ":", "# end_points will collect relevant activations for external use, for example", "#...
Inception model from http://arxiv.org/abs/1512.00567. Constructs an Inception v3 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Mixed_7c. Note that the names of the layers in the paper do not correspond to the names of the endpoints reg...
[ "Inception", "model", "from", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1512", ".", "00567", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py#L32-L439
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py
inception_v3
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, ...
python
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", "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",...
Inception model from http://arxiv.org/abs/1512.00567. "Rethinking the Inception Architecture for Computer Vision" Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, Zbigniew Wojna. With the default arguments this method constructs the exact model defined in the paper. However, one can exp...
[ "Inception", "model", "from", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1512", ".", "00567", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py#L442-L550
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py
_reduced_kernel_size_for_small_input
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...
python
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", "_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", "]", ...
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 tensor of size [batch_size, height, width, channels]. kernel_size: desired ...
[ "Define", "kernel", "size", "which", "is", "automatically", "reduced", "for", "small", "input", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py#L556-L584
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py
inception_v3_arg_scope
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...
python
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", "inception_v3_arg_scope", "(", "weight_decay", "=", "0.00004", ",", "stddev", "=", "0.1", ",", "batch_norm_var_collection", "=", "'moving_vars'", ")", ":", "batch_norm_params", "=", "{", "# Decay for the moving averages.", "'decay'", ":", "0.9997", ",", "# epsi...
Defines the default InceptionV3 arg scope. Args: weight_decay: The weight decay to use for regularizing the model. stddev: The standard deviation of the trunctated normal weight initializer. batch_norm_var_collection: The name of the collection for the batch norm variables. Returns: An `arg_...
[ "Defines", "the", "default", "InceptionV3", "arg", "scope", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_inceptionlib.py#L587-L624
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_local.py
Local.preprocess
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...
python
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", "preprocess", "(", "train_dataset", ",", "output_dir", ",", "eval_dataset", ",", "checkpoint", ")", ":", "import", "apache_beam", "as", "beam", "from", "google", ".", "datalab", ".", "utils", "import", "LambdaJob", "from", ".", "import", "_preprocess", ...
Preprocess data locally.
[ "Preprocess", "data", "locally", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_local.py#L32-L51
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_local.py
Local.train
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) ...
python
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", "train", "(", "input_dir", ",", "batch_size", ",", "max_steps", ",", "output_dir", ",", "checkpoint", ")", ":", "from", "google", ".", "datalab", ".", "utils", "import", "LambdaJob", "if", "checkpoint", "is", "None", ":", "checkpoint", "=", "_util", ...
Train model locally.
[ "Train", "model", "locally", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_local.py#L54-L67
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_local.py
Local.predict
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...
python
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", "predict", "(", "model_dir", ",", "image_files", ",", "resize", ",", "show_image", ")", ":", "from", ".", "import", "_predictor", "images", "=", "_util", ".", "load_images", "(", "image_files", ",", "resize", "=", "resize", ")", "labels_and_scores", "...
Predict using an model in a local or GCS directory.
[ "Predict", "using", "an", "model", "in", "a", "local", "or", "GCS", "directory", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_local.py#L70-L79
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_local.py
Local.batch_predict
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...
python
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", "batch_predict", "(", "dataset", ",", "model_dir", ",", "output_csv", ",", "output_bq_table", ")", ":", "import", "apache_beam", "as", "beam", "from", "google", ".", "datalab", ".", "utils", "import", "LambdaJob", "from", ".", "import", "_predictor", "i...
Batch predict running locally.
[ "Batch", "predict", "running", "locally", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_local.py#L82-L103
googledatalab/pydatalab
datalab/utils/_job.py
Job.result
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
python
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", "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. Returns: The result for the Job. Raises: An exception if the Job resulted in an exception.
[ "Get", "the", "result", "for", "a", "job", ".", "This", "will", "block", "if", "the", "job", "is", "incomplete", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_job.py#L119-L132
googledatalab/pydatalab
datalab/utils/_job.py
Job._refresh_state
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...
python
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", "_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...
Get the state of a job. Must be overridden by derived Job classes for Jobs that don't use a Future.
[ "Get", "the", "state", "of", "a", "job", ".", "Must", "be", "overridden", "by", "derived", "Job", "classes", "for", "Jobs", "that", "don", "t", "use", "a", "Future", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_job.py#L151-L169
googledatalab/pydatalab
datalab/utils/_job.py
Job.wait
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...
python
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", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "_future", ":", "try", ":", "# Future.exception() will return rather than raise any exception so we use it.", "self", ".", "_future", ".", "exception", "(", "timeout", ")", "exce...
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
[ "Wait", "for", "the", "job", "to", "complete", "or", "a", "timeout", "to", "happen", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_job.py#L175-L199
googledatalab/pydatalab
datalab/utils/_job.py
Job.state
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...
python
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", "state", "(", "self", ")", ":", "state", "=", "'in progress'", "if", "self", ".", "is_complete", ":", "if", "self", ".", "failed", ":", "state", "=", "'failed with error: %s'", "%", "str", "(", "self", ".", "_fatal_error", ")", "elif", "self", "."...
Describe the state of a Job. Returns: A string describing the job's state.
[ "Describe", "the", "state", "of", "a", "Job", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_job.py#L202-L215
googledatalab/pydatalab
datalab/utils/_job.py
Job.wait_any
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...
python
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_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. 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 completed or None if there were no jobs.
[ "Return", "when", "at", "least", "one", "of", "the", "specified", "jobs", "has", "completed", "or", "timeout", "expires", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_job.py#L257-L267
googledatalab/pydatalab
datalab/utils/_job.py
Job.wait_all
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...
python
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", "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. 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 completed or None if there were no jobs.
[ "Return", "when", "at", "all", "of", "the", "specified", "jobs", "have", "completed", "or", "timeout", "expires", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/_job.py#L270-L279
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_trainer.py
Evaluator.evaluate
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, ...
python
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", "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...
Run one round of evaluation, return loss and accuracy.
[ "Run", "one", "round", "of", "evaluation", "return", "loss", "and", "accuracy", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_trainer.py#L65-L101
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_trainer.py
Trainer.run_training
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: ...
python
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", "run_training", "(", "self", ")", ":", "self", ".", "train_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "output_path", ",", "'train'", ")", "self", ".", "model_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "o...
Runs a Master.
[ "Runs", "a", "Master", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_trainer.py#L120-L230
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_trainer.py
Trainer.log
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...
python
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", "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", "...
Logs training progress.
[ "Logs", "training", "progress", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_trainer.py#L232-L244
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_trainer.py
Trainer.eval
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...
python
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", "eval", "(", "self", ",", "session", ")", ":", "eval_start", "=", "time", ".", "time", "(", ")", "self", ".", "saver", ".", "save", "(", "session", ",", "self", ".", "sv", ".", "save_path", ",", "self", ".", "tensors", ".", "global_step", ")...
Runs evaluation loop.
[ "Runs", "evaluation", "loop", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_trainer.py#L246-L266
googledatalab/pydatalab
google/datalab/ml/_feature_slice_view.py
FeatureSliceView._get_lantern_format
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...
python
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", "_get_lantern_format", "(", "self", ",", "df", ")", ":", "if", "(", "'count'", "not", "in", "df", ")", "or", "(", "'feature'", "not", "in", "df", ")", ":", "raise", "Exception", "(", "'No \"count\" or \"feature\" found in data.'", ")", "if", "len", ...
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 function converts a DataFrame to such format...
[ "Feature", "slice", "view", "browser", "expects", "data", "in", "the", "format", "of", ":", "{", "metricValues", ":", "{", "count", ":", "12", "accuracy", ":", "1", ".", "0", "}", "feature", ":", "species", ":", "Iris", "-", "setosa", "}", "{", "metr...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_feature_slice_view.py#L24-L44
googledatalab/pydatalab
google/datalab/ml/_feature_slice_view.py
FeatureSliceView.plot
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: ...
python
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", "plot", "(", "self", ",", "data", ")", ":", "import", "IPython", "if", "(", "(", "sys", ".", "version_info", ".", "major", ">", "2", "and", "isinstance", "(", "data", ",", "str", ")", ")", "or", "(", "sys", ".", "version_info", ".", "major",...
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: "feature": identifies a s...
[ "Plots", "a", "featire", "slice", "view", "on", "given", "data", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_feature_slice_view.py#L46-L88
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py
parse_arguments
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...
python
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_arguments", "(", "argv", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Runs Preprocessing on structured data.'", ")", "parser", ".", "add_argument", "(", "'--output-dir'", ",", "type", "=", "str", ",", "requir...
Parse command line arguments. Args: argv: list of command line arguments, includeing programe name. Returns: An argparse Namespace object. Raises: ValueError: for bad parameters
[ "Parse", "command", "line", "arguments", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py#L33-L88
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py
parse_table_name
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: ...
python
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", "parse_table_name", "(", "bigquery_table", ")", ":", "id_name", "=", "bigquery_table", ".", "split", "(", "':'", ")", "if", "len", "(", "id_name", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Bigquery table name should be in the form '", "'project_id:...
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 ':'.
[ "Giving", "a", "string", "a", ":", "b", ".", "c", "returns", "b", ".", "c", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py#L91-L108
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py
run_numerical_analysis
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...
python
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_numerical_analysis", "(", "table", ",", "schema_list", ",", "args", ")", ":", "import", "google", ".", "datalab", ".", "bigquery", "as", "bq", "# Get list of numerical columns.", "numerical_columns", "=", "[", "]", "for", "col_schema", "in", "schema_li...
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 args
[ "Find", "min", "/", "max", "values", "for", "the", "numerical", "columns", "and", "writes", "a", "json", "file", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py#L111-L156
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py
run_categorical_analysis
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...
python
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_categorical_analysis", "(", "table", ",", "schema_list", ",", "args", ")", ":", "import", "google", ".", "datalab", ".", "bigquery", "as", "bq", "# Get list of categorical columns.", "categorical_columns", "=", "[", "]", "for", "col_schema", "in", "sch...
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) schema_list: Bigquery schema json object args: the command ...
[ "Find", "vocab", "values", "for", "the", "categorical", "columns", "and", "writes", "a", "csv", "file", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py#L159-L219
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py
run_analysis
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)...
python
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", "run_analysis", "(", "args", ")", ":", "import", "google", ".", "datalab", ".", "bigquery", "as", "bq", "if", "args", ".", "bigquery_table", ":", "table", "=", "bq", ".", "Table", "(", "args", ".", "bigquery_table", ")", "schema_list", "=", "table...
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.
[ "Builds", "an", "analysis", "file", "for", "training", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/preprocess/cloud_preprocess.py#L222-L256
googledatalab/pydatalab
google/datalab/_context.py
Context.set_project_id
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)
python
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", "set_project_id", "(", "self", ",", "project_id", ")", ":", "self", ".", "_project_id", "=", "project_id", "if", "self", "==", "Context", ".", "_global_context", ":", "du", ".", "save_project_id", "(", "self", ".", "_project_id", ")" ]
Set the project_id for the context.
[ "Set", "the", "project_id", "for", "the", "context", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/_context.py#L66-L70
googledatalab/pydatalab
google/datalab/_context.py
Context.default
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...
python
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", "default", "(", ")", ":", "credentials", "=", "du", ".", "get_credentials", "(", ")", "project", "=", "du", ".", "get_default_project_id", "(", ")", "if", "Context", ".", "_global_context", "is", "None", ":", "config", "=", "Context", ".", "_get_def...
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 called. Returns: ...
[ "Retrieves", "a", "default", "Context", "object", "creating", "it", "if", "necessary", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/_context.py#L102-L124
googledatalab/pydatalab
google/datalab/ml/_confusion_matrix.py
ConfusionMatrix.from_csv
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...
python
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...
[ "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", ".", "ope...
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 containing BigQuery schema. Used if "headers" is None. I...
[ "Create", "a", "ConfusionMatrix", "from", "a", "csv", "file", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_confusion_matrix.py#L41-L77