<jupyter_start><jupyter_text>Validating Historical Features with Great Expectations ![Validating Historical Features with Great Expectations](./dqm-diagram-1.png) In this tutorial, we will use the public dataset of Chicago taxi trips to present data validation capabilities of Feast. The original dataset is stored in BigQuery and consists of raw data for each taxi trip (one row per trip) since 2013. We will generate several training datasets (aka historical features in Feast) for different periods and evaluate expectations made on one dataset against another. Our features will represent aggregations of raw data with daily intervals (eg, trips per day, average fare or speed for a specific day, etc.). We will craft some features using SQL while pulling data from BigQuery (like total trips time or total miles travelled). Another chunk of features will be implemented using Feast's on-demand transformations - features calculated on the fly when requested. Our plan:0. Prepare environment1. Pull data from BigQuery (optional)2. Declare & apply features and feature views in Feast3. Generate reference dataset4. Develop & test profiler function5. Run validation on different dataset using reference dataset & profiler  0. Setup Install Feast Python SDK and great expectations:<jupyter_code>!pip install 'feast[ge]'<jupyter_output><empty_output><jupyter_text>1. Dataset preparation (Optional)  **You can skip this step if you don't have GCP account. Please use parquet files that are coming with this tutorial instead**<jupyter_code>!pip install google-cloud-bigquery
import pyarrow.parquet

from google.cloud.bigquery import Client
bq_client = Client(project='kf-feast')<jupyter_output>/Users/pyalex/projects/feast/venv/lib/python3.7/site-packages/google/auth/_default.py:70: UserWarning: Your application has authenticated using end user credentials from Google Cloud SDK without a quota project. You might receive a "quota exceeded" or "API not enabled" error. We recommend you rerun `gcloud auth application-default login` and make sure a quota project is added. Or you can use service accounts instead. For more information about service accounts, see https://cloud.google.com/docs/authentication/
  warnings.warn(_CLOUD_SDK_CREDENTIALS_WARNING)<jupyter_text>Running some basic aggregations while pulling data from BigQuery. Grouping by taxi_id and day:<jupyter_code>data_query = """SELECT 
    taxi_id,
    TIMESTAMP_TRUNC(trip_start_timestamp, DAY) as day,
    SUM(trip_miles) as total_miles_travelled,
    SUM(trip_seconds) as total_trip_seconds,
    SUM(fare) as total_earned,
    COUNT(*) as trip_count
FROM `bigquery-public-data.chicago_taxi_trips.taxi_trips` 
WHERE 
    trip_miles > 0 AND trip_seconds > 60 AND
    trip_start_timestamp BETWEEN '2019-01-01' and '2020-12-31' AND
    trip_total < 1000
GROUP BY taxi_id, TIMESTAMP_TRUNC(trip_start_timestamp, DAY)"""
driver_stats_table = bq_client.query(data_query).to_arrow()

# Storing resulting dataset into parquet file
pyarrow.parquet.write_table(driver_stats_table, "trips_stats.parquet")
def entities_query(year):
    return f"""SELECT
    distinct taxi_id
FROM `bigquery-public-data.chicago_taxi_trips.taxi_trips` 
WHERE
    trip_miles > 0 AND trip_seconds > 0 AND
    trip_start_timestamp BETWEEN '{year}-01-01' and '{year}-12-31'
"""
entities_2019_table = bq_client.query(entities_query(2019)).to_arrow()

# Storing entities (taxi ids) into parquet file
pyarrow.parquet.write_table(entities_2019_table, "entities.parquet")
#entities_2020_table = bq_client.query(entities_query(2020)).to_arrow()
#pyarrow.parquet.write_table(entities_2019_table, "entities_2020.parquet")<jupyter_output><empty_output><jupyter_text>2. Declaring features<jupyter_code>import pyarrow.parquet
import pandas as pd

from feast import Feature, FeatureView, Entity, FeatureStore
from feast.value_type import ValueType
from feast.data_format import ParquetFormat
from feast.on_demand_feature_view import on_demand_feature_view
from feast.infra.offline_stores.file_source import FileSource
from feast.infra.offline_stores.file import SavedDatasetFileStorage

from google.protobuf.duration_pb2 import Duration
batch_source = FileSource(
    event_timestamp_column="day",
    path="trips_stats.parquet",  # using parquet file that we created on previous step
    file_format=ParquetFormat()
)
taxi_entity = Entity(name='taxi', join_key='taxi_id')
trips_stats_fv = FeatureView(
    name='trip_stats',
    entities=['taxi'],
    features=[
        Feature("total_miles_travelled", ValueType.DOUBLE),
        Feature("total_trip_seconds", ValueType.DOUBLE),
        Feature("total_earned", ValueType.DOUBLE),
        Feature("trip_count", ValueType.INT64),
        
    ],
    ttl=Duration(seconds=86400),
    batch_source=batch_source,
)<jupyter_output><empty_output><jupyter_text>*Read more about feature views in [Feast docs](https://docs.feast.dev/getting-started/concepts/feature-view)*<jupyter_code>@on_demand_feature_view(
    features=[
        Feature("avg_fare", ValueType.DOUBLE),
        Feature("avg_speed", ValueType.DOUBLE),
        Feature("avg_trip_seconds", ValueType.DOUBLE),
        Feature("earned_per_hour", ValueType.DOUBLE),
    ],
    inputs={
        "stats": trips_stats_fv
    }
)
def on_demand_stats(inp):
    out = pd.DataFrame()
    out["avg_fare"] = inp["total_earned"] / inp["trip_count"]
    out["avg_speed"] = 3600 * inp["total_miles_travelled"] / inp["total_trip_seconds"]
    out["avg_trip_seconds"] = inp["total_trip_seconds"] / inp["trip_count"]
    out["earned_per_hour"] = 3600 * inp["total_earned"] / inp["total_trip_seconds"]
    return out<jupyter_output><empty_output><jupyter_text>*Read more about on demand feature views [here](https://docs.feast.dev/reference/alpha-on-demand-feature-view)*<jupyter_code>store = FeatureStore(".")  # using feature_store.yaml that stored in the same directory
store.apply([taxi_entity, trips_stats_fv, on_demand_stats])  # writing to the registry<jupyter_output><empty_output><jupyter_text>3. Generating training (reference) dataset<jupyter_code>taxi_ids = pyarrow.parquet.read_table("entities.parquet").to_pandas()<jupyter_output><empty_output><jupyter_text>Generating range of timestamps with daily frequency:<jupyter_code>timestamps = pd.DataFrame()
timestamps["event_timestamp"] = pd.date_range("2019-06-01", "2019-07-01", freq='D')<jupyter_output><empty_output><jupyter_text>Cross merge (aka relation multiplication) produces entity dataframe with each taxi_id repeated for each timestamp:<jupyter_code>entity_df = pd.merge(taxi_ids, timestamps, how='cross')
entity_df<jupyter_output><empty_output><jupyter_text>Retriving historical features for resulting entity dataframe and persisting output as a saved dataset:<jupyter_code>job = store.get_historical_features(
    entity_df=entity_df,
    features=[
        "trip_stats:total_miles_travelled",
        "trip_stats:total_trip_seconds",
        "trip_stats:total_earned",
        "trip_stats:trip_count",
        "on_demand_stats:avg_fare",
        "on_demand_stats:avg_trip_seconds",
        "on_demand_stats:avg_speed",
        "on_demand_stats:earned_per_hour",
    ]
)

store.create_saved_dataset(
    from_=job,
    name='my_training_ds',
    storage=SavedDatasetFileStorage(path='my_training_ds.parquet')
)<jupyter_output>/Users/pyalex/projects/feast/sdk/python/feast/feature_store.py:853: RuntimeWarning: Saving dataset is an experimental feature. This API is unstable and it could and most probably will be changed in the future. We do not guarantee that future changes will maintain backward compatibility.
  RuntimeWarning,<jupyter_text>4. Developing dataset profiler Dataset profiler is a function that accepts dataset and generates set of its characteristics. This charasteristics will be then used to evaluate (validate) next datasets. **Important: datasets are not compared to each other! Feast use a reference dataset and a profiler function to generate a reference profile. This profile will be then used during validation of the tested dataset.**<jupyter_code>import numpy as np

from feast.dqm.profilers.ge_profiler import ge_profiler

from great_expectations.core.expectation_suite import ExpectationSuite
from great_expectations.dataset import PandasDataset<jupyter_output>02/02/2022 02:43:45 PM WARNING:/Users/pyalex/projects/feast/venv/lib/python3.7/site-packages/great_expectations/render/view/view.py:116: DeprecationWarning: 'contextfilter' is renamed to 'pass_context', the old name will be removed in Jinja 3.1.
  def add_data_context_id_to_url(self, jinja_context, url, add_datetime=True):<jupyter_text>Loading saved dataset first and exploring the data:<jupyter_code>ds = store.get_saved_dataset('my_training_ds')
ds.to_df()<jupyter_output>/Users/pyalex/projects/feast/sdk/python/feast/feature_store.py:904: RuntimeWarning: Retrieving datasets is an experimental feature. This API is unstable and it could and most probably will be changed in the future. We do not guarantee that future changes will maintain backward compatibility.
  RuntimeWarning,<jupyter_text>Feast uses [Great Expectations](https://docs.greatexpectations.io/docs/) as a validation engine and [ExpectationSuite](https://legacy.docs.greatexpectations.io/en/latest/autoapi/great_expectations/core/expectation_suite/index.htmlgreat_expectations.core.expectation_suite.ExpectationSuite) as a dataset's profile. Hence, we need to develop a function that will generate ExpectationSuite. This function will receive instance of [PandasDataset](https://legacy.docs.greatexpectations.io/en/latest/autoapi/great_expectations/dataset/index.html?highlight=pandasdatasetgreat_expectations.dataset.PandasDataset) (wrapper around pandas.DataFrame) so we can utilize both Pandas DataFrame API and some helper functions from PandasDataset during profiling.<jupyter_code>DELTA = 0.1  # controlling allowed window in fraction of the value on scale [0, 1]

@ge_profiler
def stats_profiler(ds: PandasDataset) -> ExpectationSuite:
    # simple checks on data consistency
    ds.expect_column_values_to_be_between(
        "avg_speed",
        min_value=0,
        max_value=60,
        mostly=0.99  # allow some outliers
    )
    
    ds.expect_column_values_to_be_between(
        "total_miles_travelled",
        min_value=0,
        max_value=500,
        mostly=0.99  # allow some outliers
    )
    
    # expectation of means based on observed values
    observed_mean = ds.trip_count.mean()
    ds.expect_column_mean_to_be_between("trip_count",
                                        min_value=observed_mean * (1 - DELTA),
                                        max_value=observed_mean * (1 + DELTA))
    
    observed_mean = ds.earned_per_hour.mean()
    ds.expect_column_mean_to_be_between("earned_per_hour",
                                        min_value=observed_mean * (1 - DELTA),
                                        max_value=observed_mean * (1 + DELTA))
    
    
    # expectation of quantiles
    qs = [0.5, 0.75, 0.9, 0.95]
    observed_quantiles = ds.avg_fare.quantile(qs)
    
    ds.expect_column_quantile_values_to_be_between(
        "avg_fare",
        quantile_ranges={
            "quantiles": qs,
            "value_ranges": [[None, max_value] for max_value in observed_quantiles]
        })                                     
    
    return ds.get_expectation_suite()<jupyter_output><empty_output><jupyter_text>Testing our profiler function:<jupyter_code>ds.get_profile(profiler=stats_profiler)<jupyter_output>02/02/2022 02:43:47 PM INFO:	5 expectation(s) included in expectation_suite. result_format settings filtered.<jupyter_text>**Verify that all expectations that we coded in our profiler are present here. Otherwise (if you can't find some expectations) it means that it failed to pass on the reference dataset (do it silently is default behavior of Great Expectations).** Now we can create validation reference from dataset and profiler function:<jupyter_code>validation_reference = ds.as_reference(profiler=stats_profiler)<jupyter_output><empty_output><jupyter_text>and test it against our existing retrieval job<jupyter_code>_ = job.to_df(validation_reference=validation_reference)<jupyter_output>/Users/pyalex/projects/feast/sdk/python/feast/infra/offline_stores/offline_store.py:93: RuntimeWarning: Dataset validation is an experimental feature. This API is unstable and it could and most probably will be changed in the future. We do not guarantee that future changes will maintain backward compatibility.
  RuntimeWarning,
02/02/2022 02:43:52 PM INFO:	5 expectation(s) included in expectation_suite. result_format settings filtered.
02/02/2022 02:43:53 PM INFO:Validating data_asset_name None with expectation_suite_name default<jupyter_text>Validation successfully passed as no exception were raised.  5. Validating new historical retrieval  Creating new timestamps for Dec 2020:<jupyter_code>from feast.dqm.errors import ValidationFailed
timestamps = pd.DataFrame()
timestamps["event_timestamp"] = pd.date_range("2020-12-01", "2020-12-07", freq='D')
entity_df = pd.merge(taxi_ids, timestamps, how='cross')
entity_df
job = store.get_historical_features(
    entity_df=entity_df,
    features=[
        "trip_stats:total_miles_travelled",
        "trip_stats:total_trip_seconds",
        "trip_stats:total_earned",
        "trip_stats:trip_count",
        "on_demand_stats:avg_fare",
        "on_demand_stats:avg_trip_seconds",
        "on_demand_stats:avg_speed",
        "on_demand_stats:earned_per_hour",
    ]
)<jupyter_output><empty_output><jupyter_text>Execute retrieval job with validation reference:<jupyter_code>try:
    df = job.to_df(validation_reference=validation_reference)
except ValidationFailed as exc:
    print(exc.validation_report)<jupyter_output>/Users/pyalex/projects/feast/sdk/python/feast/infra/offline_stores/offline_store.py:93: RuntimeWarning: Dataset validation is an experimental feature. This API is unstable and it could and most probably will be changed in the future. We do not guarantee that future changes will maintain backward compatibility.
  RuntimeWarning,
02/02/2022 02:43:58 PM INFO:	5 expectation(s) included in expectation_suite. result_format settings filtered.
02/02/2022 02:43:59 PM INFO:Validating data_asset_name None with expectation_suite_name default
{'fraction_non_alphanumeric': 0.08453262540170463, 'fraction_numerical': 0.018792790275254996, 'mean_word_length': 5.0579771476936095, 'pattern_counts': {'":': 3, '<': 67, '<?xml version=': 0, '>': 71, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '18', 'dir': 'jupyter-structured-clean-dedup', 'id': '325096', 'license': 'Apache-2.0', 'n_tokens_mistral': 4540, 'n_tokens_neox': 4271, 'n_words': 1131, 'path': 'validating-historical-features.ipynb', 'repo_name': 'feast-dev/dqm-tutorial', 'size': '14314'}