5 篇来自 towardsdatascience.com

towardsdatascience.com

005

How Transformers Work

Transformers were developed to solve the problem of sequence transduction, or neural machine translation. That means any task that transforms an input sequence to an output sequence.

Recurrent Neural Networks (RNNs) and Convolutional Neural Networks (CNNs) have been used to deal with this problem because of their properties.

Recurrent Neural Networks

Recurrent Neural Networks have loops in them, allowing information to persist.

a

A Recurrent Neural Network can be thought of as multiple copies of the same network, A, each network passing a message to a successor.

recurrent neural networks are clearly related to sequences and lists.

Long-Short Term Memory (LSTM)

The problem with LSTMs

Attention

Convolutional Neural Networks

Transformers

Self-Attention

Self-Attention

Multihead attention

Positional Encoding

Overview

阅读原文 永久链接

004

How to set the Minimum Detectable Effect in AB-Tests

What does the Minimum Detectable Effect mean?

The MDE is necessary to calculate the minimum required sample size, which is the number of observations that have to be collected. An AB-Test’s results must not be analyzed before this threshold has been reached.

The MDE is the minimum effect size that should be detected with a certain probability.

Why the MDE matters

If you wanted to prove that the quality of 50% of the screws being produced was below standards, how many screws would you examine before drawing a conclusion? Probably less than if you wanted to prove that 2% of the screws are low quality.

The smaller the effect we’re interested in, the more samples we need to collect before drawing any conclusions.

Controlling Risk and Costs with the MDE

In some cases, having a very low MDE can thus be a waste of money and time. Imagine a product team is testing a very promising MVP on a marketplace website. Implementing the change is risky and would cost months of development work but could lead to a massive increase in user conversion. In this case, the team would need an uplift in the conversion rate of at least 5% to justify the costs. Setting a significantly lower MDE would thus not be necessary for the underlying cause and prolong the test unnecessarily (the test would be overpowered).

At the same time, we need to ensure that the AB-Test has the right statistical set up to detect an effect if there exists one. Let’s assume we conduct an experiment where we change the copy on our website’s Buy Now-button to increase the conversion rate. We only power our test to detect an increase in conversion rate by at least 50% with a certain probability. In this case, the test would be very likely not to deliver any significant results even if the change had a positive effect. We might wrongly conclude that the change doesn’t make a difference and decide to continue using the old copy (in this case, one speaks of underpowered tests).

Setting an appropriate MDE

MDE highly depends on the use case.

Your minimum MDE should be the smallest effect that would justify implementing the change that is being tested.

come up with an exact number? It comes down to a simple ROI calculation. Consider the following (very simplified) situation:

  • A team is validating an MVP to make users add travel insurance to their purchase on a travel website’s checkout.
  • The website registers 2000 bookings per day (730.000 per year).
  • The estimated net profit for insurance is 3$ per user.
  • Implementing the full feature would cost the team ca. 150 developer hours with, let’s say 500$ per hour, totaling up to 75.000$ (not considering any opportunity costs).

On a yearly basis, the website would have to sell 25.000 insurances to break even, equalling 3.42% of bookings adding insurance.

With the insurance conversion rate being the primary metric for the experiment, 3.42% would be a reasonable MDE. Any value lower than this would not be of interest to the team and would unnecessarily prolong the test’s duration.

阅读原文 永久链接

003

Fundamentals Of Statistics For Data Scientists and Analysts

Random Variables

a Random Variable is a way to map the outcomes of random processes, such as flipping a coin or rolling a dice, to numbers. For instance, we can define the random process of flipping a coin by random variable X which takes a value 1 if the outcome if heads and 0 if the outcome is tails.

we have a random process of flipping a coin where this experiment can produce two possible outcomes: {0,1}. This set of all possible outcomes is called the Sample Space of the experiment.

Each time the random process is repeated, it is referred to as an Event. In this example, flipping a coin and getting a tail as an outcome is an event. The chance or the likelihood of this event occurring with a particular outcome is called the probability of that event.

A Probability of an event is the likelihood that a random variable takes a specific value of x which can be described by P(x). In the example of flipping a coin, the likelihood of getting heads or tails is the same, that is 0.5 or 50%.

Mean, Variance, Standard Deviation

The Population is the set of all observations (individuals, objects, events, or procedures) and is usually very large and diverse, whereas a Sample is a subset of observations from the population that ideally is a true representation of the population.

For this purpose, one can use statistical sampling techniques such as Random Sampling, Systematic Sampling, Clustered Sampling, Weighted Sampling, and Stratified Sampling.

Mean

Mean also known as the average, is a central value of a finite set of numbers.

Then the sample mean defined by μ, which is very often used to approximate the population mean, can be expressed as follows: $$ \mu = \frac{\sum_{i=1}^N {x_i}}{N} $$

The mean is also referred to as expectation which is often defined by E() or random variable with a bar on the top. For example, the expectation of random variables X and Y, that is E(X) and E(Y)

import numpy as np import math x = np.array([1,3,5,6]) mean_x = np.mean(x)

in case the data contains Nan values

x_nan = np.array([1,3,5,6, math.nan]) mean_x_nan = np.nanmean(x_nan) return mean_x, mean_x_nan

#+RESULTS[47c5597f7f1d86f0de2f7976a0bdabc4b0686d71]: mean | 3.75 | 3.75 |

Variance

The Variance measures how far the data points are spread out from the average value, and is equal to the sum of squares of differences between the data values and the average (the mean). $$ \sigma^2 = \frac{\sum_{i=1}^N {(x_i - \mu)^2}}{N} $$

import numpy as np import math x = np.array([1,3,5,6]) variance_x = np.var(x)

here you need to specify the degrees of freedom (df) max number of logically independent data points that have freedom to vary

x_nan = np.array([1,3,5,6, math.nan]) mean_x_nan = np.nanvar(x_nan, ddof = 1) return variance_x, mean_x_nan

#+RESULTS[1f4f54b3c26d20ada10a72a95e36082491698a3a]: variance | 3.6875 | 4.916666666666667 |

Standard Deviation

The Standard Deviation is simply the square root of the variance and measures the extent to which data varies from its mean. $$ \mu = \sqrt{\frac{\sum_{i=1}^N (x_i - \mu)^2}{N}} $$ import numpy as np import math x = np.array([1,3,5,6]) variance_x = np.std(x)

x_nan = np.array([1,3,5,6, math.nan]) mean_x_nan = np.nanstd(x_nan, ddof = 1) return variance_x, mean_x_nan

#+RESULTS[a6af68e4a430e697897fe9b71efd277bad66f7c3]: standard-deviation | 1.920286436967152 | 2.217355782608345 |

Covariance

The Covariance is a measure of the joint variability of two random variables and describes the relationship between these two variables. It is defined as the expected value of the product of the two random variables’ deviations from their means.

import numpy as np import math x = np.array([1,3,5,6]) y = np.array([-2,-4,-5,-6]) #this will return the covariance matrix of x,y containing x_variance, y_variance on diagonal elements and covariance of x,y cov_xy = np.cov(x,y) return cov_xy

#+RESULTS[3423d8c2618e6cb48ee72cc37f1e5aa9d0c39a29]: covariance | 4.91666667 | -3.75 | | -3.75 | 2.91666667 |

Correlation

The Correlation is also a measure for relationship and it measures both the strength and the direction of the linear relationship between two variables. $$ Cor(X,Z) = \frac{Cov(X,Z)}{\sigma_x, \sigma_z} $$

import numpy as np import math x = np.array([1,3,5,6]) y = np.array([-2,-4,-5,-6])

corr = np.corrcoef(x,y) return corr

#+RESULTS[fdc6a0723c221a59e2ff9f0495be4ce448123083]: correlation | 1 | -0.99026741 | | -0.99026741 | 1 |

Probability Distribution Functions

A function that describes all the possible values, the sample space, and the corresponding probabilities that a random variable can take within a given range, bounded between the minimum and maximum possible values, is called a Probability Distribution Functions (pdf) or probability density. Every pdf needs to satisfy the following two criteria: \begin{equation} [0 \le Pr(X) \le 1] [\Sigma p(X) = 1] \end{equation}

Probability functions are usually classified into two categories:

  • Discrete Probability Distribution Discrete distribution function describes the random process with countable sample space, like in the case of an example of tossing a coin that has only two possible outcomes.
  • Continuous Probability Distributions Continuous distribution function describes the random process with continuous sample space.

Binomial Distribution

The Binomial Distribution is the discrete probability distribution of the number of successes in a sequence of n independent experiments, each with the boolean-valued outcome: success (with probability p) or failure (with probability q = 1 − p). $$ f(k,n,p)=\Pr(X=k)={n \choose k}p^{k}(1-p)^{n-k} $$

Binomial Distribution Mean & Variance

$$ {E} [X]=np $$ $$ {Var} [X]=np(1-p) $$

Random Generation of 1000 independent Binomial samples

import numpy as np n = 8 p = 0.16 N = 1000 X = np.random.binomial(n,p,N)

Histogram of Binomial distribution

import matplotlib.pyplot as plt counts, bins, ignored = plt.hist(X, 20, density = True, rwidth = 0.7, color = ‘purple’) plt.title(“Binomial distribution with p = 0.16 n = 8”) plt.xlabel(“Number of successes”) plt.ylabel(“Probability”) plt.savefig(‘assets/binomial-distribution.png’) return ‘assets/binomial-distribution.png’

#+ATTR_ORG : :width 480 #+RESULTS[249ae2a17b71841d458066a3c2322044980b62b3]: binomial-distribution [[file:assets/binomial-distribution.png]]

Poisson Distribution

The Poisson Distribution is the discrete probability distribution of the number of events occurring in a specified time period, given the average number of times the event occurs over that time period.

Poisson Distribution Mean & Variance

Random Generation of 1000 independent Poisson samples

import numpy as np lambda_ = 7 N = 1000 X = np.random.poisson(lambda_,N)

Histogram of Poisson distribution

import matplotlib.pyplot as plt counts, bins, ignored = plt.hist(X, 50, density = True, color = ‘purple’) plt.title(“Randomly generating from Poisson Distribution with lambda = 7”) plt.xlabel(“Number of visitors”) plt.ylabel(“Probability”) plt.savefig(“assets/poisson-distribution-sample.png”) return “assets/poisson-distribution-sample.png”

#+RESULTS[8a9163f040c4fe5ab0a165b8deffa80a7c32bf79]: poisson-distribution [[file:assets/poisson-distribution-sample.png]]

Normal Distribution

The Normal Distribution is the continuous probability distribution for a real-valued random variable.

Normal Distribution Mean & Variance

Random Generation of 1000 independent Normal samples

import numpy as np mu = 0 sigma = 1 N = 1000 X = np.random.normal(mu,sigma,N)

Population distribution

from scipy.stats import norm x_values = np.arange(-5,5,0.01) y_values = norm.pdf(x_values)#Sample histogram with Population distribution import matplotlib.pyplot as plt counts, bins, ignored = plt.hist(X, 30, density = True,color = ‘purple’,label = ‘Sampling Distribution’) plt.plot(x_values,y_values, color = ‘y’,linewidth = 2.5,label = ‘Population Distribution’) plt.title(“Randomly generating 1000 obs from Normal distribution mu = 0 sigma = 1”) plt.ylabel(“Probability”) plt.legend() plt.savefig(“assets/normal-distribution-sample.png”) return “assets/normal-distribution-sample.png”

#+RESULTS[1c3fa38f5dcefe428e28582a9747bb77dd8f368f]: normal-distribution [[file:assets/normal-distribution-sample.png]]

阅读原文 永久链接

002

Complete Guide to A/B Testing Design, Implementation and Pitfalls

“The world is a big A/B test” Sean Ellis if you want to learn or refresh your knowledge in the essential statistical concepts you can check this article: Fundamentals of statistics for Data Scientists and Data Analysts notes: Fundamentals Of Statistics For Data Scientists and Analysts

What is A/B testing and when to use it?

The idea behind A/B Testing is that you show the variated version of the product to a sample of customers (the experimental group) and the existing version of the product to another sample of customers (the control group). Then, the difference in product performance in experimental/treatment versus the control group is tracked, to identify the effect of this new version(s) of the product on the performance of the product.

Benefits of A/B testing

  • Allows to learn what works and what doesn’t in a quick manner
  • You get feedback directly from actual/real product customers
  • Since the users are not aware that they are being tested, the results will be unbiased

Demerits of A/B testing

  • Presenting different content/price/features to different customers especially in the same geolocation might potentially be dangerous resulting in Change Aversion (we will discuss how this can be addressed later on)
  • Requires a significant amount of Product, Engineering, and Data Science resources
  • Might lead to wrong conclusions if not conducted properly

Questions to clarify before any A/B test

  • What does a sample population look like and what are the customer segments for the target product?
  • Can we find the answer to our business question using exploratory/historical data analysis (e.g. by using causal analysis)?
  • Do we want to test single or multiple variants of the target product?
  • Can we ensure truly randomized control and experimental groups s.t. both samples are an unbiased and true representation of the true user population?
  • Can we ensure the integrity of the treatment vs control effects during the entire duration of the test?

Choice of Primary metric

for the A/B test, we need to tie up the primary metric to the direct and the higher-level goals of the product.

Metric validity question: If this chosen metric were to increase significantly while everything else stays constant, would we achieve our goal and address the problem?

Common A/B test metrics

Click-Through Rate (CTR)

Click-Through Rate ==CTR = {# total clicks * 100%} / {# total clicks + # total veiws}==

Click-Through Probability (CTP)

Click-Through Probability ==CTP = {# poeple with at least 1 ciclk * 100%} / {# number of unique visitors per page}==

Conversion Rate

Conversion Rate defined as the proportion of sessions ending up with a transaction. ==CR = {# converted} / {# converted + # not converted}==

Hypothesis of the test

A/B test should always be based on a Hypothesis that needs to be tested.

For example, if the KPI of the product is to improve the quality of the recommender system’s recommendations and this can be done for example by adding Impression Discounting or building a Re-ranker model for the recommender.

Do not merge multiple ideas into one hypothesis and also limit the variables introduced in the test so that you can understand their individual impact.

Design of the test (Power Analysis)

keeping in mind that it’s not really about testing — it’s about learning.

Step 1: Statistical Hypothesis

Step 2: Power Analysis

To make sure that our results are repeatable, robust, and can be generalized to the entire population we need to avoid p-hacking, to ensure real statistical significance and to avoid biased results, we want to make sure we collect “enough” amount of observations and we run the test for a minimum predetermined amount of time. Therefore, before running the test we need to determine the sample size of the control and experimental groups and for how long we need to run the test. This process is often referred to as Power Analysis and it includes 3 specific steps: determining the power of the test, determining the significance level of the test, and determining a Minimum Detectable Effect.

Power of the test

Power of a Test is the probability of correctly rejecting the Null Hypothesis. The power, often defined by (1-beta) is equal to the probability of not making a Type II Error, where Type II error is the probability of not rejecting the null hypothesis while the null is false.

It’s common practice to pick 80% as the power of the A/B test, that is 20% Type II error which means that we are fine with not detecting (failing to reject the null) a treatment effect while there is an effect.

Significance level of the test

Significance Level which is also the probability of Type I Error is the likelihood of rejecting the null, hence detecting a treatment effect, while the null is true and there is no statistically significant impact.

Generally, we use the significance value of 5% which indicates that we have a 5% risk of concluding that there exists a statistically significant difference between the experimental and control variant performances when there is no actual difference.

Minimum Detectable Effect (delta)

Minimum Detectable Effect what is the substantive to the statistical significance that the business wants to see as a minimum impact of the new version to find this variant investment-worthy?

MDE is a proxy that relates to the smallest effect that would matter in practice for the business and is usually set by stakeholders.

It’s common practice to pick 80% as the power and 5% as the significance level of the A/B test, that is 20% Type II error and 5% Type I error. However, the choice of a value of this parameter depends on the nature of the test and the business constraints.

Step 3: Calculating minimum sample size

Calculation of the sample size depends on the underlying primary metric that you have chosen for tracking the progress of the control and experimental versions.

Case 1: Sample Size Calculation with Binary Metric

When we are dealing with a primary performance tracking metric that has two possible values such as the Click Through Rate where the user can either click (success) or not click (failure) and if the users’ responses to the product can be defined as “independent” events then we can consider this as Bernoulli Trials where the click event (success) occurs with probability p_con in case of the Control Group and p_exp in case of the Experimental Group.

Then the sample size needed to compare these two Binomial Proportions, using a two-sided test with prespecified significance level, power level, MID can be calculated as follows:

where we need to use A/A testing (an A/B test except assigning the same treatment to both groups) to obtain the estimates for p_bar and q_bar.

Case 2: Sample Size Calculation with Continuous Metric

When we are dealing with a primary performance tracking metric that is in the form of an average such as the mean order amount where we intend to compare the means of the Control and Experimental Groups, then we can use the Central Limit Theorem and state that the mean sampling distribution of both Control and Experimental Groups follow Normal Distribution.

Hence, the sample size needed to compare the means of two Normally Distributed Samples, using a two-sided test with prespecified significance level, power level, MID can be calculated as follows:

where we can run an A/A test to obtain the sample variances, σ²_con, and σ²_exp.

Step 4: Determining A/B test duration

To determine the baseline of a duration time, a common approach is to use the following formula: Duration = {N} / {# visitors per day}

Too small test duration: Novelty Effects

when picking a test duration we need to make sure we don’t run the test for too short a time period otherwise we can have a Novelty Effects.

Too large test duration: Maturation Effects

the longer the test period the larger is the likelihood of external effects impacting the reaction of the users and possibly contaminating the test results, Maturation Effects.

Running the A/B test

Analysing A/B test results in Python

This set includes:

  • Choosing an appropriate statistical test
  • Calculating the test statistics (T)
  • Calculating the p-value of the test statistics
  • Reject or fail to reject the statistical hypothesis (statistical significance)
  • Calculate the margin of error (external validity of the experiment)
  • Calculate confidence interval (external validity and practical significance of the experiment)

Choosing an appropriate statistical test

Once the interaction data of the Control and Experimental groups are collected, you can test the statistical hypothesis earlier by choosing an appropriate statistical test that is usually categorized in Parametric Statistics and Non-Parametric Statistics tests. The choice of the test depends on the following factors:

  • format of the primary metric (underlying pdf)
  • sample size (for CLT)
  • nature of the statistical hypothesis (show that a relationship between two groups merely exists or identify the type of relationship between the groups)

The most popular Parametric Statistics tests that are used in A/B testing are:

  • 2 Sample T-test (when N < 30, metric follows student-t distribution, and you want to identify whether there exist a relationship and the type of relationship between control and experimental groups)
  • 2 Sample Z-test (when N > 30, metric follows asymptotic Normal distribution and you want to identify whether there exist a relationship and the type of relationship between control and experimental groups)

The most popular Non-Parametric Statistics tests that are used in A/B testing are:

  • Fisher’s Exact Test (small N, identify and you want to identify whether there exist a relationship between control and experimental groups)
  • Chi-squared Test (large N, identify and you want to identify whether there exist a relationship between control and experimental groups)
  • Wilcoxon Rank Sum/Mann Whitney test (small N or large N, skewed sampling distributions, testing the difference in medians between control and experimental groups)

2 Sample T-test

<<<2 Sample T-test>>> If you want to test whether there is a statistically significant difference between the control and experimental groups’ metrics that are in the form of averages (e.g. average purchase amount), metric follows student-t distribution and when the sample size is smaller than 30, you can use 2-sample T-test to test the following hypothesis:

import numpy as np from scipy.stats import t

N_con = 20 df_con = N_con - 1 # degrees of freedom of Control N_exp = 20 df_exp = N_exp - 1 # degrees of freedom of Experimental

Significance level

alpha = 0.05

data of control group with t-distribution

X_con = np.random.standard_t(df_con,N_con)

data of experimental group with t-distribution

X_exp = np.random.standard_t(df_exp,N_exp)

mean of control

mu_con = np.mean(X_con)

mean of experimental

mu_exp = np.mean(X_exp)

variance of control

sigma_sqr_con = np.var(X_con) #variance of control sigma_sqr_exp = np.var(X_exp)

pooled variance

pooled_variance_t_test = ((N_con-1)sigma_sqr_con + (N_exp -1) * sigma_sqr_exp)/(N_con + N_exp-2)(1/N_con + 1/N_exp)

Standard Error

SE = np.sqrt(pooled_variance_t_test)

Test Statistics

T = (mu_con-mu_exp)/SE

Critical value for two sided 2 sample t-test

t_crit = t.ppf(1-alpha/2, N_con + N_exp - 2)

P-value of the two sided T-test using t-distribution and its symmetric property

p_value = t.sf(T, N_con + N_exp - 2)*2

Margin of Error

margin_error = t_crit * SE

Confidence Interval

CI = [(mu_con-mu_exp) - margin_error, (mu_con-mu_exp) + margin_error]

print(“T-score: ”, T) print(“T-critical: ”, t_crit) print(“P_value: ”, p_value) print(“Confidence Interval of 2 sample Z-test: ”, np.round(CI,2)) return T, t_crit, p_value, np.round(CI,2)

#+RESULTS[d4e8a8fb20443ebb125d788946f4d41a02331fa1]: | -0.9332906095291454 | 2.024394164575136 | 1.643437434527514 | array | ((-0.89 0.33)) |

Bootstrapping and Bootstrap Quantile Method for SE and CI

Statistical Significance vs Practical Significance

Quality of A/B test (Reliability, Validity, Potency)

Common problems and pitfalls of A/B testing

Ethics and privacy in A/B testing

阅读原文 永久链接

已经到底了

全部 5 篇都在这里。