code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def fetch_pr_labels():
"""
Returns the labels associated with the current pull request.
"""
if "GITHUB_ACTIONS" not in os.environ:
return None
if os.environ.get("GITHUB_EVENT_NAME") != "pull_request":
return None
with open(os.environ["GITHUB_EVENT_PATH"]) as f:
pr_data ... |
Returns the labels associated with the current pull request.
| fetch_pr_labels | python | mlflow/mlflow | conftest.py | https://github.com/mlflow/mlflow/blob/master/conftest.py | Apache-2.0 |
def clean_up_envs():
"""
Clean up virtualenvs and conda environments created during tests to save disk space.
"""
yield
if "GITHUB_ACTIONS" in os.environ:
from mlflow.utils.virtualenv import _get_mlflow_virtualenv_root
shutil.rmtree(_get_mlflow_virtualenv_root(), ignore_errors=True... |
Clean up virtualenvs and conda environments created during tests to save disk space.
| clean_up_envs | python | mlflow/mlflow | conftest.py | https://github.com/mlflow/mlflow/blob/master/conftest.py | Apache-2.0 |
def serve_wheel(request, tmp_path_factory):
"""
Models logged during tests have a dependency on the dev version of MLflow built from
source (e.g., mlflow==1.20.0.dev0) and cannot be served because the dev version is not
available on PyPI. This fixture serves a wheel for the dev version from a temporary
... |
Models logged during tests have a dependency on the dev version of MLflow built from
source (e.g., mlflow==1.20.0.dev0) and cannot be served because the dev version is not
available on PyPI. This fixture serves a wheel for the dev version from a temporary
PyPI repository running on localhost and append... | serve_wheel | python | mlflow/mlflow | conftest.py | https://github.com/mlflow/mlflow/blob/master/conftest.py | Apache-2.0 |
def fetch_patch_prs(version):
"""
Fetch PRs labeled with `v{version}` from the MLflow repository.
"""
label = f"v{version}"
per_page = 100
page = 1
pulls = []
while True:
response = requests.get(
f'https://api.github.com/search/issues?q=is:pr+repo:mlflow/mlflow+label:... |
Fetch PRs labeled with `v{version}` from the MLflow repository.
| fetch_patch_prs | python | mlflow/mlflow | dev/check_patch_prs.py | https://github.com/mlflow/mlflow/blob/master/dev/check_patch_prs.py | Apache-2.0 |
def build_protoc_from_source(version):
"""
Build and install protoc from source for macOS arm64 version 3.19.4 only.
"""
assert (
platform.system() == "Darwin"
and platform.machine() == "arm64"
and Version(version) < Version("26")
), "This function is intended for macOS arm64... |
Build and install protoc from source for macOS arm64 version 3.19.4 only.
| build_protoc_from_source | python | mlflow/mlflow | dev/generate_protos.py | https://github.com/mlflow/mlflow/blob/master/dev/generate_protos.py | Apache-2.0 |
def download_file(url, output_path):
"""
Download a file using wget on Linux and curl on macOS.
"""
if platform.system() == "Darwin":
subprocess.check_call(
[
"curl",
"-L",
url,
"-o",
output_path,
... |
Download a file using wget on Linux and curl on macOS.
| download_file | python | mlflow/mlflow | dev/generate_protos.py | https://github.com/mlflow/mlflow/blob/master/dev/generate_protos.py | Apache-2.0 |
def download_and_extract_protoc(version):
"""
Download and extract specific version protoc tool, return extracted protoc executable file path
and include path.
"""
assert platform.system() in [
"Darwin",
"Linux",
], "The script only supports MacOS or Linux system."
assert pla... |
Download and extract specific version protoc tool, return extracted protoc executable file path
and include path.
| download_and_extract_protoc | python | mlflow/mlflow | dev/generate_protos.py | https://github.com/mlflow/mlflow/blob/master/dev/generate_protos.py | Apache-2.0 |
def create_pom_with_pinned_scala_version(pom_file_path: str, scala_version: str) -> str:
"""
Creates a new pom.xml file with the given scala version.
Args:
pom_file_path: Path to the original pom.xml file.
scala_version: Scala version to pin to.
Returns:
Path to the new pom.xml... |
Creates a new pom.xml file with the given scala version.
Args:
pom_file_path: Path to the original pom.xml file.
scala_version: Scala version to pin to.
Returns:
Path to the new pom.xml file.
| create_pom_with_pinned_scala_version | python | mlflow/mlflow | dev/set-mlflow-spark-scala-version.py | https://github.com/mlflow/mlflow/blob/master/dev/set-mlflow-spark-scala-version.py | Apache-2.0 |
def get_latest_micro_versions(versions):
"""
Returns the latest micro version in each minor version.
"""
seen = set()
latest_micro_versions = []
for ver in sorted(versions, reverse=True):
major_and_minor = ver.release[:2]
if major_and_minor not in seen:
seen.add(major... |
Returns the latest micro version in each minor version.
| get_latest_micro_versions | python | mlflow/mlflow | dev/set_matrix.py | https://github.com/mlflow/mlflow/blob/master/dev/set_matrix.py | Apache-2.0 |
def filter_versions(
flavor: str,
versions: list[Version],
min_ver: Version,
max_ver: Version,
unsupported: list[SpecifierSet],
allow_unreleased_max_version: bool = False,
):
"""
Returns the versions that satisfy the following conditions:
1. Newer than or equal to `min_ver`.
2. O... |
Returns the versions that satisfy the following conditions:
1. Newer than or equal to `min_ver`.
2. Older than or equal to `max_ver.major`.
3. Not in `unsupported`.
| filter_versions | python | mlflow/mlflow | dev/set_matrix.py | https://github.com/mlflow/mlflow/blob/master/dev/set_matrix.py | Apache-2.0 |
def get_changed_flavors(changed_files, flavors):
"""
Detects changed flavors from a list of changed files.
"""
changed_flavors = set()
for f in changed_files:
match = FLAVOR_FILE_PATTERN.match(f)
if match and match.group(2) in flavors:
changed_flavors.add(match.group(2))
... |
Detects changed flavors from a list of changed files.
| get_changed_flavors | python | mlflow/mlflow | dev/set_matrix.py | https://github.com/mlflow/mlflow/blob/master/dev/set_matrix.py | Apache-2.0 |
def infer_python_version(package: str, version: str) -> str:
"""
Infer the minimum Python version required by the package.
"""
candidates = ("3.10",)
if rp := _requires_python(package, version):
spec = SpecifierSet(rp)
return next(filter(spec.contains, candidates), candidates[0])
... |
Infer the minimum Python version required by the package.
| infer_python_version | python | mlflow/mlflow | dev/set_matrix.py | https://github.com/mlflow/mlflow/blob/master/dev/set_matrix.py | Apache-2.0 |
def _find_matches(spec: dict[str, T], version: str) -> Iterator[T]:
"""
Args:
spec: A dictionary with key as version specifier and value as the corresponding value.
For example, {"< 1.0.0": "numpy<2.0", ">= 1.0.0": "numpy>=2.0"}.
version: The version to match against the specifiers.
... |
Args:
spec: A dictionary with key as version specifier and value as the corresponding value.
For example, {"< 1.0.0": "numpy<2.0", ">= 1.0.0": "numpy>=2.0"}.
version: The version to match against the specifiers.
Returns:
An iterator of values that match the version.
| _find_matches | python | mlflow/mlflow | dev/set_matrix.py | https://github.com/mlflow/mlflow/blob/master/dev/set_matrix.py | Apache-2.0 |
def validate_test_coverage(flavor: str, config: FlavorConfig):
"""
Validate that all test files for the flavor are executed in the cross-version tests.
This is done by parsing `run` commands in the `ml-package-versions.yml` to get the list
of executed test files, and then comparing it with the actual t... |
Validate that all test files for the flavor are executed in the cross-version tests.
This is done by parsing `run` commands in the `ml-package-versions.yml` to get the list
of executed test files, and then comparing it with the actual test files in the directory.
| validate_test_coverage | python | mlflow/mlflow | dev/set_matrix.py | https://github.com/mlflow/mlflow/blob/master/dev/set_matrix.py | Apache-2.0 |
def _get_test_files(test_dir_or_path: str) -> set[Path]:
"""List all test files in the given directory or file path."""
path = Path(test_dir_or_path)
if path.is_dir():
return set(path.rglob("test_*.py"))
if PYTEST_FILE_PATTERN.match(path.name):
return {path}
return set() | List all test files in the given directory or file path. | _get_test_files | python | mlflow/mlflow | dev/set_matrix.py | https://github.com/mlflow/mlflow/blob/master/dev/set_matrix.py | Apache-2.0 |
def validate_requirements(
requirements: dict[str, list[str]],
name: str,
category: str,
package_info: PackageInfo,
versions: list[Version],
) -> None:
"""
Validate that the requirements specified in the config don't contain unused items.
Here's an example of invalid requirements:
`... |
Validate that the requirements specified in the config don't contain unused items.
Here's an example of invalid requirements:
```
sklearn:
package_info:
pip_release: "scikit-learn"
autologging:
minimum: "1.3.0"
maximum: "1.5.0"
requiremen... | validate_requirements | python | mlflow/mlflow | dev/set_matrix.py | https://github.com/mlflow/mlflow/blob/master/dev/set_matrix.py | Apache-2.0 |
def batch_fetch_prs_graphql(pr_numbers: list[int]) -> list[PullRequest]:
"""
Batch fetch PR data using GitHub GraphQL API.
"""
if not pr_numbers:
return []
# GitHub GraphQL has query size limits, so batch in chunks
MAX_PRS_PER_QUERY = 50 # Conservative limit to avoid query size issues
... |
Batch fetch PR data using GitHub GraphQL API.
| batch_fetch_prs_graphql | python | mlflow/mlflow | dev/update_changelog.py | https://github.com/mlflow/mlflow/blob/master/dev/update_changelog.py | Apache-2.0 |
def _fetch_pr_chunk_graphql(pr_numbers: list[int]) -> list[PullRequest]:
"""
Fetch a chunk of PRs using GraphQL.
"""
# Build GraphQL query with aliases for each PR
query_parts = [
"query($owner: String!, $repo: String!) {",
" repository(owner: $owner, name: $repo) {",
]
for... |
Fetch a chunk of PRs using GraphQL.
| _fetch_pr_chunk_graphql | python | mlflow/mlflow | dev/update_changelog.py | https://github.com/mlflow/mlflow/blob/master/dev/update_changelog.py | Apache-2.0 |
def update_versions(new_py_version: str) -> None:
"""
`new_py_version` is either:
- a release version (e.g. "2.1.0")
- a RC version (e.g. "2.1.0rc0")
- a dev version (e.g. "2.1.0.dev0")
"""
old_py_version = get_current_py_version()
replace_python(old_py_version, new_py_version, _P... |
`new_py_version` is either:
- a release version (e.g. "2.1.0")
- a RC version (e.g. "2.1.0rc0")
- a dev version (e.g. "2.1.0.dev0")
| update_versions | python | mlflow/mlflow | dev/update_mlflow_versions.py | https://github.com/mlflow/mlflow/blob/master/dev/update_mlflow_versions.py | Apache-2.0 |
def update_version(src, key, new_version, category, update_max):
"""
Examples
========
>>> src = '''
... sklearn:
... ...
... models:
... minimum: "0.0.0"
... maximum: "0.0.0"
... xgboost:
... ...
... autologging:
... minimum: "1.1.1"
... m... |
Examples
========
>>> src = '''
... sklearn:
... ...
... models:
... minimum: "0.0.0"
... maximum: "0.0.0"
... xgboost:
... ...
... autologging:
... minimum: "1.1.1"
... maximum: "1.1.1"
... '''.strip()
>>> new_src = update_version(src... | update_version | python | mlflow/mlflow | dev/update_ml_package_versions.py | https://github.com/mlflow/mlflow/blob/master/dev/update_ml_package_versions.py | Apache-2.0 |
def _get_autolog_flavor_module_map(config):
"""
Parse _ML_PACKAGE_VERSIONS to get the mapping of flavor name to
the module name to be imported for autologging.
"""
autolog_flavor_module_map = {}
for flavor, config in config.items():
if "autologging" not in config:
continue
... |
Parse _ML_PACKAGE_VERSIONS to get the mapping of flavor name to
the module name to be imported for autologging.
| _get_autolog_flavor_module_map | python | mlflow/mlflow | dev/update_ml_package_versions.py | https://github.com/mlflow/mlflow/blob/master/dev/update_ml_package_versions.py | Apache-2.0 |
def get_min_supported_version(versions_infos: list[VersionInfo]) -> Optional[str]:
"""
Get the minimum version that is released within the past two years
"""
min_support_date = datetime.now() - timedelta(days=2 * 365)
min_support_date = min_support_date.replace(tzinfo=None)
# Extract versions t... |
Get the minimum version that is released within the past two years
| get_min_supported_version | python | mlflow/mlflow | dev/update_ml_package_versions.py | https://github.com/mlflow/mlflow/blob/master/dev/update_ml_package_versions.py | Apache-2.0 |
def ignore_map(code: str) -> dict[str, set[int]]:
"""
Creates a mapping of rule name to line numbers to ignore.
{
"<rule_name>": {<line_number>, ...},
...
}
"""
mapping: dict[str, set[int]] = {}
readline = iter(code.splitlines(True)).__next__
for tok in tokenize.generate... |
Creates a mapping of rule name to line numbers to ignore.
{
"<rule_name>": {<line_number>, ...},
...
}
| ignore_map | python | mlflow/mlflow | dev/clint/src/clint/linter.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/linter.py | Apache-2.0 |
def _iter_md_code_blocks(s: str) -> Iterator[CodeBlock]:
"""
Iterates over code blocks in a Markdown string.
"""
code_block_loc: Location | None = None
code_lines: list[str] = []
closing_fence: str | None = None
line_iter = enumerate(s.splitlines())
while t := next(line_iter, None):
... |
Iterates over code blocks in a Markdown string.
| _iter_md_code_blocks | python | mlflow/mlflow | dev/clint/src/clint/linter.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/linter.py | Apache-2.0 |
def _find_artifact_path_index(call_path: tuple[str, str]) -> int | None:
"""
Finds the index of the `artifact_path` argument in the function signature of `log_model`.
"""
for p in Path(*call_path).rglob("*.py"):
if not p.is_file():
continue
if (idx := _ArtifactPathFinder.par... |
Finds the index of the `artifact_path` argument in the function signature of `log_model`.
| _find_artifact_path_index | python | mlflow/mlflow | dev/clint/src/clint/linter.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/linter.py | Apache-2.0 |
def __init__(
self,
*,
path: Path,
config: Config,
ignore: dict[str, set[int]],
cell: int | None = None,
offset: Location | None = None,
):
"""
Lints a Python file.
Args:
path: Path to the file being linted.
con... |
Lints a Python file.
Args:
path: Path to the file being linted.
config: Linter configuration declared within the pyproject.toml file.
ignore: Mapping of rule name to line numbers to ignore.
cell: Index of the cell being linted in a Jupyter notebook.
... | __init__ | python | mlflow/mlflow | dev/clint/src/clint/linter.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/linter.py | Apache-2.0 |
def _log_model_with_artifact_path(self, node: ast.Call) -> bool:
"""
Returns True if the call looks like `mlflow.<flavor>.log_model(...)` and
the `artifact_path` argument is specified.
"""
parts = self._resolve_call(node)
if len(parts) != 3:
return False
... |
Returns True if the call looks like `mlflow.<flavor>.log_model(...)` and
the `artifact_path` argument is specified.
| _log_model_with_artifact_path | python | mlflow/mlflow | dev/clint/src/clint/linter.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/linter.py | Apache-2.0 |
def _has_trace_ui_content(output: dict[str, Any]) -> bool:
"""Check if an output contains MLflow trace UI content."""
data = output.get("data")
if not data:
return False
# Check only HTML outputs since trace UI content is only added to text/html
html = data.get("text/html")
if not html:... | Check if an output contains MLflow trace UI content. | _has_trace_ui_content | python | mlflow/mlflow | dev/clint/src/clint/linter.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/linter.py | Apache-2.0 |
def _id(self) -> str:
"""
Return a unique identifier for this rule.
""" |
Return a unique identifier for this rule.
| _id | python | mlflow/mlflow | dev/clint/src/clint/rules.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/rules.py | Apache-2.0 |
def _message(self) -> str:
"""
Return a message that explains this rule.
""" |
Return a message that explains this rule.
| _message | python | mlflow/mlflow | dev/clint/src/clint/rules.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/rules.py | Apache-2.0 |
def check(node: ast.AnnAssign) -> bool:
"""
Returns True if the value to assign is `None` but the type annotation is
not `Optional[...]` or `... | None`. For example: `a: int = None`.
"""
return ImplicitOptional._is_none(node.value) and not (
ImplicitOptional._is_opti... |
Returns True if the value to assign is `None` but the type annotation is
not `Optional[...]` or `... | None`. For example: `a: int = None`.
| check | python | mlflow/mlflow | dev/clint/src/clint/rules.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/rules.py | Apache-2.0 |
def _is_optional(ann: ast.AST) -> bool:
"""
Returns True if `ann` looks like `Optional[...]`.
"""
return (
isinstance(ann, ast.Subscript)
and isinstance(ann.value, ast.Name)
and ann.value.id == "Optional"
) |
Returns True if `ann` looks like `Optional[...]`.
| _is_optional | python | mlflow/mlflow | dev/clint/src/clint/rules.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/rules.py | Apache-2.0 |
def _is_bitor_none(ann: ast.AST) -> bool:
"""
Returns True if `ann` looks like `... | None`.
"""
return (
isinstance(ann, ast.BinOp)
and isinstance(ann.op, ast.BitOr)
and (isinstance(ann.right, ast.Constant) and ann.right.value is None)
) |
Returns True if `ann` looks like `... | None`.
| _is_bitor_none | python | mlflow/mlflow | dev/clint/src/clint/rules.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/rules.py | Apache-2.0 |
def check(node: ast.Call) -> bool:
"""
Returns True if `node` looks like `subprocess.Popen(["mlflow", ...])`.
"""
if (
isinstance(node.func, ast.Attribute)
and isinstance(node.func.value, ast.Name)
and (node.func.value.id == "subprocess")
a... |
Returns True if `node` looks like `subprocess.Popen(["mlflow", ...])`.
| check | python | mlflow/mlflow | dev/clint/src/clint/rules.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/rules.py | Apache-2.0 |
def check(node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
"""
Returns True if the function has @pytest.mark.repeat decorator.
"""
for decorator in node.decorator_list:
if PytestMarkRepeat._is_pytest_mark_repeat(decorator):
return True
return Fal... |
Returns True if the function has @pytest.mark.repeat decorator.
| check | python | mlflow/mlflow | dev/clint/src/clint/rules.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/rules.py | Apache-2.0 |
def _is_pytest_mark_repeat(decorator: ast.AST) -> bool:
"""
Check if a decorator is @pytest.mark.repeat in any form:
- pytest.mark.repeat
- pytest.mark.repeat(n)
"""
# Handle direct call like @pytest.mark.repeat(10)
if isinstance(decorator, ast.Call):
... |
Check if a decorator is @pytest.mark.repeat in any form:
- pytest.mark.repeat
- pytest.mark.repeat(n)
| _is_pytest_mark_repeat | python | mlflow/mlflow | dev/clint/src/clint/rules.py | https://github.com/mlflow/mlflow/blob/master/dev/clint/src/clint/rules.py | Apache-2.0 |
def process_method(method_descriptor, state):
"""
Given a method descriptor, add information being referenced into the GenerateSchemaState.
"""
if not method_descriptor.GetOptions().HasExtension(databricks_pb2.graphql):
return
rpcOptions = method_descriptor.GetOptions().Extensions[databricks... |
Given a method descriptor, add information being referenced into the GenerateSchemaState.
| process_method | python | mlflow/mlflow | dev/proto_to_graphql/parsing_utils.py | https://github.com/mlflow/mlflow/blob/master/dev/proto_to_graphql/parsing_utils.py | Apache-2.0 |
def populate_message_types(field_descriptor, state, is_input, visited):
"""
Given a field descriptor, recursively walk through the referenced message types and add
information being referenced into the GenerateSchemaState.
"""
if field_descriptor in visited:
# Break the loop for recursive ty... |
Given a field descriptor, recursively walk through the referenced message types and add
information being referenced into the GenerateSchemaState.
| populate_message_types | python | mlflow/mlflow | dev/proto_to_graphql/parsing_utils.py | https://github.com/mlflow/mlflow/blob/master/dev/proto_to_graphql/parsing_utils.py | Apache-2.0 |
def _get_reference_map():
"""
Sphinx computes references for type annotations using fully-qualified classnames,
so references in undocumented modules (even if the referenced object is exposed via
a different module from the one it's defined in) are considered invalid by Sphinx.
Example:
```
... |
Sphinx computes references for type annotations using fully-qualified classnames,
so references in undocumented modules (even if the referenced object is exposed via
a different module from the one it's defined in) are considered invalid by Sphinx.
Example:
```
def start_run(...) -> ActiveRun:... | _get_reference_map | python | mlflow/mlflow | docs/api_reference/source/conf.py | https://github.com/mlflow/mlflow/blob/master/docs/api_reference/source/conf.py | Apache-2.0 |
def _func(): # <- obj_line
""" <- obj_line + offset
Docstring <- obj_line + offset + extra_offset
.. code-block:: <- obj_line + offset + extra_offset + lineno_in_docstring
:test:
...
""" | <- obj_line + offset
Docstring <- obj_line + offset + extra_offset
.. code-block:: <- obj_line + offset + extra_offset + lineno_in_docstring
:test:
...
| _func | python | mlflow/mlflow | docs/api_reference/source/testcode_block.py | https://github.com/mlflow/mlflow/blob/master/docs/api_reference/source/testcode_block.py | Apache-2.0 |
def generate_data(location_data, start_dt) -> pd.DataFrame:
"""
Synthetic data generation utility to take a real data set and generate a 'stacked'
representation that can be grouped by identifying keys within columns.
Here we are taking a list of tuples as location data [(country, city)] and applying
... |
Synthetic data generation utility to take a real data set and generate a 'stacked'
representation that can be grouped by identifying keys within columns.
Here we are taking a list of tuples as location data [(country, city)] and applying
a random factor to each copy of the underlying series to generate... | generate_data | python | mlflow/mlflow | examples/diviner/train.py | https://github.com/mlflow/mlflow/blob/master/examples/diviner/train.py | Apache-2.0 |
def prediction_target_scatter(eval_df, _builtin_metrics, artifacts_dir):
"""
This example custom artifact generates and saves a scatter plot to ``artifacts_dir`` that
visualizes the relationship between the predictions and targets for the given model to a
file as an image artifact.
"""
plt.scatt... |
This example custom artifact generates and saves a scatter plot to ``artifacts_dir`` that
visualizes the relationship between the predictions and targets for the given model to a
file as an image artifact.
| prediction_target_scatter | python | mlflow/mlflow | examples/evaluation/evaluate_with_custom_metrics.py | https://github.com/mlflow/mlflow/blob/master/examples/evaluation/evaluate_with_custom_metrics.py | Apache-2.0 |
def predict(
self,
input,
params: Optional[dict[str, Any]] = None,
):
"""
Generate predictions for the data.
Args:
input: pandas.DataFrame with one column containing images to be scored. The image
column must contain base64 encoded binary ... |
Generate predictions for the data.
Args:
input: pandas.DataFrame with one column containing images to be scored. The image
column must contain base64 encoded binary content of the image files. The image
format must be supported by PIL (e.g. jpeg or png).
... | predict | python | mlflow/mlflow | examples/flower_classifier/image_pyfunc.py | https://github.com/mlflow/mlflow/blob/master/examples/flower_classifier/image_pyfunc.py | Apache-2.0 |
def _predict_images(self, images):
"""
Generate predictions for input images.
Args:
images: Binary image data.
Returns:
Predicted probabilities for each class.
"""
def preprocess_f(z):
return decode_and_resize_image(z, self._image_di... |
Generate predictions for input images.
Args:
images: Binary image data.
Returns:
Predicted probabilities for each class.
| _predict_images | python | mlflow/mlflow | examples/flower_classifier/image_pyfunc.py | https://github.com/mlflow/mlflow/blob/master/examples/flower_classifier/image_pyfunc.py | Apache-2.0 |
def log_model(keras_model, signature, artifact_path, image_dims, domain):
"""
Log a KerasImageClassifierPyfunc model as an MLflow artifact for the current run.
Args:
keras_model: Keras model to be saved.
signature: Model signature.
artifact_path: Run-relative artifact path this mode... |
Log a KerasImageClassifierPyfunc model as an MLflow artifact for the current run.
Args:
keras_model: Keras model to be saved.
signature: Model signature.
artifact_path: Run-relative artifact path this model is to be saved to.
image_dims: Image dimensions the Keras model expects... | log_model | python | mlflow/mlflow | examples/flower_classifier/image_pyfunc.py | https://github.com/mlflow/mlflow/blob/master/examples/flower_classifier/image_pyfunc.py | Apache-2.0 |
def score_model(path, host, port):
"""
Score images on the local path with MLflow model deployed at given uri and port.
Args:
path: Path to a single image file or a directory of images.
host: Host the model is deployed at.
port: Port the model is deployed at.
Returns:
S... |
Score images on the local path with MLflow model deployed at given uri and port.
Args:
path: Path to a single image file or a directory of images.
host: Host the model is deployed at.
port: Port the model is deployed at.
Returns:
Server response.
| score_model | python | mlflow/mlflow | examples/flower_classifier/score_images_rest.py | https://github.com/mlflow/mlflow/blob/master/examples/flower_classifier/score_images_rest.py | Apache-2.0 |
def on_epoch_end(self, epoch, logs=None):
"""
Log Keras metrics with MLflow. Update the best model if the model improved on the validation
data.
"""
if not logs:
return
for name, value in logs.items():
name = "valid_" + name[4:] if name.startswith(... |
Log Keras metrics with MLflow. Update the best model if the model improved on the validation
data.
| on_epoch_end | python | mlflow/mlflow | examples/flower_classifier/train.py | https://github.com/mlflow/mlflow/blob/master/examples/flower_classifier/train.py | Apache-2.0 |
def on_train_end(self, *args, **kwargs):
"""
Log the best model with MLflow and evaluate it on the train and validation data so that the
metrics stored with MLflow reflect the logged model.
"""
self._model.set_weights(self._best_weights)
x, y = self._train
train_r... |
Log the best model with MLflow and evaluate it on the train and validation data so that the
metrics stored with MLflow reflect the logged model.
| on_train_end | python | mlflow/mlflow | examples/flower_classifier/train.py | https://github.com/mlflow/mlflow/blob/master/examples/flower_classifier/train.py | Apache-2.0 |
def train(
image_files,
labels,
domain,
image_width=224,
image_height=224,
epochs=1,
batch_size=16,
test_ratio=0.2,
seed=None,
):
"""
Train VGG16 model on provided image files. This will create a new MLflow run and log all
parameters, metrics and the resulting model with ... |
Train VGG16 model on provided image files. This will create a new MLflow run and log all
parameters, metrics and the resulting model with MLflow. The resulting model is an instance
of KerasImageClassifierPyfunc - a custom python function model that embeds all necessary
preprocessing together with the V... | train | python | mlflow/mlflow | examples/flower_classifier/train.py | https://github.com/mlflow/mlflow/blob/master/examples/flower_classifier/train.py | Apache-2.0 |
def new_eval( # noqa: D417
nepochs, experiment_id, null_train_loss, null_valid_loss, null_test_loss, return_all=False
):
"""
Create a new eval function
Args:
nepochs: Number of epochs to train the model.
experiment_id: Experiment id for the training run.
... |
Create a new eval function
Args:
nepochs: Number of epochs to train the model.
experiment_id: Experiment id for the training run.
null_train_loss: Loss of a null model on the training dataset.
null_valid_loss: Loss of a null model on the validation datas... | new_eval | python | mlflow/mlflow | examples/hyperparam/search_hyperopt.py | https://github.com/mlflow/mlflow/blob/master/examples/hyperparam/search_hyperopt.py | Apache-2.0 |
def eval(params):
"""
Train Keras model with given parameters by invoking MLflow run.
Notice we store runUuid and resulting metric in a file. We will later use these to pick
the best run and to log the runUuids of the child runs as an artifact. This is a
temp... |
Train Keras model with given parameters by invoking MLflow run.
Notice we store runUuid and resulting metric in a file. We will later use these to pick
the best run and to log the runUuids of the child runs as an artifact. This is a
temporary workaround until MLflow off... | eval | python | mlflow/mlflow | examples/hyperparam/search_hyperopt.py | https://github.com/mlflow/mlflow/blob/master/examples/hyperparam/search_hyperopt.py | Apache-2.0 |
def __exit__(self, exc_type, exc_val, exc_tb):
"""
Log the best model at the end of the training run.
"""
if not self._best_model:
raise Exception("Failed to build any model")
mlflow.log_metric(self.train_loss, self._best_train_loss, step=self._next_step)
mlfl... |
Log the best model at the end of the training run.
| __exit__ | python | mlflow/mlflow | examples/hyperparam/train.py | https://github.com/mlflow/mlflow/blob/master/examples/hyperparam/train.py | Apache-2.0 |
def on_epoch_end(self, epoch, logs=None):
"""
Log Keras metrics with MLflow. If model improved on the validation data, evaluate it on
a test set and store it as the best model.
"""
if not logs:
return
self._next_step = epoch + 1
train_loss = logs["loss... |
Log Keras metrics with MLflow. If model improved on the validation data, evaluate it on
a test set and store it as the best model.
| on_epoch_end | python | mlflow/mlflow | examples/hyperparam/train.py | https://github.com/mlflow/mlflow/blob/master/examples/hyperparam/train.py | Apache-2.0 |
def yield_artifacts(run_id, path=None):
"""Yield all artifacts in the specified run"""
client = MlflowClient()
for item in client.list_artifacts(run_id, path):
if item.is_dir:
yield from yield_artifacts(run_id, item.path)
else:
yield item.path | Yield all artifacts in the specified run | yield_artifacts | python | mlflow/mlflow | examples/lightgbm/lightgbm_sklearn/utils.py | https://github.com/mlflow/mlflow/blob/master/examples/lightgbm/lightgbm_sklearn/utils.py | Apache-2.0 |
def fetch_logged_data(run_id):
"""Fetch params, metrics, tags, and artifacts in the specified run"""
client = MlflowClient()
data = client.get_run(run_id).data
# Exclude system tags: https://www.mlflow.org/docs/latest/tracking.html#system-tags
tags = {k: v for k, v in data.tags.items() if not k.star... | Fetch params, metrics, tags, and artifacts in the specified run | fetch_logged_data | python | mlflow/mlflow | examples/lightgbm/lightgbm_sklearn/utils.py | https://github.com/mlflow/mlflow/blob/master/examples/lightgbm/lightgbm_sklearn/utils.py | Apache-2.0 |
async def route_retrieval(
self, ctx: Context, ev: StartEvent
) -> VectorSearchRetrieveEvent | BM25RetrieveEvent | TransformQueryEvent | QueryEvent | None:
"""Route query to the retrieval steps based on the model config."""
query = ev.get("query")
if query is None:
retur... | Route query to the retrieval steps based on the model config. | route_retrieval | python | mlflow/mlflow | examples/llama_index/workflow/workflow/workflow.py | https://github.com/mlflow/mlflow/blob/master/examples/llama_index/workflow/workflow/workflow.py | Apache-2.0 |
async def query_vector_store(self, ev: VectorSearchRetrieveEvent) -> RetrievalResultEvent:
"""Perform retrieval using the vector store."""
nodes = self.vs_retriever.retrieve(ev.query)
return RetrievalResultEvent(nodes=nodes, retriever="vector_search") | Perform retrieval using the vector store. | query_vector_store | python | mlflow/mlflow | examples/llama_index/workflow/workflow/workflow.py | https://github.com/mlflow/mlflow/blob/master/examples/llama_index/workflow/workflow/workflow.py | Apache-2.0 |
async def transform_query(self, ev: TransformQueryEvent) -> WebsearchEvent:
"""Transform the user query into a search query."""
prompt = TRANSFORM_QUERY_TEMPLATE.format(query=ev.query)
transformed_query = self.llm.complete(prompt).text
return WebsearchEvent(search_query=transformed_query... | Transform the user query into a search query. | transform_query | python | mlflow/mlflow | examples/llama_index/workflow/workflow/workflow.py | https://github.com/mlflow/mlflow/blob/master/examples/llama_index/workflow/workflow/workflow.py | Apache-2.0 |
async def query_web_search(self, ev: WebsearchEvent) -> RetrievalResultEvent:
"""Perform web search with the transformed query string"""
search_results = self.tavily_tool.search(ev.search_query, max_results=5)
nodes = [NodeWithScore(node=document, score=None) for document in search_results]
... | Perform web search with the transformed query string | query_web_search | python | mlflow/mlflow | examples/llama_index/workflow/workflow/workflow.py | https://github.com/mlflow/mlflow/blob/master/examples/llama_index/workflow/workflow/workflow.py | Apache-2.0 |
async def gather_retrieval_results(
self, ctx: Context, ev: RetrievalResultEvent
) -> RerankEvent | QueryEvent | None:
"""Gather the retrieved texts and send them to the reranking step."""
# Wait for results from all retrievers
results = ctx.collect_events(ev, [RetrievalResultEvent] ... | Gather the retrieved texts and send them to the reranking step. | gather_retrieval_results | python | mlflow/mlflow | examples/llama_index/workflow/workflow/workflow.py | https://github.com/mlflow/mlflow/blob/master/examples/llama_index/workflow/workflow/workflow.py | Apache-2.0 |
async def rerank(self, ctx: Context, ev: RerankEvent) -> QueryEvent:
"""Evaluate relevancy of retrieved documents with the query."""
query = await ctx.get("query")
# Rerank the nodes using LLM (RankGPT based)
reranker = RankGPTRerank(llm=self.llm, top_n=5)
reranked_nodes = reran... | Evaluate relevancy of retrieved documents with the query. | rerank | python | mlflow/mlflow | examples/llama_index/workflow/workflow/workflow.py | https://github.com/mlflow/mlflow/blob/master/examples/llama_index/workflow/workflow/workflow.py | Apache-2.0 |
def _already_ran(entry_point_name, parameters, git_commit, experiment_id=None):
"""Best-effort detection of if a run with the given entrypoint name,
parameters, and experiment id already ran. The run must have completed
successfully and have at least the parameters provided.
"""
experiment_id = expe... | Best-effort detection of if a run with the given entrypoint name,
parameters, and experiment id already ran. The run must have completed
successfully and have at least the parameters provided.
| _already_ran | python | mlflow/mlflow | examples/multistep_workflow/main.py | https://github.com/mlflow/mlflow/blob/master/examples/multistep_workflow/main.py | Apache-2.0 |
async def customer_balance(ctx: RunContext[SupportDependencies], include_pending: bool) -> str:
"""Returns the customer's current account balance."""
balance = await ctx.deps.db.customer_balance(
id=ctx.deps.customer_id,
include_pending=include_pending,
)
return f"${balance:.2f}" | Returns the customer's current account balance. | customer_balance | python | mlflow/mlflow | examples/pydanticai/tracing.py | https://github.com/mlflow/mlflow/blob/master/examples/pydanticai/tracing.py | Apache-2.0 |
def model_training_hyperparameter_tuning(max_epochs, total_trials, params):
"""
This function takes input params max_epochs, total_trials, params and creates a nested run in MLflow.
The parameters, metrics, model and summary are dumped into their respective mlflow-run ids. The best
parameters are dumped... |
This function takes input params max_epochs, total_trials, params and creates a nested run in MLflow.
The parameters, metrics, model and summary are dumped into their respective mlflow-run ids. The best
parameters are dumped along with the baseline model.
Args:
max_epochs: Max epochs used for ... | model_training_hyperparameter_tuning | python | mlflow/mlflow | examples/pytorch/AxHyperOptimizationPTL/ax_hpo_iris.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/AxHyperOptimizationPTL/ax_hpo_iris.py | Apache-2.0 |
def __init__(self, tokenizer, source, max_length, num_samples, dataset="20newsgroups"):
"""
Custom Dataset - Converts the input text and label to tensor
Args:
tokenizer: bert tokenizer
source: data source - Either a dataframe or DataPipe
max_length: maximum l... |
Custom Dataset - Converts the input text and label to tensor
Args:
tokenizer: bert tokenizer
source: data source - Either a dataframe or DataPipe
max_length: maximum length of the news text
num_samples: number of samples to load
dataset: Data... | __init__ | python | mlflow/mlflow | examples/pytorch/BertNewsClassification/bert_classification.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/BertNewsClassification/bert_classification.py | Apache-2.0 |
def __init__(self, dataset, batch_size, num_workers, num_samples):
"""
Initialization of inherited lightning data module
"""
super().__init__()
self.PRE_TRAINED_MODEL_NAME = "bert-base-uncased"
self.train_dataset = None
self.val_dataset = None
self.test_da... |
Initialization of inherited lightning data module
| __init__ | python | mlflow/mlflow | examples/pytorch/BertNewsClassification/bert_classification.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/BertNewsClassification/bert_classification.py | Apache-2.0 |
def setup(self, stage=None):
"""
Split the data into train, test, validation data
Args:
stage: Stage - training or testing
"""
self.tokenizer = BertTokenizer.from_pretrained(self.PRE_TRAINED_MODEL_NAME)
if self.dataset == "20newsgroups":
num_sampl... |
Split the data into train, test, validation data
Args:
stage: Stage - training or testing
| setup | python | mlflow/mlflow | examples/pytorch/BertNewsClassification/bert_classification.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/BertNewsClassification/bert_classification.py | Apache-2.0 |
def create_data_loader(self, source, count):
"""
Generic data loader function
Args:
source: Input dataframe.
count: Number of samples to load.
Returns:
Returns the constructed dataloader.
"""
ds = NewsDataset(
source=sourc... |
Generic data loader function
Args:
source: Input dataframe.
count: Number of samples to load.
Returns:
Returns the constructed dataloader.
| create_data_loader | python | mlflow/mlflow | examples/pytorch/BertNewsClassification/bert_classification.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/BertNewsClassification/bert_classification.py | Apache-2.0 |
def __init__(self, dataset, lr):
"""
Initializes the network, optimizer and scheduler
"""
super().__init__()
self.dataset = dataset
self.lr = lr
self.PRE_TRAINED_MODEL_NAME = "bert-base-uncased"
self.bert_model = BertModel.from_pretrained(self.PRE_TRAINED_... |
Initializes the network, optimizer and scheduler
| __init__ | python | mlflow/mlflow | examples/pytorch/BertNewsClassification/bert_classification.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/BertNewsClassification/bert_classification.py | Apache-2.0 |
def forward(self, input_ids, attention_mask):
"""
Args:
input_ids: Input data.
attention_mask: Attention mask value.
Returns:
output: Type of news for the given news snippet.
"""
output = self.bert_model(input_ids=input_ids, attention_mask=att... |
Args:
input_ids: Input data.
attention_mask: Attention mask value.
Returns:
output: Type of news for the given news snippet.
| forward | python | mlflow/mlflow | examples/pytorch/BertNewsClassification/bert_classification.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/BertNewsClassification/bert_classification.py | Apache-2.0 |
def training_step(self, train_batch, batch_idx):
"""
Training the data as batches and returns training loss on each batch
Args:
train_batch: Batch data
batch_idx: Batch indices
Returns:
output: Training loss
"""
input_ids = train_batc... |
Training the data as batches and returns training loss on each batch
Args:
train_batch: Batch data
batch_idx: Batch indices
Returns:
output: Training loss
| training_step | python | mlflow/mlflow | examples/pytorch/BertNewsClassification/bert_classification.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/BertNewsClassification/bert_classification.py | Apache-2.0 |
def test_step(self, test_batch, batch_idx):
"""
Performs test and computes the accuracy of the model
Args:
test_batch: Batch data
batch_idx: Batch indices
Returns:
output - Testing accuracy
"""
input_ids = test_batch["input_ids"].to(s... |
Performs test and computes the accuracy of the model
Args:
test_batch: Batch data
batch_idx: Batch indices
Returns:
output - Testing accuracy
| test_step | python | mlflow/mlflow | examples/pytorch/BertNewsClassification/bert_classification.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/BertNewsClassification/bert_classification.py | Apache-2.0 |
def validation_step(self, val_batch, batch_idx):
"""
Performs validation of data in batches
Args:
val_batch: Batch data
batch_idx: Batch indices
Returns:
output: valid step loss
"""
input_ids = val_batch["input_ids"].to(self.device)
... |
Performs validation of data in batches
Args:
val_batch: Batch data
batch_idx: Batch indices
Returns:
output: valid step loss
| validation_step | python | mlflow/mlflow | examples/pytorch/BertNewsClassification/bert_classification.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/BertNewsClassification/bert_classification.py | Apache-2.0 |
def configure_optimizers(self):
"""
Initializes the optimizer and learning rate scheduler
Returns:
output: Initialized optimizer and scheduler
"""
self.optimizer = torch.optim.AdamW(self.parameters(), lr=self.lr)
self.scheduler = {
"scheduler": to... |
Initializes the optimizer and learning rate scheduler
Returns:
output: Initialized optimizer and scheduler
| configure_optimizers | python | mlflow/mlflow | examples/pytorch/BertNewsClassification/bert_classification.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/BertNewsClassification/bert_classification.py | Apache-2.0 |
def get_titanic():
"""
we now preprocess the data by converting some categorical features such as
gender, location of embarcation, and passenger class into one-hot encodings
We also remove some features that are more difficult to analyze
After processing, the features we have are:
Age: Passenger... |
we now preprocess the data by converting some categorical features such as
gender, location of embarcation, and passenger class into one-hot encodings
We also remove some features that are more difficult to analyze
After processing, the features we have are:
Age: Passenger Age
Sibsp: Number of ... | get_titanic | python | mlflow/mlflow | examples/pytorch/CaptumExample/Titanic_Captum_Interpret.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/CaptumExample/Titanic_Captum_Interpret.py | Apache-2.0 |
def feature_conductance(net, test_input_tensor):
"""
The method takes tensor(s) of input examples (matching the forward function of the model),
and returns the input attributions for the given input example.
The returned values of the attribute method are the attributions,
which match the size of th... |
The method takes tensor(s) of input examples (matching the forward function of the model),
and returns the input attributions for the given input example.
The returned values of the attribute method are the attributions,
which match the size of the given inputs, and delta,
which approximates the er... | feature_conductance | python | mlflow/mlflow | examples/pytorch/CaptumExample/Titanic_Captum_Interpret.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/CaptumExample/Titanic_Captum_Interpret.py | Apache-2.0 |
def layer_conductance(net, test_input_tensor):
"""
To use Layer Conductance, we create a LayerConductance object passing in the model as well as the module (layer) whose output we would like to understand.
In this case, we choose net.sigmoid1, the output of the first hidden layer.
Now obtain the conduct... |
To use Layer Conductance, we create a LayerConductance object passing in the model as well as the module (layer) whose output we would like to understand.
In this case, we choose net.sigmoid1, the output of the first hidden layer.
Now obtain the conductance values for all the test examples by calling attri... | layer_conductance | python | mlflow/mlflow | examples/pytorch/CaptumExample/Titanic_Captum_Interpret.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/CaptumExample/Titanic_Captum_Interpret.py | Apache-2.0 |
def neuron_conductance(net, test_input_tensor, neuron_selector=None):
"""
We have identified that some of the neurons are not learning important features, while others are.
Can we now understand what each of these important neurons are looking at in the input?
For instance, are they identifying differen... |
We have identified that some of the neurons are not learning important features, while others are.
Can we now understand what each of these important neurons are looking at in the input?
For instance, are they identifying different features in the input or similar ones?
To answer these questions, we c... | neuron_conductance | python | mlflow/mlflow | examples/pytorch/CaptumExample/Titanic_Captum_Interpret.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/CaptumExample/Titanic_Captum_Interpret.py | Apache-2.0 |
def setup(self, stage=None):
"""
Downloads the data, parse it and split the data into train, test, validation data
Args:
stage: Stage - training or testing
"""
self.df_train = datasets.MNIST(
"dataset", download=True, train=True, transform=self.transform... |
Downloads the data, parse it and split the data into train, test, validation data
Args:
stage: Stage - training or testing
| setup | python | mlflow/mlflow | examples/pytorch/IterativePruning/mnist.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/IterativePruning/mnist.py | Apache-2.0 |
def forward(self, x):
"""
Args:
x: Input data
Returns:
output - mnist digit label for the input image
"""
batch_size = x.size()[0]
# (b, 1, 28, 28) -> (b, 1*28*28)
x = x.view(batch_size, -1)
# layer 1 (b, 1*28*28) -> (b, 128)
... |
Args:
x: Input data
Returns:
output - mnist digit label for the input image
| forward | python | mlflow/mlflow | examples/pytorch/IterativePruning/mnist.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/IterativePruning/mnist.py | Apache-2.0 |
def training_step(self, train_batch, batch_idx):
"""
Training the data as batches and returns training loss on each batch
Args:
train_batch: Batch data
batch_idx: Batch indices
Returns:
output - Training loss
"""
x, y = train_batch
... |
Training the data as batches and returns training loss on each batch
Args:
train_batch: Batch data
batch_idx: Batch indices
Returns:
output - Training loss
| training_step | python | mlflow/mlflow | examples/pytorch/IterativePruning/mnist.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/IterativePruning/mnist.py | Apache-2.0 |
def test_step(self, test_batch, batch_idx):
"""
Performs test and computes the accuracy of the model
Args:
test_batch: Batch data.
batch_idx: Batch indices.
Returns:
output: Testing accuracy.
"""
x, y = test_batch
output = sel... |
Performs test and computes the accuracy of the model
Args:
test_batch: Batch data.
batch_idx: Batch indices.
Returns:
output: Testing accuracy.
| test_step | python | mlflow/mlflow | examples/pytorch/IterativePruning/mnist.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/IterativePruning/mnist.py | Apache-2.0 |
def test_step(self, test_batch, batch_idx):
"""
Performs test and computes the accuracy of the model
Args:
test_batch: Batch data
batch_idx: Batch indices
Returns:
output: Testing accuracy
"""
x, y = test_batch
output = self.f... |
Performs test and computes the accuracy of the model
Args:
test_batch: Batch data
batch_idx: Batch indices
Returns:
output: Testing accuracy
| test_step | python | mlflow/mlflow | examples/pytorch/MNIST/mnist_autolog_example.py | https://github.com/mlflow/mlflow/blob/master/examples/pytorch/MNIST/mnist_autolog_example.py | Apache-2.0 |
def load_data(fpath):
"""
Simple helper function for loading data to be used by CPU/GPU models.
Args:
fpath: Path to the data to be ingested
Returns:
DataFrame wrapping the data at [fpath]. Data will be in either a Pandas or RAPIDS (cuDF) DataFrame
"""
import cudf
df = cud... |
Simple helper function for loading data to be used by CPU/GPU models.
Args:
fpath: Path to the data to be ingested
Returns:
DataFrame wrapping the data at [fpath]. Data will be in either a Pandas or RAPIDS (cuDF) DataFrame
| load_data | python | mlflow/mlflow | examples/rapids/mlflow_project/src/rf_test/train.py | https://github.com/mlflow/mlflow/blob/master/examples/rapids/mlflow_project/src/rf_test/train.py | Apache-2.0 |
def _train(params, fpath, hyperopt=False):
"""
Args:
params: Hyperparameters. Its structure is consistent with how search space is defined.
fpath: Path or URL for the training data used with the model.
hyperopt: Use hyperopt for hyperparameter search during training.
Returns:
... |
Args:
params: Hyperparameters. Its structure is consistent with how search space is defined.
fpath: Path or URL for the training data used with the model.
hyperopt: Use hyperopt for hyperparameter search during training.
Returns:
dict with fields 'loss' (scalar loss) and 'statu... | _train | python | mlflow/mlflow | examples/rapids/mlflow_project/src/rf_test/train.py | https://github.com/mlflow/mlflow/blob/master/examples/rapids/mlflow_project/src/rf_test/train.py | Apache-2.0 |
def train(params, fpath, hyperopt=False):
"""
Proxy function used to call _train
Args:
params: Hyperparameters. Its structure is consistent with how search space is defined.
fpath: Path or URL for the training data used with the model.
hyperopt: Use hyperopt for hyperparameter searc... |
Proxy function used to call _train
Args:
params: Hyperparameters. Its structure is consistent with how search space is defined.
fpath: Path or URL for the training data used with the model.
hyperopt: Use hyperopt for hyperparameter search during training.
Returns:
dict wit... | train | python | mlflow/mlflow | examples/rapids/mlflow_project/src/rf_test/train.py | https://github.com/mlflow/mlflow/blob/master/examples/rapids/mlflow_project/src/rf_test/train.py | Apache-2.0 |
def train(fpath, max_depth, max_features, n_estimators):
"""
Train a Random Forest classifier with the specified hyperparameters.
Args:
fpath: Path or URL for the training data used with the model.
max_depth: Maximum depth of the trees in the Random Forest.
max_features: Number of f... |
Train a Random Forest classifier with the specified hyperparameters.
Args:
fpath: Path or URL for the training data used with the model.
max_depth: Maximum depth of the trees in the Random Forest.
max_features: Number of features to consider when looking for the best split.
n_e... | train | python | mlflow/mlflow | examples/rapids/mlflow_project/src/rf_test/train_simple.py | https://github.com/mlflow/mlflow/blob/master/examples/rapids/mlflow_project/src/rf_test/train_simple.py | Apache-2.0 |
def log_param(self, param):
"""Log a parameter dict for the given run."""
url = self.base_url + "/runs/log-parameter"
payload = {"run_id": self.run_id, "key": param["key"], "value": param["value"]}
r = requests.post(url, json=payload)
return r.status_code | Log a parameter dict for the given run. | log_param | python | mlflow/mlflow | examples/rest_api/mlflow_tracking_rest_api.py | https://github.com/mlflow/mlflow/blob/master/examples/rest_api/mlflow_tracking_rest_api.py | Apache-2.0 |
def log_metric(self, metric):
"""Log a metric dict for the given run."""
url = self.base_url + "/runs/log-metric"
payload = {
"run_id": self.run_id,
"key": metric["key"],
"value": metric["value"],
"timestamp": metric["timestamp"],
"step... | Log a metric dict for the given run. | log_metric | python | mlflow/mlflow | examples/rest_api/mlflow_tracking_rest_api.py | https://github.com/mlflow/mlflow/blob/master/examples/rest_api/mlflow_tracking_rest_api.py | Apache-2.0 |
def _get_user_id():
"""Get the ID of the user for the current run."""
try:
return pwd.getpwuid(os.getuid())[0]
except ImportError:
return _DEFAULT_USER_ID | Get the ID of the user for the current run. | _get_user_id | python | mlflow/mlflow | examples/rest_api/mlflow_tracking_rest_api.py | https://github.com/mlflow/mlflow/blob/master/examples/rest_api/mlflow_tracking_rest_api.py | Apache-2.0 |
def get_default_pip_requirements(include_cloudpickle=False):
"""Create list of default pip requirements for MLflow Models.
Returns
-------
list of default pip requirements for MLflow Models produced by this flavor.
Calls to :func:`save_model()` and :func:`log_model()` produce a pip environment
... | Create list of default pip requirements for MLflow Models.
Returns
-------
list of default pip requirements for MLflow Models produced by this flavor.
Calls to :func:`save_model()` and :func:`log_model()` produce a pip environment
that, at a minimum, contains these requirements.
| get_default_pip_requirements | python | mlflow/mlflow | examples/sktime/flavor.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/flavor.py | Apache-2.0 |
def load_model(model_uri, dst_path=None):
"""
Load a ``sktime`` model from a local file or a run.
Parameters
----------
model_uri : str
The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/pa... |
Load a ``sktime`` model from a local file or a run.
Parameters
----------
model_uri : str
The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://... | load_model | python | mlflow/mlflow | examples/sktime/flavor.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/flavor.py | Apache-2.0 |
def _load_pyfunc(path):
"""Load PyFunc implementation. Called by ``pyfunc.load_model``.
Parameters
----------
path : str
Local filesystem path to the MLflow Model with the ``sktime`` flavor.
"""
try:
sktime_flavor_conf = _get_flavor_configuration(model_path=path, flavor_name=FL... | Load PyFunc implementation. Called by ``pyfunc.load_model``.
Parameters
----------
path : str
Local filesystem path to the MLflow Model with the ``sktime`` flavor.
| _load_pyfunc | python | mlflow/mlflow | examples/sktime/flavor.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/flavor.py | Apache-2.0 |
def mock_s3_bucket():
"""Create a mock S3 bucket using moto.
Returns
-------
string with name of mock S3 bucket
"""
with moto.mock_s3():
bucket_name = "mock-bucket"
my_config = Config(region_name="us-east-1")
s3_client = boto3.client("s3", config=my_config)
s3_cl... | Create a mock S3 bucket using moto.
Returns
-------
string with name of mock S3 bucket
| mock_s3_bucket | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def sktime_custom_env(tmp_path):
"""Create a conda environment and returns path to conda environment yml file."""
conda_env = tmp_path.joinpath("conda_env.yml")
_mlflow_conda_env(conda_env, additional_pip_deps=["sktime"])
return conda_env | Create a conda environment and returns path to conda environment yml file. | sktime_custom_env | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def data_longley():
"""Create sample data for univariate model with exogenous regressor."""
y, X = load_longley()
y_train, y_test, X_train, X_test = temporal_train_test_split(y, X)
return y_train, y_test, X_train, X_test | Create sample data for univariate model with exogenous regressor. | data_longley | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def naive_forecaster_model_with_regressor(data_longley):
"""Create instance of fitted naive forecaster model."""
y_train, _, X_train, _ = data_longley
model = NaiveForecaster()
return model.fit(y_train, X_train) | Create instance of fitted naive forecaster model. | naive_forecaster_model_with_regressor | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_auto_arima_model_save_and_load(auto_arima_model, model_path, serialization_format):
"""Test saving and loading of native sktime auto_arima_model."""
flavor.save_model(
sktime_model=auto_arima_model,
path=model_path,
serialization_format=serialization_format,
)
loaded_mod... | Test saving and loading of native sktime auto_arima_model. | test_auto_arima_model_save_and_load | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_auto_arima_model_pyfunc_output(auto_arima_model, model_path, serialization_format):
"""Test auto arima prediction of loaded pyfunc model."""
flavor.save_model(
sktime_model=auto_arima_model,
path=model_path,
serialization_format=serialization_format,
)
loaded_pyfunc = fl... | Test auto arima prediction of loaded pyfunc model. | test_auto_arima_model_pyfunc_output | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
def test_naive_forecaster_model_with_regressor_pyfunc_output(
naive_forecaster_model_with_regressor, model_path, data_longley
):
"""Test naive forecaster prediction of loaded pyfunc model."""
_, _, _, X_test = data_longley
flavor.save_model(sktime_model=naive_forecaster_model_with_regressor, path=model... | Test naive forecaster prediction of loaded pyfunc model. | test_naive_forecaster_model_with_regressor_pyfunc_output | python | mlflow/mlflow | examples/sktime/test_sktime_model_export.py | https://github.com/mlflow/mlflow/blob/master/examples/sktime/test_sktime_model_export.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.