Tuesday, November 7, 2023

Supervised Learning Algorithms - Tree and Ensemble

Decision Trees

  • Data analysis - ask series of questions to narrow down on the label (Color? Brown; Has wings? Yes; Answer - Bird)
  • Splits - the goal is to:
    • Minimize the number of splits thus making the tree max efficient
    • Maximize Information Gain (IG) at each split (i.e. ask the right questions)
      • Impurity - how heavily the data across multiple classes is mixed
      • IG = Decrease in impurity = Impurity(parent) - Impurity(Child)
  • Tree depth - hyperparameter; max number of splits that can occur
    • Analyze the data set - split into two according to the majority of the class present in each leaf
    • Shallow tree - can underfit the data
    • Deep tree - can overfit (i.e. every example ends up a separate leaf; introduce a lot of noise)
  • Traces the through the tree until a leaf is reached.  Then use the mean target value of the training points at that leaf as the prediction.

Regression trees

  • Instead of going by the majority, split by the mean target value of the sample (i.e. calculate the mean of the leaf constituents, make prediction based on the mean)
  • Benefits:
    • Very interpretable
    • Train quickly
    • Can handle non-linear relationships
    • No needs for scaling
  • Challenges:
    • Sensitive to depth
    • Prone to overfitting

Ensemble Models

  • Combine multiple models into a meta-model for better performance
  • Averaging multiple models - less likely to overfit if the models are independent
    • Feed full dataset (or a slice) into multiple models
    • Use Aggregation function (majority, average, weighted averaged, etc.) to determine the overall prediction based on the individual predictions of each model
  • Challenges:
    • Time / compute resources to train
    • Cost of running multiple models
    • Decrease in interpretability

Bagging

  • Bootstrap aggregation - sampling with replacement
  • Pull out a sample from a set for use in a model; replace the pulled out sample
  • Can end up pulling the same sample multiple times
  • Because each model is trained using a different data set, the results can be considered independent
  • The average of the predictions is then taken
    • Build serious of trees, then average the outputs
    • Reduces overfitting

Random Forest

  • Use bagging to train multiple trees
  • Use multiple trees and take the majority vote
  • Each member model may use a different subset of both features and observations to train
  • Decisions driving this:
    • Number of trees
    • Sampling strategy for bagging
      • Bagging samples size as % of total
      • Max number of feature represented in the bagging sample
    • Depth of trees
      • Max depth
      • Min samples per leaf

Clustering

  • Unsupervised learning technique
  • Organize data points into logical groups
  • Sort similar data points into same cluster - and different data points into another
    • Ex: dividing potential customers in groups and targeting each a specific marketing
    • Key decision - determining the basis for similarity in data

K-Means Clustering

  • Sort data based on distance from the nearest cluster center
    • Ex: data points near each other go into one cluster; far from each other - into another cluster
  • Goal - minimize the sum of distance from each data point to the center
    1. Select centers within the cluster (at random)
    2. Assign each data point to the closest data center
    3. Move the center from the original locations to the mean distance location (re-center)
    4. Repeat the above 2 and 3 until the centers are no longer moving
  • Strengths:
    • Easy to implement
    • Quick to run
    • Good point for starting to wok w clustering
  • Weakness:
    • Requires to identify how many clusters will be used ahead of time
    • Doe not work for geographically complex data

Monday, November 6, 2023

Linear Regression and Regularization

Types of Algorithms

  • Parametric algorithm (Linear model)
    • Based on a mathematical model that defines the relationship between inputs and outputs
    • Fixed and pre-determined set of parameters and coefficients
    • Can learn quickly
    • Can be too simple for real world - prone to underfitting
  • Non-Parametric algorithm
    • Does not make assumptions about relationship b/w input and output ahead of building a model
    • Flexible and adapts well to non-linear data relationships
    • Performs better than linear
    • Requires more data to train; prone to overfitting

Linear Regression

  • Linear relations b/w features and targets (input and the output that we are looking to predict), defined by set of coefficients
  • Simple, easy to interpret and see the relationship between inputs and outputs
  • Yet is a basis for many more complex models
  • Example: Home Price = # of Bedroom
  • Y = W0 + W1*X; W0 is Bias;  W1 is Coefficient/weight
  • Multiple Linear regression
    • y = W0 + W1*X1 + W2*X2 +…+Wp*Xp
    • Additional W's - ex: House Size; Location, etc.
  • Total Error of a Model
    • SSE - Cost function
      • Sum of Squared Errors - (Sum of Predictions minus Actuals) squared
    • The goal is to minimize it

Polynomial Regression

  • Non-linear relationships can be modeled as well
  • Ex: use a non-linear function to create a feature, x=X or log(x); then use it as input

Regularization

  • When a complex model does not predict well on new data
    • Add a penalty factor to the cost function to penalize feature complexity
    • This would reduce the complexity in the model and decrease the probability of overfitting thus helping the model performance
    • I.e. a coefficient per feature - the more features there are the more coefficients are added to the penalty function, which wight on the overall regression cost
    • Use another variable, lamba, to multiply the sum up the coefficients - this controls the severity of the punishment
    • Penalty factor
      • LASSO regression
        • Penalty factor is the sum of the absolute value of the coefficients, multiplied by lambda
        • Reduces the coefficients of irrelevant features to 0
        • Suitable for a simpler and more inheritable model
      • Ridge regression
        • Penalty factor is the sum of the coefficients squared, multiplied by lambda
        • Reduces them close to 0 but does not completely remove them
        • Suitable when there is complex relationship of target to many features with collinearity/correlation

Logistic Regression

  • Mainly used for classification tasks
  • Linear regression is not the best solution when an outcome of 0 or 1 is required
  • Linear regression produces an actual prediction value, not 1 or 0
  • Solution option - predict probability of p(y=1)
  • Use logistics/sigmoid function - the input for this would be the output of the linear model
  • The output of the sigmoid would be between 0 and 1; this can then be interpreted as the probability of either 0 or 1
  • Gradient descent - "an iterative first-order optimization algorithm, used to find a local minimum/maximum of a given function."
  • Use gradient descent to determine the values of the weights that minimize the cost
    • Update the values of the weights in by a small amount to move closer to the weights which minimize our loss/cost function
    • Need - a variable to use in every step called leaning rate; the gradient of the cost/loss function itself; weight values from the previous iteration
  • To visualize in a graph - iterate against the gradient slowly until reach the bottom (i.e. the minimum cost point)
  • What if there more than 1 or (two classes) - predicting multiple classes?
    • Use softmax function instead of sigmoid - it provides the probability of belonging to each class normalized to sum of 1
    • Then take the class with the highest probability value as our prediction


Sunday, November 5, 2023

Testing and Evaluation of a Model

Testing a Model

  • Divide data into
    • Training Set - build / train the model
    • Test Set - model performance evaluation set; data different from Training set
  • Need to be careful with data leakage - test data getting into model building process
  • This causes performance estimate to be overly optimistic vs. when using new data
    • Further split Training set into:
      • Training Set
      • Validation Set - use for improving the model and monitoring performance on the test set
    • And only then test using the Test set - as an unbiased exercise on a separate set of data
  • K-Folds Cross Validation
    • Another test strategy
    • Split the data into subsets ("folds")
    • Run multiple iteration of the model using a separate "fold"
    • Calculate the Error as the Average Error across K-Folds validation runs
    • This approach is industry standard as it:
      • Maximizes the use training data
      • Provides better insight into performance

Model Evaluation

  • Metrics used
    • Outcome - business impact, usually $
    • Output - model output; usually remains internal, non-customer
  • Regression Metrics:
    • MSE - Mean Squared Error
      • Most popularly used
      • Influenced by large errors (these are penalized heavily), scale of data
      • This is the model to use of concerned with minimizing large errors on outlier datapoints
    • MAE - Mean Absolute Error
      • Influenced by scale
      • Can be easier to interpret
      • Doesn’t go after outlier results as heavily as MSE
    • MAPE - Mean Absolute Percent Error
      • Converts an error to %
      • Easer understood by non-technical clientele
      • An error could be small - but when compared to the value of the target, the % could be large
    • Coefficient of Determination (R-squared)
      • Definition - the proportion of the variation in the dependent variable that is predictable from the independent variable(s)
      • Displays how much of the variability in the target variable is explained by the model
      • Totals squared deviation from mean (SST) = Sum of squares regression (SSR) + Total squared error (SSE)
      • R-squared = SSR/SST = 2- SSE/SSR
      • Usually b/w 1 and 0; the closer it is to 1, the better it explains variability in the target variable

Accuracy

  • To aim at better accuracy be careful with input data class imbalance (ex: how many days a year a healthy person is sick?)
  • Confusion Matrix - True/False Positives vs True/False Negatives
    • FPR Rate - False Positives Rate (FPR), i.e. False Positives/Total True + False Positives
    • Precision - True Positives Rate (TPR), i.e. True Positives/Total True + False Positives
  • Receiver Operating Characteristic (ROC) Curves
    • FPR and TPR across different threshold values for the given model
    • I.e. set a threshold - a prediction below the threshold is a Negative, above - Positive
    • Typical threshold is 0.5
    • Use the Positives/Negatives to generate TPR/FPR by comparing these to the actual targets
    • Re-run this across different threshold and plot TPR (y-axis) and FPR (x-axis) on a graph - ROC Curve
  • Areas Under ROC (AUROC)
    • Area under ROC Curve
    • Higher AUROC - better quality model
  • Precision Recall Curve (PR)
    • Measures Precision vs Recall values across multiple thresholds
    • Used in situations of high class imbalance (many 0's, few 1's)
    • Does not factor True Negatives

Errors

  • Common error causes:
    • Proper problem faming and metric section
    • Data quality
    • Feature selection
    • Model fit
    • Inherent error

Thursday, November 2, 2023

Building a Machine Leaning Model

 Building a Model

  • Creating a model is an interactive process:
    • Gather the data needed
    • Selection of features - collect past observations (houses for sale) and targets (sale process)
    • Choice of algorithm - template for relationship between the input and the output
    • Selection of values for hyperparameters (tuning the dials of the model to make sure it functions)
    • Selection of Loss (cost) function
    • Train the model using past data collected
    • Evaluate the performance

Feature Selection

  • Features - characteristics of the input data
  • Important to define feature - interaction of factors that:
    • Might influence the solution (years the house is build, city, neighborhood)
    • The data that we might be able to collect
  • Methods of selection:
    • Speak w experts - domain expertise
    • Collect data - Visualization
    • Past data collection =- statistical correlation
    • Collect as much as you can, but narrow down the data - Modeling

Algorithm Selection

  • Dependent on the task that needs t be solved
  • Best approach - employ different algorithms and train all
  • Criteria for algorithm selection:
    • Performance Accuracy - expected performance of the model
    • Interpretability - how easy/hard it is to interpret and predict the result of the model computation
    • Computational Efficiency - computational horsepower measure in relation to the result generation

Model Complexity

Depends on:
  • Number of Features
  • Algorithm - linear regression vs neuronetworks
  • Hyperparameter Values

Bias-Variance Trade off

  • Bias - modeling a complex problem using a simple model; the model is incapable of fully capturing the depth and underlying patterns in the data.
  • Variance - sensitivity of the module to small fluctuations in the data; ex: interpreting noise as actual patterns
Typically
  • Simpler model = higher bias; lower variance
  • Complex model = lower bias; higher variance
  • Total Error = Bias`2 + Variance + Inherent Error(noise)`2
  • Need to be careful Underfitting / Overfitting the model 

Wednesday, November 1, 2023

What is Machine Leaning?

What is Machine Leaning?

“Field of study that gives computers the ability to learn without being explicitly programmed” – Arthur Samuel, IBM, 1959

  • Machine learning - set of methods & tools which help realize the goal of the field of artificial intelligence
  • Deep learning, or the use of neural networks containing many layers - a subfield of machine learning
  • Computer vision, natural language processing, recommendation systems etc. - sub-fields of AI which rely on machine learning methods

Terminology
  • “Data are characteristics or information, usually numerical, that are collected through observation.” - OECD Glossary of Statistical Terms, https://www.oecd-ilibrary.org/economics/oecd-glossary-of-statistical-terms_9789264055087-en
  • Observations - ex: House
  • Features - ex: Neighborhood, School district, Square footage, Number of bedrooms, Year built
  • Targets - ex: Market sale price
  • Model - an approximation of the relationship between two variables: 
    • Input Var -> Model -> Output Var
    • A model needs:
      • Features - inputs
      • Algorithm - formula
      • Hyperparameter - formula tweaks
      • Loss function - to use to optimize the model

Wednesday, July 19, 2023

Snowflake on AWS - Quick Summary

 Snowflake - an SQL Compatible database:

  • Originally redeveloped on AWS, 2012-2014
  • Added other cloud providers
  • AWS's customer AND partner
  • Designed to be a cloud data warehouse - not a data lake
  • Not aimed an analytics use - doesn't have pipeline features
  • Lives on S2, Azure Blob storage
  • Virtual warehouse - doesn’t mean a w/house, just compute
  • Its own meta data store

Consists of:

  • Database Layer - Lives on S2, Azure Blob storage
  • Query Processing Layer - a virtual warehouse - doesn’t mean a w/house, just compute
  • Cloud Services Layer - its own meta data store


Key features:

  • Multi-tenant - all customers live in the snowflake VPC
  • Not available in EVERY region for EVERY cloud provider
  • Data resides in .fdn format - proprietary, columnar, micro-partitions
  • Any data loaded - get converted into this format; gets split into columnar micro-partitions
  • This is done for query optimization purposes - to scan on related portions and get results faster
  • Multiple Editions: Standard, Enterprise, Business Critical, Virtual Private Snowflake
  • Higher level editions include all feature of the lower
  • Pay As You go on demand - credits; there are discounts for pay-upfront
  • Storage - temp tables, transient, permanent - incur cost
  • Credits are T-Shirt sized according to the size of DB - M, XL, etc.

Thursday, November 25, 2021

Snowflake on AWS - load data from S3


  • On AWS: Create IAM User Group and a User for a dedicated Snowflake user
  • Create a User Role granting it AmazonS3FullAccess policy and a trust entity of “Another AWS account”. Use the root account ID in “Specify accounts that can use this role”. Select “Require external ID” and temporarily set External ID an arbitrary value (any).

create or replace storage integration s3_integr

  type = external_stage

  storage_provider = s3

  enabled = true

  storage_aws_role_arn = '<ARN of the AWS role created above>'

  storage_allowed_locations = ('s3://<Path to the data file folder on S3>');

  • Run the command to describe the integration

DESC INTEGRATION s3_integr;

  • Extract STORAGE_AWS_IAM_USER_ARN and STORAGE_AWS_EXTERNAL_ID values from the output and include these in the trust relationship JSON of the Snowflake user role (on AWS IAM):

{

  "Version": "2012-10-17",

  "Statement": [

    {

      "Effect": "Allow",

      "Principal": {

        "AWS": "<STORAGE_AWS_IAM_USER_ARN here>"

      },

      "Action": "sts:AssumeRole",

      "Condition": {

        "StringEquals": {

          "sts:ExternalId": "<STORAGE_AWS_EXTERNAL_ID here>

        }

      }

    }

  ]

}

  • Crate a new database

CREATE or replace DATABASE CUSTOM_DB;

  • To manually load the data - follow the steps immediately below. For continuous data load with Snowpipe scroll further down.

Loading CSV data

  create or replace file format custom_db.public.csv_format

                    type = csv

                    skip_header = 1

                    null_if = ('NULL', 'null')

                    empty_field_as_null = true;

create or replace stage custom_db.public.ext_csv_stage

  URL = ' s3://<Path to the csv file/folder on S3>'

  STORAGE_INTEGRATION = s3_integr

  file_format = custom_db.public.csv_format;    

  • Once loaded – the stage and file format is visible under Databases->CUSTOM_DB->Stages/File Formats. Can use Grant Privileges to share these. 

CREATE or replace TABLE CUSTOM_DATA_CSV(

     CUSTOM_FIELD_1    NUMBER(38,6) 

   , CUSTOM_FIELD_2    NUMBER(38,6) 

   , CUSTOM_FIELD_3    VARCHAR(256) 

   , CUSTOM_FIELD_4    NUMBER(38,1) 

   , CUSTOM_FIELD_5    VARCHAR(256) 

   , CUSTOM_FIELD_6    VARCHAR(128)

   , CUSTOM_FIELD_7    NUMBER(38,8) 

);

copy into CUSTOM_DATA_CSV

from @custom_db.public.ext_csv_stage

on_error = CONTINUE;



Loading PARQUET data

  • Create a file format for PARQUET data import

create or replace file format custom_db.public.parquet_format

  type = 'parquet';

create or replace stage custom_db.public.ext_parquet_stage

  URL = ' s3://<Path to the parquet file/folder on S3>'

  STORAGE_INTEGRATION = s3_integr

  file_format = custom.public.parquet_format;

  • Crate a new custom table for parquet data

CREATE or replace TABLE CUSTOM_DATA_PARQUET(

     CUSTOM_FIELD_1    VARCHAR(150)

   , CUSTOM_FIELD_2    VARCHAR(150)

   , CUSTOM_FIELD_3    VARCHAR(150)

   , CUSTOM_FIELD_4    VARCHAR(150)

   , CUSTOM_FIELD_5    VARCHAR(150)

   , CUSTOM_FIELD_6    VARCHAR(150)

   , CUSTOM_FIELD_7    VARCHAR(150)

   ,filename           VARCHAR

   ,file_row_number    VARCHAR

   ,load_timestamp timestamp default TO_TIMESTAMP_NTZ(current_timestamp)

);

  • Ingest data from S3

copy into custom_db.public.custom_data_parquet

from (select

$1: parquet_custom_field_1::varchar,

$1: parquet_custom_field_2::varchar,

$1: parquet_custom_field_3::varchar,

$1: parquet_custom_field_4::varchar,

$1: parquet_custom_field_5::varchar,

$1: parquet_custom_field_6::varchar,

$1:"Optionally_exact_spelling_of_fieldname_from_parquet_in_double_quotes"::varchar,

METADATA$FILENAME,

METADATA$FILE_ROW_NUMBER,

TO_TIMESTAMP_NTZ(current_timestamp)

from @custom_db.public.ext_parquet_stage);

Loading JSON data

  • Create a file format for JSON data import

create or replace file format custom_db.public.json_format

  type = 'json';

create or replace stage custom_db.public.ext_json_stage

  URL = ' s3://<Path to the JSON file/folder on S3>'

  STORAGE_INTEGRATION = s3_integr

  file_format = custom.public.json_format;

  • Create a new custom table for parquet data

CREATE or replace TABLE CUSTOM_DATA_JSON(

    id VARCHAR(50)

   , CUSTOM_FIELD_1    VARCHAR(150)

   , CUSTOM_FIELD_2    VARCHAR(150)

   , CUSTOM_FIELD_3    INTEGER

   , CUSTOM_FIELD_4    FLOAT

   , CUSTOM_FIELD_5    VARCHAR(150)

   , CUSTOM_FIELD_6    VARCHAR(128)

   , CUSTOM_FIELD_7    VARCHAR(128)

   ,filename    VARCHAR

   ,file_row_number VARCHAR

   ,load_timestamp timestamp default TO_TIMESTAMP_NTZ(current_timestamp)

);

  • Ingest data from S3. Using case-sensitive field names that match the exact JSON construct content – including trailing spaces, etc.

copy into custom_db.public.custom_data_json

from (select

$1:"_id"::varchar,

$1:" Custom Field 1 "::varchar,

$1:" Custom Field 2 "::varchar,

$1:" Custom Field 3 "::integer,

$1:" Custom Field 4 "::float,

$1:" Custom Field 5 "::varchar,

$1:" Custom Field 6 "::varchar,

$1:" Custom Field 7 "::varchar,

METADATA$FILENAME,

METADATA$FILE_ROW_NUMBER,

TO_TIMESTAMP_NTZ(current_timestamp)

from @custom_db.public.ext_json_stage);


Snowpipe

  • https://docs.snowflake.com/en/user-guide/data-load-snowpipe-intro.html#data-duplication
  • Serverless data load mechanism
  • Enables loading data from files as soon as they’re available in a stage. 
  • Leverages event notifications (ex: AWS SQS) for cloud storage to inform Snowpipe of the arrival of new data files to load. A dedicated COPY statement identifies the source location of the data files (i.e., a stage) and a target table. The user is billed for the compute each load consumes
Loading CSV file(s) data
  • Similar to the manual load, steps to create storage integration, TABLE, csv file format and stage are required
  • Same commands as above can be re-used making sure that URL parameter in stage definition points to the S3 folder where csv files will be dropped. Re-running integration command can re-generate STORAGE_AWS_IAM_USER_ARN and STORAGE_AWS_EXTERNAL_ID. Make sure that User Role Trusl relationship is updated accordingly
  • Define the actual pipe. Note that this contains the exact same copy command as used for manual loads

create or replace pipe custom_db.public.myawesomepipe auto_ingest=true as

copy into custom_data_csv

from @custom_db.public.ext_csv_stage

on_error = CONTINUE;

  • Run the show command to display the list of created pipes. Locate the newly created pipe and extract the value of "notification_channel" column. This is the ARN of the SQS topic that the pipe will use. 

show pipes;

  • Copy this value into S3->Bucket that the data files will be uploaded into->Properties-Event notifications. Create new event notification with destination of SQS Queue and supply the ARN copied from the Snowflake show pipe output.
Loading PARQUET file(s) data
  • The steps are very much similar to the above CSV pipeline and manual PARQUET load examples
  • Ensure that the stage defined during the manual PARQUET load above contains the URL of the folder and not the individual file
  • Same commands as above can be re-used. Making sure that URL parameter in stage definition points to the location (folder?) withing the bucket where parquet files will be uploaded into.
  • Create a snowpipe definition - or update an existing one using create or replace pipe followed by the same copy command used to manually load the parquet files

create or replace pipe custom_db.public.myawesomepipe auto_ingest=true as

copy into custom_db.public.custom_data_parquet

from (select

$1: parquet_custom_field_1::varchar,

$1: parquet_custom_field_2::varchar,

$1: parquet_custom_field_3::varchar,

$1: parquet_custom_field_4::varchar,

$1: parquet_custom_field_5::varchar,

$1: parquet_custom_field_6::varchar,

$1:"Optionally_exact_spelling_of_fieldname_from_parquet_in_double_quotes"::varchar,

METADATA$FILENAME,

METADATA$FILE_ROW_NUMBER,

TO_TIMESTAMP_NTZ(current_timestamp)

from @custom_db.public.ext_parquet_stage);

  • The SQS queue ARN will remain unchanged from what was generated in the above CVS pipe run. If this is the first time a Snowpipe is defined, see steps above on copying updating the Event notifications on the S3 bucket.
Loading JSON file(s) data
  • Similar to parquet and CSV steps, JSON can be loaded using the combination create or replace pipe and the copy into from the manual CSV load.
  • Need to make sure the table, file format and stage are defined correctly