{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Pipelines\n", "\n", "EvalML pipelines represent a sequence of operations to be applied to data, where each operation is either a data transformation or an ML modeling algorithm.\n", "\n", "A pipeline holds a combination of one or more components, which will be applied to new input data in sequence.\n", "\n", "Each component and pipeline supports a set of parameters which configure its behavior. The AutoML search process seeks to find the combination of pipeline structure and pipeline parameters which perform the best on the data." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Defining a Pipeline Instance\n", "Pipeline instances can be instantiated using any of the following classes:\n", "\n", " - `RegressionPipeline`\n", " - `BinaryClassificationPipeline`\n", " - `MulticlassClassificationPipeline`\n", " - `TimeSeriesRegressionPipeline`\n", " - `TimeSeriesBinaryClassificationPipeline`\n", " - `TimeSeriesMulticlassClassificationPipeline`\n", " \n", "The class you want to use will depend on your problem type.\n", "The only required parameter input for instantiating a pipeline instance is `component_graph`, which can be a `ComponentGraph` [instance](https://evalml.alteryx.com/en/stable/autoapi/evalml/pipelines/index.html#evalml.pipelines.ComponentGraph), a list, or a dictionary containing a sequence of components to be fit and evaluated.\n", "\n", "A `component_graph` list is the default representation, which represents a linear order of transforming components with an estimator as the final component. A `component_graph` dictionary is used to represent a non-linear graph of components, where the key is a unique name for each component and the value is a list with the component's class as the first element and any parents of the component as the following element(s). For these two `component_graph` formats, each component can be provided as a reference to the component class for custom components, and as either a string name or as a reference to the component class for components defined in EvalML.\n", "\n", "If you choose to provide a `ComponentGraph` instance and want to set custom parameters for your pipeline, set it through the pipeline initialization rather than `ComponentGraph.instantiate()`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from evalml.pipelines import MulticlassClassificationPipeline, ComponentGraph\n", "\n", "component_graph_as_list = [\"Imputer\", \"Random Forest Classifier\"]\n", "MulticlassClassificationPipeline(component_graph=component_graph_as_list)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "component_graph_as_dict = {\n", " \"Imputer\": [\"Imputer\", \"X\", \"y\"],\n", " \"Encoder\": [\"One Hot Encoder\", \"Imputer.x\", \"y\"],\n", " \"Random Forest Clf\": [\"Random Forest Classifier\", \"Encoder.x\", \"y\"],\n", " \"Elastic Net Clf\": [\"Elastic Net Classifier\", \"Encoder.x\", \"y\"],\n", " \"Final Estimator\": [\n", " \"Logistic Regression Classifier\",\n", " \"Random Forest Clf.x\",\n", " \"Elastic Net Clf.x\",\n", " \"y\",\n", " ],\n", "}\n", "\n", "MulticlassClassificationPipeline(component_graph=component_graph_as_dict)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cg = ComponentGraph(component_graph_as_dict)\n", "\n", "# set parameters in the pipeline rather than through cg.instantiate()\n", "MulticlassClassificationPipeline(component_graph=cg, parameters={})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you're using your own [custom components](components.ipynb) you can refer to them like so:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from evalml.pipelines.components import Transformer\n", "\n", "\n", "class NewTransformer(Transformer):\n", " name = \"New Transformer\"\n", " hyperparameter_ranges = {\"parameter_1\": [\"a\", \"b\", \"c\"]}\n", "\n", " def __init__(self, parameter_1=1, random_seed=0):\n", " parameters = {\"parameter_1\": parameter_1}\n", " super().__init__(parameters=parameters, random_seed=random_seed)\n", "\n", " def transform(self, X, y=None):\n", " # Your code here!\n", " return X\n", "\n", "\n", "MulticlassClassificationPipeline([NewTransformer, \"Random Forest Classifier\"])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Pipeline Usage\n", "\n", "All pipelines define the following methods:\n", "\n", "* `fit` fits each component on the provided training data, in order.\n", "\n", "* `predict` computes the predictions of the component graph on the provided data.\n", "\n", "* `score` computes the value of [an objective](objectives.ipynb) on the provided data." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from evalml.demos import load_wine\n", "\n", "X, y = load_wine()\n", "\n", "pipeline = MulticlassClassificationPipeline(\n", " component_graph={\n", " \"Label Encoder\": [\"Label Encoder\", \"X\", \"y\"],\n", " \"Imputer\": [\"Imputer\", \"X\", \"Label Encoder.y\"],\n", " \"Random Forest Classifier\": [\n", " \"Random Forest Classifier\",\n", " \"Imputer.x\",\n", " \"Label Encoder.y\",\n", " ],\n", " }\n", ")\n", "pipeline.fit(X, y)\n", "print(pipeline.predict(X))\n", "print(pipeline.score(X, y, objectives=[\"log loss multiclass\"]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Custom Name\n", "\n", "By default, a pipeline's name is created using the component graph that makes up the pipeline. E.g. A pipeline with an imputer, one-hot encoder, and logistic regression classifier will have the name 'Logistic Regression Classifier w/ Imputer + One Hot Encoder'.\n", "\n", "If you'd like to override the pipeline's name attribute, you can set the `custom_name` parameter when initalizing a pipeline, like so:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "component_graph = [\"Imputer\", \"One Hot Encoder\", \"Logistic Regression Classifier\"]\n", "pipeline = MulticlassClassificationPipeline(component_graph)\n", "print(\"Pipeline with default name:\", pipeline.name)\n", "\n", "\n", "pipeline_with_name = MulticlassClassificationPipeline(\n", " component_graph, custom_name=\"My cool custom pipeline\"\n", ")\n", "print(\"Pipeline with custom name:\", pipeline_with_name.name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Pipeline Parameters\n", "\n", "You can also pass in custom parameters by using the `parameters` parameter, which will then be used when instantiating each component in `component_graph`. The parameters dictionary needs to be in the format of a two-layered dictionary where the key-value pairs are the component name and corresponding component parameters dictionary. The component parameters dictionary consists of (parameter name, parameter values) key-value pairs.\n", "\n", "An example will be shown below. The API reference for component parameters can also be found [here](../api_index.rst#components)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "parameters = {\n", " \"Imputer\": {\n", " \"categorical_impute_strategy\": \"most_frequent\",\n", " \"numeric_impute_strategy\": \"median\",\n", " },\n", " \"Logistic Regression Classifier\": {\n", " \"penalty\": \"l2\",\n", " \"C\": 1.0,\n", " },\n", "}\n", "component_graph = [\n", " \"Imputer\",\n", " \"One Hot Encoder\",\n", " \"Standard Scaler\",\n", " \"Logistic Regression Classifier\",\n", "]\n", "MulticlassClassificationPipeline(component_graph=component_graph, parameters=parameters)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Pipeline Description\n", "\n", "You can call `.graph()` to see each component and its parameters. Each component takes in data and feeds it to the next." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "component_graph = [\n", " \"Imputer\",\n", " \"One Hot Encoder\",\n", " \"Standard Scaler\",\n", " \"Logistic Regression Classifier\",\n", "]\n", "pipeline = MulticlassClassificationPipeline(\n", " component_graph=component_graph, parameters=parameters\n", ")\n", "pipeline.graph()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "component_graph_as_dict = {\n", " \"Imputer\": [\"Imputer\", \"X\", \"y\"],\n", " \"Encoder\": [\"One Hot Encoder\", \"Imputer.x\", \"y\"],\n", " \"Random Forest Clf\": [\"Random Forest Classifier\", \"Encoder.x\", \"y\"],\n", " \"Elastic Net Clf\": [\"Elastic Net Classifier\", \"Encoder.x\", \"y\"],\n", " \"Final Estimator\": [\n", " \"Logistic Regression Classifier\",\n", " \"Random Forest Clf.x\",\n", " \"Elastic Net Clf.x\",\n", " \"y\",\n", " ],\n", "}\n", "\n", "nonlinear_pipeline = MulticlassClassificationPipeline(\n", " component_graph=component_graph_as_dict\n", ")\n", "nonlinear_pipeline.graph()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can see a textual representation of the pipeline by calling `.describe()`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pipeline.describe()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nonlinear_pipeline.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Component Graph" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can use `pipeline.get_component(name)` and provide the component name to access any component (API reference [here](../autoapi/evalml/pipelines/index.rst#evalml.pipelines.PipelineBase.get_component)):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pipeline.get_component(\"Imputer\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nonlinear_pipeline.get_component(\"Elastic Net Clf\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, you can index directly into the pipeline to get a component" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "first_component = pipeline[0]\n", "print(first_component.name)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nonlinear_pipeline[\"Final Estimator\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Pipeline Estimator\n", "\n", "EvalML enforces that the last component of a linear pipeline is an estimator. You can access this estimator directly by using `pipeline.estimator`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pipeline.estimator" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Input Feature Names\n", "\n", "After a pipeline is fitted, you can access a pipeline's `input_feature_names` attribute to obtain a dictionary containing a list of feature names passed to each component of the pipeline. This could be especially useful for debugging where a feature might have been dropped or detecting unexpected behavior." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pipeline = MulticlassClassificationPipeline([\"Imputer\", \"Random Forest Classifier\"])\n", "pipeline.fit(X, y)\n", "pipeline.input_feature_names" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Binary Classification Pipeline Thresholds\n", "\n", "For binary classification pipelines, you can choose to tune the decision boundary threshold, which allows the pipeline to distinguish predictions from positive to negative. The default boundary, if none is set, is 0.5, which means that predictions with a probability of `>= 0.5` are classified as the positive class, while all others are negative.\n", "\n", "You can use the binary classification pipeline's `optimize_thresholds` method to choose the best threshold for an objective, or it can be manually set. EvalML's [AutoMLSearch](../autoapi/evalml/automl/index.rst#evalml.automl.AutoMLSearch) uses `optimize_thresholds` by default for `binary` problems, and it uses `F1` as the default objective to optimize on. This can be turned off by passing in `optimize_thresholds=False`, or you can changed the objective used by changing the `objective` or `alternate_thresholding_objective` arguments." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from evalml.demos import load_breast_cancer\n", "from evalml.pipelines import BinaryClassificationPipeline\n", "\n", "X, y = load_breast_cancer()\n", "X_to_predict = X.tail(10)\n", "\n", "bcp = BinaryClassificationPipeline(\n", " {\n", " \"Imputer\": [\"Imputer\", \"X\", \"y\"],\n", " \"Label Encoder\": [\"Label Encoder\", \"Imputer.x\", \"y\"],\n", " \"RFC\": [\"Random Forest Classifier\", \"Imputer.x\", \"Label Encoder.y\"],\n", " }\n", ")\n", "bcp.fit(X, y)\n", "\n", "predict_proba = bcp.predict_proba(X_to_predict)\n", "predict_proba" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# view the current threshold\n", "print(\"The threshold is {}\".format(bcp.threshold))\n", "\n", "# view the first few predictions\n", "print(bcp.predict(X_to_predict))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that the default threshold above is `None`, which means that the pipeline defaults to using 0.5 as the threshold.\n", "\n", "You can manually set the threshold as well:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# you can manually set the threshold\n", "bcp.threshold = 0.99\n", "# view the threshold\n", "print(\"The threshold is {}\".format(bcp.threshold))\n", "\n", "# view the first few predictions\n", "print(bcp.predict(X_to_predict))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, the best way to set the threshold is by using the pipeline's `optimize_threshold` method. This takes in the predicted values, as well as the true values and objective to optimize with, and it finds the best threshold to maximize this objective value. \n", "\n", "This method is best used with validation data, since optimizing on training data could lead to overfitting and optimizing on test data would introduce large biases.\n", "\n", "Below walks through threshold tuning using the `F1` objective." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from evalml.objectives import F1\n", "\n", "# get predictions for positive class only\n", "predict_proba = predict_proba.iloc[:, -1]\n", "bcp.optimize_threshold(X_to_predict, y.tail(10), predict_proba, F1())\n", "\n", "print(\"The new threshold is {}\".format(bcp.threshold))\n", "\n", "# view the first few predictions\n", "print(bcp.predict(X_to_predict))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Grabbing rows near the decision boundary\n", "For binary classification problems, you can also look at the rows closest to the decision boundary by using `rows_of_interest`. This method returns the indices of interest, which can then be used to obtain the subset of the data that falls closest to the decision boundary. This can help with further analysis of the model, and can give you better understanding of what rows the model could be having trouble with.\n", "\n", "`rows_of_interest` takes in an `epsilon` parameter (defaulted to `0.1`), which determines which rows to return. The rows that are returned are the rows where the probability of it being in the positive class fall between the `threshold +- epsilon` range. Increase the `epsilon` value to get more rows, and decrease it to get fewer rows.\n", "\n", "Below is a walkthrough of using `rows_of_interest`, building off the previous pipeline which is already thresholded." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from evalml.pipelines.utils import rows_of_interest\n", "\n", "indices = rows_of_interest(bcp, X, y, types=\"all\")\n", "X.iloc[indices].head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can see what the probabilities are for these rows to determine how close they are to the new pipeline threshold. X is used here for brevity." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pred_proba = bcp.predict_proba(X)\n", "pos_value_proba = pred_proba.iloc[:, -1]\n", "pos_value_proba.iloc[indices].head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Saving and Loading Pipelines\n", "\n", "You can save and load trained or untrained pipeline instances using the Python [pickle](https://docs.python.org/3/library/pickle.html#:~:text=%E2%80%9CPickling%E2%80%9D%20is%20the%20process%20whereby,back%20into%20an%20object%20hierarchy.) format, like so:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pickle\n", "\n", "pipeline_to_pickle = BinaryClassificationPipeline(\n", " [\"Imputer\", \"Random Forest Classifier\"]\n", ")\n", "\n", "with open(\"pipeline.pkl\", \"wb\") as f:\n", " pickle.dump(pipeline_to_pickle, f)\n", "\n", "pickled_pipeline = None\n", "with open(\"pipeline.pkl\", \"rb\") as f:\n", " pickled_pipeline = pickle.load(f)\n", "\n", "assert pickled_pipeline == pipeline_to_pickle\n", "pickled_pipeline.fit(X, y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Generate Code\n", "\n", "Once you have instantiated a pipeline, you can generate string Python code to recreate this pipeline, which can then be saved and run elsewhere with EvalML. `generate_pipeline_code` requires a pipeline instance as the input. It can also handle custom components, but it won't return the code required to define the component. Note that any external libraries used in creating the pipeline instance will also need to be imported to execute the returned code.\n", "\n", "Code generation is not yet supported for nonlinear pipelines." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from evalml.pipelines.utils import generate_pipeline_code\n", "from evalml.pipelines import BinaryClassificationPipeline\n", "import pandas as pd\n", "from evalml.utils import infer_feature_types\n", "from skopt.space import Integer\n", "\n", "\n", "class MyDropNullColumns(Transformer):\n", " \"\"\"Transformer to drop features whose percentage of NaN values exceeds a specified threshold\"\"\"\n", "\n", " name = \"My Drop Null Columns Transformer\"\n", " hyperparameter_ranges = {}\n", "\n", " def __init__(self, pct_null_threshold=1.0, random_seed=0, **kwargs):\n", " \"\"\"Initalizes an transformer to drop features whose percentage of NaN values exceeds a specified threshold.\n", "\n", " Args:\n", " pct_null_threshold(float): The percentage of NaN values in an input feature to drop.\n", " Must be a value between [0, 1] inclusive. If equal to 0.0, will drop columns with any null values.\n", " If equal to 1.0, will drop columns with all null values. Defaults to 0.95.\n", " \"\"\"\n", " if pct_null_threshold < 0 or pct_null_threshold > 1:\n", " raise ValueError(\n", " \"pct_null_threshold must be a float between 0 and 1, inclusive.\"\n", " )\n", " parameters = {\"pct_null_threshold\": pct_null_threshold}\n", " parameters.update(kwargs)\n", "\n", " self._cols_to_drop = None\n", " super().__init__(\n", " parameters=parameters, component_obj=None, random_seed=random_seed\n", " )\n", "\n", " def fit(self, X, y=None):\n", " pct_null_threshold = self.parameters[\"pct_null_threshold\"]\n", " X = infer_feature_types(X)\n", " percent_null = X.isnull().mean()\n", " if pct_null_threshold == 0.0:\n", " null_cols = percent_null[percent_null > 0]\n", " else:\n", " null_cols = percent_null[percent_null >= pct_null_threshold]\n", " self._cols_to_drop = list(null_cols.index)\n", " return self\n", "\n", " def transform(self, X, y=None):\n", " \"\"\"Transforms data X by dropping columns that exceed the threshold of null values.\n", " Args:\n", " X (pd.DataFrame): Data to transform\n", " y (pd.Series, optional): Targets\n", " Returns:\n", " pd.DataFrame: Transformed X\n", " \"\"\"\n", "\n", " X = infer_feature_types(X)\n", " return X.drop(columns=self._cols_to_drop)\n", "\n", "\n", "pipeline_instance = BinaryClassificationPipeline(\n", " [\n", " \"Imputer\",\n", " MyDropNullColumns,\n", " \"DateTime Featurizer\",\n", " \"Natural Language Featurizer\",\n", " \"One Hot Encoder\",\n", " \"Random Forest Classifier\",\n", " ],\n", " custom_name=\"Pipeline with Custom Component\",\n", " random_seed=20,\n", ")\n", "\n", "code = generate_pipeline_code(pipeline_instance)\n", "print(code)\n", "\n", "# This string can then be pasted into a separate window and run, although since the pipeline has custom component `MyDropNullColumns`,\n", "# the code for that component must also be included\n", "from evalml.demos import load_fraud\n", "\n", "X, y = load_fraud(1000)\n", "exec(code)\n", "pipeline.fit(X, y)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.6" } }, "nbformat": 4, "nbformat_minor": 4 }