#!/usr/bin/env python # coding: utf-8 # >### 🚩 *Create a free WhyLabs account to get more value out of whylogs!*
# >*Did you know you can store, visualize, and monitor whylogs profiles with the [WhyLabs Observability Platform](https://whylabs.ai/whylogs-free-signup?utm_source=whylogs-Github&utm_medium=whylogs-example&utm_campaign=Segments)? Sign up for a [free WhyLabs account](https://whylabs.ai/whylogs-free-signup?utm_source=whylogs-Github&utm_medium=whylogs-example&utm_campaign=Segments) to leverage the power of whylogs and WhyLabs together!* # # Intro to Segmentation # [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/whylabs/whylogs/blob/mainline/python/examples/advanced/Segments.ipynb) # Sometimes, certain subgroups of data can behave very differently from the overall dataset. When monitoring the health of a dataset, it’s often helpful to have visibility at the sub-group level to better understand how these subgroups are contributing to trends in the overall dataset. whylogs supports data segmentation for this purpose. # # Data segmentation is done at the point of profiling a dataset. # # Segmentation can be done by a single feature or by multiple features simultaneously. For example, you could have different profiles according to the gender of your dataset ("M" or "F"), and also for different combinations of, let's say, Gender and City Code. You can also further filter the segments for specific partitions you are interested in - let's say, Gender "M" with age above 18. # # In this example, we will show you a number of ways you can segment your data, and also how you can write these profiles to different locations. # ## Table of Content # # 1. Segmenting on a single column # 2. Segmenting on multiple columns # 3. Filtering Segments # 4. Writing Segmented Results to Disk # 5. Sending Segmented Results to WhyLabs # ## Installing whylogs # If you don't have it installed already, install whylogs: # In[ ]: # Note: you may need to restart the kernel to use updated packages. get_ipython().run_line_magic('pip', 'install whylogs') # ## Getting the Data & Defining the Segments # Let's first download the data we'll be working with. # # This dataset contains transaction information for an online grocery store, such as: # # - product description # - category # - user rating # - market price # - number of items sold last week # In[1]: import pandas as pd url = "https://whylabs-public.s3.us-west-2.amazonaws.com/whylogs_examples/Ecommerce/baseline_dataset_base.csv" df = pd.read_csv(url)[["date","product","category", "rating", "market_price","sales_last_week"]] df['rating'] = df['rating'].astype(int) df.head() # # ## Segmenting on a Single Column # It looks like the `category` feature is a good one to segment on. Let's see how many categories there are for the complete dataset: # In[2]: df['category'].value_counts() # There are 11 categories. # # We might be interested in having access to metrics specific to each category, so let's generate segmented profiles for each category. # In[3]: from whylogs.core.segmentation_partition import segment_on_column column_segments = segment_on_column("category") # In[4]: column_segments # `column_segments` is a dictionary for different SegmentationPartition, with informations such as id and additional logic. For the moment, all we're interested in is that we can pass it to our `DatasetSchema` in order to generate segmented profiles while logging: # In[5]: import whylogs as why from whylogs.core.schema import DatasetSchema results = why.log(df, schema=DatasetSchema(segments=column_segments)) # Since we had 11 different categories, we can expect the `results` to have 11 segments. Let's make sure that is the case: # In[6]: print(f"After profiling the result set has: {results.count} segments") # Great. # # Now, let's visualize the metrics for a single segment (the first one). # # Results can have multiple partitions, and each partition can have multiple segments. Segments within a partition are non-overlapping. Segments across partitions, however, might overlap. # # In this example, we have only one partition with 11 non-overlapping segments. Let's fetch the available segments: # Now, let's visualize the metrics for the first segment: # In[14]: first_segment = results.segments()[0] segmented_profile = results.profile(first_segment) print("Profile view for segment {}".format(first_segment.key)) segmented_profile.view().to_pandas() # We can see that the first segment is for product transactions of the `Baby Care` category, and we have 707 rows for that particular segment. # ## Segmenting on More than one Column # # # We might also be interested in segmenting based on more than one segment. # # Let's say we are interested in generating profiles for every combination of `category` and `rating`. That way, we can inspect the metrics for, let's say, for `Beverages` with `rating` of 5. # In[9]: df['rating'].value_counts() # This time, we'll use `SegmentationPartition` to create the partition: # In[10]: from whylogs.core.segmentation_partition import ( ColumnMapperFunction, SegmentationPartition, ) segmentation_partition = SegmentationPartition( name="category,rating", mapper=ColumnMapperFunction(col_names=["category", "rating"]) ) # Let's create our dictionary with the only partition we have: # In[11]: multi_column_segments = {segmentation_partition.name: segmentation_partition} results = why.log(df, schema=DatasetSchema(segments=multi_column_segments)) print(f"After profiling the result set has: {results.count} segments") # Again, let's check the first segment: # In[12]: partition = results.partitions[0] segments = results.segments_in_partition(partition) first_segment = next(iter(segments)) segmented_profile = results.profile(first_segment) print("Profile view for segment {}".format(first_segment.key)) segmented_profile.view().to_pandas() # The first segment is now for transactions of __Baby Care__ category with rating of __3__. There are 162 records for this specific segment. # ## Filtering the Segments # You can further select data in a partition by using a `SegmentFilter`. # # Let's say you are interested only in the `Baby Care` category. Instead of generating all 11 segmented features, you can specify a __SegmentFilter__ to get only one segment. # # We can do so by specifying a __filter function__ to the __filter__ property of the Partition: # In[13]: from whylogs.core.segmentation_partition import segment_on_column from whylogs.core.segmentation_partition import SegmentFilter column_segments = segment_on_column("category") column_segments['category'].filter = SegmentFilter(filter_function=lambda df: df.category=='Baby Care') # We're passing a simple lambda function here, but you can define more complex scenarios by passing any Callable to it. # Now, we just repeat the logging process: # In[14]: import whylogs as why from whylogs.core.schema import DatasetSchema results = why.log(df, schema=DatasetSchema(segments=column_segments)) print(f"After profiling the result set has: {results.count} segments") # We can see that now we have only 1 segment. # ### Filtering on other columns # You don't need to filter on the same category you're segmenting on. In fact, you can use multiple columns to get very specific slices of interest for your data. # # Unlike segmenting on multiple columns, with filtering you don't need to get the segments for the complete cartesian product of your rules. This avoids combinatorial explosions for cases when you are interested in a very specific slice of your data, and are not particularly interested in all possible group combinations. # # Let's say high-quality, high-cost products are key to a certain promotion you want to release. You can create segments based on `category`, just as before, and can further filter it to track only data for your defined rule. # # The only difference between this case and the previous one is the lambda function provided, but for reproducibility let's repeat the whole code again: # In[23]: from whylogs.core.segmentation_partition import segment_on_column from whylogs.core.segmentation_partition import SegmentFilter import whylogs as why from whylogs.core.schema import DatasetSchema column_segments = segment_on_column("category") column_segments['category'].filter = SegmentFilter(filter_function=lambda df: (df.market_price>200) & (df.rating > 3)) results = why.log(df, schema=DatasetSchema(segments=column_segments)) partition = results.partitions[0] segments = results.segments_in_partition(partition) first_segment = next(iter(segments)) segmented_profile = results.profile(first_segment) print("Profile view for segment {}".format(first_segment.key)) segmented_profile.view().to_pandas() # Notice that we now have a count of 389, whereas our first example had a count of 707. That's because now we're filtering the data to track only points that match our rule for high-quality, high-cost products. # ## Writing the Segments to Disk # Once you have the segmented results, you can use the results' `writer` method to write it to disk, for example: # In[24]: import os directory = "segmented_profiles" if not os.path.exists(directory): os.makedirs(directory) results.writer().option(base_dir=directory).write() # This will write 11 binary profiles to the specified folder. Let's check with `listdir`: # In[18]: os.listdir(directory) # ## Sending Segmented Profiles to WhyLabs # With the whylogs Writer, you can write your profiles to different locations. If you have a WhyLabs account, you can easily send your segmented profiles to be monitored in your dashboard. # # We will show briefly how to do it in this example. If you want more details, please check the [WhyLabs Writer Example](../integrations/writers/Writing_to_WhyLabs.ipynb) (also available [in our documentation](https://whylogs.readthedocs.io/en/latest/examples/integrations/writers/Writing_to_WhyLabs.html)). # Provided you already have the required information and keys, let's first set our environment variables: # In[18]: import getpass import os # set your org-id here - should be something like "org-xxxx" print("Enter your WhyLabs Org ID") os.environ["WHYLABS_DEFAULT_ORG_ID"] = input() # set your datased_id (or model_id) here - should be something like "model-xxxx" print("Enter your WhyLabs Dataset ID") os.environ["WHYLABS_DEFAULT_DATASET_ID"] = input() # set your API key here print("Enter your WhyLabs API key") os.environ["WHYLABS_API_KEY"] = getpass.getpass() print("Using API Key ID: ", os.environ["WHYLABS_API_KEY"][0:10]) # Then, it's as simple as calling `writer("whylabs")`: # In[ ]: results.writer("whylabs").write() # You should be able to see your segments at your dashboard at the __segments__ tab: # ![alt text](images/whylabs_segments.png)