Skip to content

WIP ENH: add stats.control_charts - #5503

Open
josef-pkt wants to merge 1 commit into
statsmodels:mainfrom
josef-pkt:control_charts
Open

josef-pkt wants to merge 1 commit into
statsmodels:mainfrom
josef-pkt:control_charts

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

adding by getting started with control charts script from #4191 to stats.control_charts

example converted to notebook is at https://gist.github.com/josef-pkt/f97874ca89237e78a505392803f6b40a

raise ValueError('only t and normal for now' )

center = endog.mean(0)
std = endog.std(0, ddof=1)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

center and std computation need to handle weights and use options, e.g. for robust estimators

raise ValueError('only t and normal for now' )

self.center = self.endog.mean(0)
self.std = self.endog.std(0, ddof=1)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as above
center and std computation need to handle weights and use options, e.g. for robust estimators

if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
if np.isscalar(self.upp) or True:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or True ? why?

return fig

class ControlChartEWMAMvMean(ControlChartMean):
"""T2 control chart for multivariate mean

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wrong docstring

@josef-pkt

josef-pkt commented Feb 16, 2019 •

Copy link
Copy Markdown
Member Author

I think the vectorized ControlChartMean should have an option to plot the t-statistic instead of raw values, so that the mean and control limits are the same (similar to T2 chart).

heteroscedasticity: e.g. different number of observations in x-bar chart
AFAIR, I did some experiments with changing std, where also control limits adjust with std. Alternative version is to use standardized values, i.e. t-values, so the control limits stay constant (but it hides the changing uncertainty because we don't see control interval getting wider or narrower)

t-values should be standardized "effect" size, i.e. y / std without dividing by nobs or df, i.e. we want std for predicted observation not for predicted mean (in terms of results.get_prediction)

related parameter uncertainty: The usual control charts and the current implementation ignore parameter uncertainty, i.e. mean and std are assumed known or estimated from a large sample during phase 2 evaluation.
effect size stays constant as nobs increases
parameter uncertainty, e.g. standard t-values, becomes smaller as nobs increases when mean is assumed to be constant.

@josef-pkt

Copy link
Copy Markdown
Member Author

thought about robust estimation:

  • weighted mean and std for given weights, e.g. 0-1 weights that drop outliers, this works for known or identified outliers
  • as preliminary step we can use robust mean and std estimators to identify outliers, e.g. using RLM, statsmodels.robust, median, mad, trimmed mean and std and their multivariate counterparts (e.g. robust cov for T2 when those become available in statsmodels.)

related aside: do we get get_prediction with prediction/confidence intervals for RLM?

e.g. control chart using OLS: OLS with just a constant as exog and using get_prediction should be pretty much equivalent to the basic mean chart, and will be extendable to explanatory variables e.g. calender effects. phase 2 evaluation would be OLS out-of-sample prediction error and prediction (obs) intervals.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.2%) to 84.317% when pulling 4d0f7cc on josef-pkt:control_charts into db49000 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

related: connection to GLM
https://www.itl.nist.gov/div898/handbook/pmc/section3/pmc331.htm at the end
"Note: In general, it is not a good idea to use 3-sigma limits for distributions that are highly skewed"
one recommendation is to transform a poisson count variable to make it closer to normal distributed.
This is similar to anscombe and other residuals in GLM, and also related to the one, 2 or k-sample tests for rates and proportions.
i.e. once we know what we need, it will be useful to reuse or combine control charts with GLM and k-sample hypothesis tests.

interesting aside https://en.wikipedia.org/wiki/Control_chart#Alternative_bases
Shewhart/Deming versus Pearson, 3 sigma versus distributional assumptions.
In the current version I allow for crit to be user defined but default to ppf (of normal, t, F or chisquare).
However, the main background for our implementation will be hypothesis testing and multiple testing corrections.

@josef-pkt

Copy link
Copy Markdown
Member Author

What are the required methods to modularize this and let subclasses overwrite for the specific case?

e.g. plot_chart currently computes the statistic for the test sample, this should be in a separate method so plot_chart only does the plotting independently of which chart is used.
Do we need several plots/charts in the same plot as I currently have? Should we have a plot grid in the vectorized case or just add an index for which column/variable to plot?
(I like vectorized because it comes almost for free and can complement multivariate plots, and we could add a max plot.)

How can we have a class that doesn't use data, i.e. only phase 2 for fixed given parameters.

plot_chart in ControlChartMvMean and ControlChartEWMAMvMean use statistic and are identical except for computing the statistic for new data. This should be the generic case.

in analogy to model/results classes, we would have fit, update_fit and predict or get_prediction plus plotting the chart.

  • estimate parameters, currently in __init__ -> use private _fit called from __init__?
  • compute the test statistic, i.e. predict and prediction interval (which is currently fixed at low and upp) plus possible computed out of sample residual. (aside families in GLM comput resid_dev and resid_anscombe with data as arguments, i.e. can be used also for out-of-sample, resid_pearson is in GLMResults and uses endog attribute)

@josef-pkt

Copy link
Copy Markdown
Member Author

ASIDE: "If all you have are nails, then everything looks like a hammer"
or, The convergence of model/results and control charts.
(or why we have anova and t-tests in addition to linear models)

What do we do about pandas integration? e.g. currently I use and index in plot that is just np.arange. pandas support would provide the user index.
If we want full pandas support, then we might be better off using the current model infrastructure, predict now also returns pandas with the provided index.

x, xbar, p, c, u and similar charts follow the same assumptions as OLS, WLS, GLM, Poisson, ...
CUSUM and EMWA are different. We do have CUSUM test but that is only insample.
To provide control chart like support in the Results classes, we will need some additional methods, e.g. more prediction, out of sample residuals and the corresponding out of sample outlier tests.

aside in the aside: In ETS (efficient trimmed squares) #452 we do something similar. Estimate a candidate model on a subset, then "test" which other observations in the remaining sample are inliers given the estimates based on the subsample.

Can we define CUSUM and EMWA for out of sample observations, similarly to the corresponding control charts? CUSUM and EMWA assume an ordering in the observations, which we don't have or use in the models outside of tsa (with some exceptions like autocorrelation in OLS diagnostic or HAC cov_type).

OLS outlier_test is insample, i.e. uses data from the model. GLM influence and outliers is also all designed for insample data.

another aside in the aside: out of sample evaluation criteria would also be useful for cross-validation, e.g. we don't have loglike/loglike_obs in general for out-of sample data. i.e. they always use the endog, exog attached to the model.

Nevertheless, we still want to get explicit control charts in the same way as I would like to get the 1, 2 and k-sample hypothesis tests and confidence intervals into statsmodels (those are largely special cases of GLM, but with extras like power calculation and more methods for small samples, and more convenient to use when a full model is overkill.)

(We need a collection of hammers for nails with different sizes. :)

@josef-pkt

Copy link
Copy Markdown
Member Author

default for alpha
In the literature that I looked at today the implicit or explicit default alpha corresponds to the 3 sigma limits in the normal case. They seem to use the same alpha for non-normal distribution.
This is a multiple testing correction to have a fixed average run time to false positive

alpha / 2

>>> stats.norm.sf(3)
0.0013498980316300933

average run for two sided test

>>> 1 / stats.norm.sf(3) / 2
370.39834734495918

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants