<jupyter_start><jupyter_text>Copyright 2020 The TensorFlow Authors.<jupyter_code>#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.<jupyter_output><empty_output><jupyter_text>Create a TFX pipeline using templates with Local orchestrator View on TensorFlow.orgRun in Google ColabView source on GitHubDownload notebook  IntroductionThis document will provide instructions to create a TensorFlow Extended (TFX) pipelineusing *templates* which are provided with TFX Python package.Most of instructions are Linux shell commands, and correspondingJupyter Notebook code cells which invoke those commands using `!` are provided.You will build a pipeline using [Taxi Trips dataset](https://data.cityofchicago.org/Transportation/Taxi-Trips/wrvz-psew)released by the City of Chicago. We strongly encourage you to try to buildyour own pipeline using your dataset by utilizing this pipeline as a baseline.We will build a pipeline which runs on local environment. If you are interested in using Kubeflow orchestrator on Google Cloud, please see [TFX on Cloud AI Platform Pipelines tutorial](https://www.tensorflow.org/tfx/tutorials/tfx/cloud-ai-platform-pipelines). Prerequisites* Linux / MacOS* Python >= 3.5.3You can get all prerequisites easily by [running this notebook on Google Colab](https://colab.sandbox.google.com/github/tensorflow/tfx/blob/master/docs/tutorials/tfx/template_local.ipynb).  Step 1. Set up your environment.**Throughout this document, we will present commands twice. Once as a copy-and-paste-ready shell command, once as a jupyter notebook cell. If you are using Colab, just skip shell script block and execute notebook cells.**You should prepare a development environment to build a pipeline.Install `tfx` python package. We recommend use of `virtualenv` in the local environment. You can use following shell script snippet to set up your environment.```sh Create a virtualenv for tfx.virtualenv -p python3 venvsource venv/bin/activate Install python packages.python -m pip install --user --upgrade tfx==0.30.0```If you are using colab:<jupyter_code>import sys
!{sys.executable} -m pip install --user --upgrade -q tfx==0.30.0<jupyter_output><empty_output><jupyter_text>NOTE: There might be some errors during package installation. For example,>ERROR: some-package 0.some_version.1 has requirement other-package!=2.0.,&lt;3,&gt;=1.15, but you'll have other-package 2.0.0 which is incompatible.Please ignore these errors at this moment.<jupyter_code># Set `PATH` to include user python binary directory.
HOME=%env HOME
PATH=%env PATH
%env PATH={PATH}:{HOME}/.local/bin<jupyter_output><empty_output><jupyter_text>Let's check the version of TFX.```bashpython -c "from tfx import version ; print('TFX version: {}'.format(version.__version__))"```<jupyter_code>!python3 -c "from tfx import version ; print('TFX version: {}'.format(version.__version__))"<jupyter_output><empty_output><jupyter_text>And, it's done. We are ready to create a pipeline.  Step 2. Copy predefined template to your project directory.In this step, we will create a working pipeline project directory and files by copying additional files from a predefined template.You may give your pipeline a different name by changing the `PIPELINE_NAME` below. This will also become the name of the project directory where your files will be put.```bashexport PIPELINE_NAME="my_pipeline"export PROJECT_DIR=~/tfx/${PIPELINE_NAME}```<jupyter_code>PIPELINE_NAME="my_pipeline"
import os
# Create a project directory under Colab content directory.
PROJECT_DIR=os.path.join(os.sep,"content",PIPELINE_NAME)<jupyter_output><empty_output><jupyter_text>TFX includes the `taxi` template with the TFX python package. If you are planning to solve a point-wise prediction problem, including classification and regresssion, this template could be used as a starting point.The `tfx template copy` CLI command copies predefined template files into your project directory.```shtfx template copy \   --pipeline_name="${PIPELINE_NAME}" \   --destination_path="${PROJECT_DIR}" \   --model=taxi```<jupyter_code>!tfx template copy \
  --pipeline_name={PIPELINE_NAME} \
  --destination_path={PROJECT_DIR} \
  --model=taxi<jupyter_output><empty_output><jupyter_text>Change the working directory context in this notebook to the project directory.```bashcd ${PROJECT_DIR}```<jupyter_code>%cd {PROJECT_DIR}<jupyter_output><empty_output><jupyter_text>Step 3. Browse your copied source files. The TFX template provides basic scaffold files to build a pipeline, including Python source code, sample data, and Jupyter Notebooks to analyse the output of the pipeline. The `taxi` template uses the same *Chicago Taxi* dataset and ML model as the [Airflow Tutorial](https://www.tensorflow.org/tfx/tutorials/tfx/airflow_workshop).In Google Colab, you can browse files by clicking a folder icon on the left. Files should be copied under the project directoy, whose name is `my_pipeline` in this case. You can click directory names to see the content of the directory, and double-click file names to open them.Here is brief introduction to each of the Python files.-   `pipeline` - This directory contains the definition of the pipeline    -   `configs.py` — defines common constants for pipeline runners    -   `pipeline.py` — defines TFX components and a pipeline-   `models` - This directory contains ML model definitions.    -   `features.py`, `features_test.py` — defines features for the model    -   `preprocessing.py`, `preprocessing_test.py` — defines preprocessing        jobs using `tf::Transform`    -   `estimator` - This directory contains an Estimator based model.        -   `constants.py` — defines constants of the model        -   `model.py`, `model_test.py` — defines DNN model using TF estimator    -   `keras` - This directory contains a Keras based model.        -   `constants.py` — defines constants of the model        -   `model.py`, `model_test.py` — defines DNN model using Keras-   `local_runner.py`, `kubeflow_runner.py` — define runners for each orchestration engine You might notice that there are some files with `_test.py` in their name. These are unit tests of the pipeline and it is recommended to add more unit tests as you implement your own pipelines.You can run unit tests by supplying the module name of test files with `-m` flag. You can usually get a module name by deleting `.py` extension and replacing `/` with `.`.  For example:```bashpython -m models.features_test```<jupyter_code>!{sys.executable} -m models.features_test
!{sys.executable} -m models.keras.model_test<jupyter_output><empty_output><jupyter_text>Step 4. Run your first TFX pipelineYou can create a pipeline using `pipeline create` command.```bashtfx pipeline create --engine=local --pipeline_path=local_runner.py```<jupyter_code>!tfx pipeline create --engine=local --pipeline_path=local_runner.py<jupyter_output><empty_output><jupyter_text>Then, you can run the created pipeline using `run create` command.```shtfx run create --engine=local --pipeline_name="${PIPELINE_NAME}"```<jupyter_code>!tfx run create --engine=local --pipeline_name={PIPELINE_NAME}<jupyter_output><empty_output><jupyter_text>If successful, you'll see `Component CsvExampleGen is finished.` When you copy the template, only one component, CsvExampleGen, is included in the pipeline.  Step 5. Add components for data validation.In this step, you will add components for data validation including `StatisticsGen`, `SchemaGen`, and `ExampleValidator`. If you are interested in data validation, please see [Get started with Tensorflow Data Validation](https://www.tensorflow.org/tfx/data_validation/get_started).We will modify copied pipeline definition in `pipeline/pipeline.py`. If you are working on your local environment, use your favorite editor to edit the file. If you are working on Google Colab, >**Click folder icon on the left to open `Files` view**.>**Click `my_pipeline` to open the directory and click `pipeline` directory to open and double-click `pipeline.py` to open the file**.>Find and uncomment the 3 lines which add `StatisticsGen`, `SchemaGen`, and `ExampleValidator` to the pipeline. (Tip: find comments containing `TODO(step 5):`).> Your change will be saved automatically in a few seconds. Make sure that the `*` mark in front of the `pipeline.py` disappeared in the tab title. **There is no save button or shortcut for the file editor in Colab. Python files in file editor can be saved to the runtime environment even in `playground` mode.**You now need to update the existing pipeline with modified pipeline definition. Use the `tfx pipeline update` command to update your pipeline, followed by the `tfx run create` command to create a new execution run of your updated pipeline.```sh Update the pipelinetfx pipeline update --engine=local --pipeline_path=local_runner.py You can run the pipeline the same way.tfx run create --engine local --pipeline_name "${PIPELINE_NAME}"```<jupyter_code># Update the pipeline
!tfx pipeline update --engine=local --pipeline_path=local_runner.py
# You can run the pipeline the same way.
!tfx run create --engine local --pipeline_name {PIPELINE_NAME}<jupyter_output><empty_output><jupyter_text>You should be able to see the output log from the added components. Our pipeline creates output artifacts in `tfx_pipeline_output/my_pipeline` directory.  Step 6. Add components for training.In this step, you will add components for training and model validation including `Transform`, `Trainer`, `Resolver`, `Evaluator`, and `Pusher`.> **Open `pipeline/pipeline.py`**. Find and uncomment 5 lines which add `Transform`, `Trainer`, `Resolver`, `Evaluator` and `Pusher` to the pipeline. (Tip: find `TODO(step 6):`)As you did before, you now need to update the existing pipeline with the modified pipeline definition. The instructions are the same as Step 5. Update the pipeline using `tfx pipeline update`, and create an execution run using `tfx run create`.```shtfx pipeline update --engine=local --pipeline_path=local_runner.pytfx run create --engine local --pipeline_name "${PIPELINE_NAME}"```<jupyter_code>!tfx pipeline update --engine=local --pipeline_path=local_runner.py
!tfx run create --engine local --pipeline_name {PIPELINE_NAME}<jupyter_output><empty_output><jupyter_text>When this execution run finishes successfully, you have now created and run your first TFX pipeline using Local orchestrator!**NOTE:** You might have noticed that every time we create a pipeline run, every component runs again and again even though the input and the parameters were not changed.It is waste of time and resources, and you can skip those executions with pipeline caching. You can enable caching by specifying `enable_cache=True` for the `Pipeline` object in `pipeline.py`.  Step 7. (*Optional*) Try BigQueryExampleGen.[BigQuery] is a serverless, highly scalable, and cost-effective cloud data warehouse. BigQuery can be used as a source for training examples in TFX. In this step, we will add `BigQueryExampleGen` to the pipeline.You need a [Google Cloud Platform](https://cloud.google.com/gcp/getting-started) account to use BigQuery. Please prepare a GCP project.Login to your project using colab auth library or `gcloud` utility.```sh You need `gcloud` tool to login in local shell environment.gcloud auth login```<jupyter_code>if 'google.colab' in sys.modules:
  from google.colab import auth
  auth.authenticate_user()
  print('Authenticated')<jupyter_output><empty_output><jupyter_text>You should specify your GCP project name to access BigQuery resources using TFX. Set `GOOGLE_CLOUD_PROJECT` environment variable to your project name.```shexport GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_NAME_HERE```<jupyter_code># Set your project name below.
# WARNING! ENTER your project name before running this cell.
%env GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_NAME_HERE<jupyter_output><empty_output><jupyter_text>> **Open `pipeline/pipeline.py`**. Comment out `CsvExampleGen` and uncomment the line which create an instance of `BigQueryExampleGen`. You also need to uncomment `query` argument of the `create_pipeline` function.We need to specify which GCP project to use for BigQuery again, and this is done by setting `--project` in `beam_pipeline_args` when creating a pipeline.> **Open `pipeline/configs.py`**. Uncomment the definition of `BIG_QUERY__WITH_DIRECT_RUNNER_BEAM_PIPELINE_ARGS` and `BIG_QUERY_QUERY`. You should replace the project id and the region value in this file with the correct values for your GCP project.> **Open `local_runner.py`**. Uncomment two arguments, `query` and `beam_pipeline_args`, for create_pipeline() method.Now the pipeline is ready to use BigQuery as an example source. Update the pipeline and create a run as we did in step 5 and 6.<jupyter_code>!tfx pipeline update --engine=local --pipeline_path=local_runner.py
!tfx run create --engine local --pipeline_name {PIPELINE_NAME}<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08422310162024939, 'fraction_numerical': 0.0034346300306130066, 'mean_word_length': 5.38417540514776, 'pattern_counts': {'":': 0, '<': 61, '<?xml version=': 0, '>': 71, 'https://': 7, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '171028', 'license': 'Apache-2.0', 'n_tokens_mistral': 3703, 'n_tokens_neox': 3642, 'n_words': 1574, 'path': 'docs/tutorials/tfx/template_local.ipynb', 'repo_name': 'UsharaniPagadala/tfx', 'size': '13393'}