Skip to content

ENH: functional boxplot - highest density region - #3876

Closed
tupui wants to merge 20 commits into
statsmodels:masterfrom
tupui:hdr-boxplot
Closed

tupui wants to merge 20 commits into
statsmodels:masterfrom
tupui:hdr-boxplot

Conversation

@tupui

@tupui tupui commented Aug 18, 2017

Copy link
Copy Markdown
Contributor

This is related to issue #3864.

It implements the Highest Density Region (HDR) technique from Hyndman[2010].

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.07%) to 81.182% when pulling 3643cf0 on tupui:hdr-boxplot into 6625458 on statsmodels:master.

@tupui

tupui commented Aug 18, 2017 •

Copy link
Copy Markdown
Contributor Author

The builds where already not passing on master. But here import matplotlib also leads to errors as not installed. I used it to remove duplicated legends. Will try to come up with something else.

@josef-pkt

Copy link
Copy Markdown
Member

This pull request introduces 1 alert - view on lgtm.com

new alerts:

  • 1 for Syntax error

Comment posted by lgtm.com

@josef-pkt

Copy link
Copy Markdown
Member

There are some problems in master, but this PR uses features that are not available in py 2.7
e.g.

E     File "C:\projects\statsmodels\statsmodels\graphics\functional.py", line 218
E       contour_grid = np.meshgrid(*[np.linspace(*min_max[i], n_contours)
E   SyntaxError: only named arguments may follow *expression

@tupui

tupui commented Aug 18, 2017

Copy link
Copy Markdown
Contributor Author

Just saw that, I am fixing looking to fix it now. What is your opinion otherwise?

@tupui

tupui commented Aug 18, 2017

Copy link
Copy Markdown
Contributor Author

I am more concern about the difference between fboxplot and this one. On the figures, we can see that both methods find the same outliers (same legend) but actually the displayed curves are not the same. There might be an index error.

@tupui

tupui commented Aug 18, 2017 •

Copy link
Copy Markdown
Contributor Author

I think there are no more issues. So before I get the tests here, we should decide

  • Whether or not to use a class design like the one I have done here.
  • Change the grid search into global optimization (see the class for the code).
  • Add more options for plotting like in fboxplot (not the case with rainbowplot).

Tell me if I can do something else, this is my first PR to an open source project.

@josef-pkt josef-pkt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I added some comments based on a first read-through, where I don't understand the details yet.

numpy just had the discussion about adding quantiles as alternative to percentiles. In the code and docstring it will be less confusing to avoid the work "percentile" if we mean fractions and quantiles. using interval (0, 1) instead of (0, 100)

Comment thread statsmodels/graphics/functional.py Outdated
__all__ = ['hdrboxplot', 'fboxplot', 'rainbowplot', 'banddepth']


def kernel_smoothing_(data, optimize=False):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

those helper function need leading underscore in name to make them private, no trailing underscore

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Oh misread your previous comment, my bad!

Comment thread statsmodels/graphics/functional.py Outdated
3. Plot the bivariate plot,
4. Compute mediane curve along with percentiles and outliers curves.

Behind the scene, the dataset is represented as a matrix. Each line

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

long explanation should go in the notes section. This should have just be a short explanation , so we get faster to Parameter section which we/users need to look at more often

Comment thread statsmodels/graphics/functional.py Outdated
components, this is called a bivariate plot.

This visualization exhibit a cluster of points. It indicate that a lot of
curve lead to common components. The center of the cluster is the mediane

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It indicate that a lot of curve lead to common components.

It's not clear what this sentence means.

----------
data : sequence of ndarrays or 2-D ndarray
The vectors of functions to create a functional boxplot from. If a
sequence of 1-D arrays, these should all be the same size.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It's not (yet) clear to me whether a sequence of 1-D arrays works.
asarray(data) would concatenate rows, and not column_stack

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Indeed, this is not clear to me as well. I took this from fboxplot.

Comment thread statsmodels/graphics/functional.py Outdated
return projection


def hdrboxplot(data, ncomp=2, alpha=[], threshold=0.95, optimize=False,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

don't use mutable like [] as default, just to avoid any kind of related problems.
None as default?

Comment thread statsmodels/graphics/functional.py Outdated
Number of components to use. If None, returns the as many as the
smaller of the number of rows or columns in data.
alpha : list, optional
Extra percentile values to compute.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

use quantile instead of percentile, to emphasize that we want a fractional number between 0 and 1.

same for threshold
"fraction" also works

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Got it, I have been mislead with quartile and forgot the word quantile.

Comment thread statsmodels/graphics/functional.py Outdated

- 'median', array. Median curve.
- 'mean_percentile', array. 50% percentile band. [sup, inf] curves
- 'extreme_percentile', list of array. 90% percentile band. [sup, inf]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm not sure about those names

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Is it extreme that is bothering you?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

not necessarily.
mean: We use it usually as average or expected value, so mean percentile sounds strange, is it and average or a percentile

and then related to the other comments quantile versus percentile

Can those be interpreted as confidence intervals/bands?

maybe directly referring to the coverage or alpha level would be better
0.5-band or 50% percentiles

I don't have a clear suggestion

@tupui tupui Aug 19, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I changed all percentile to quantile.

Regarding the bands yes it can be seen as a level of confidence. It is like a box plot with its 1.5 Inter Quartiles Ranges. I checked the original paper, they use: 50% HDR. So I suggest:
hdr_50 or hdr_05 and for the label 50% HDR.

Comment thread statsmodels/graphics/functional.py Outdated
label = str(labels[ii]) if labels is not None else None
ax.plot(xdata, outlier,
ls='--', alpha=0.7, label=label)
except ValueError:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

what raises the ValueError?
An explicit check would make the code more informative and more robust.
e.g. if len(outliers) != 0

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It is caused by the ax.plot that is not able to process an empty array. I agree with you, I can use a condition here.

@coveralls

coveralls commented Aug 18, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.07%) to 81.181% when pulling a450035 on tupui:hdr-boxplot into 6625458 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member

I think the function is fine for the graphics module, at least from the API/user perspective.
For more we also would have to decide what else to expose in case those methods become functionality in themselves and not just to support the plot.

I don't understand enough yet for the other issues. (And I'm not sure I will be able to get to it today.)

What are the tradeoffs and what are your recommendations or preferences given that it's your code and you have some experience in using it?

@tupui

tupui commented Aug 18, 2017 •

Copy link
Copy Markdown
Contributor Author

In my opinion, the only benefit for using a class for this would be to get the extra plots. So the plot of the reduced space and the contour plot if ncomp=2 (the plot I linked to in the issue). I think it is fine if we do not have this extra. Although, what could be added in the output dictionary is the explained variance due to the choice of ncomp. Using sklearn I was asking the user for a level of variance. Thus, this can work like this as the user can relaunch it if not satisfied by the variance.

As for the optimization part. I did not included at first because I know that some are not fine with adding some optimization stuff as no one agree on which method to use (gradient free or not, etc.). But without this you will not be able to do ncomp>3 due to memory consumption of np.meshgrid. So to me, this is helpful and plus, it ensure a better convergence (normal as not restricted to the discretization of the space). I also found this faster to compute. So if you are fine with some scipy.optimize.differential_evolution, I will do this.

Finally, for the plot options, I think that if the user wants more control, it might be better using the resinstead of adding tons of options.

@coveralls

coveralls commented Aug 18, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.06%) to 81.19% when pulling a450035 on tupui:hdr-boxplot into 6625458 on statsmodels:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.1%) to 81.141% when pulling bcd32f9 on tupui:hdr-boxplot into 6625458 on statsmodels:master.

@tupui

tupui commented Aug 19, 2017

Copy link
Copy Markdown
Contributor Author

I am modifying the code to add optimization. Is it okay if I use some multiprocessing? I use this to compute the HDR bands as I have to find the min and max value for each index of xdata. So there is an optimization per xdata that can easily be speed up with multiprocessing. (Again, I already have the code).

@tupui

tupui commented Aug 19, 2017 •

Copy link
Copy Markdown
Contributor Author

Got it working. It adds two functions outside hdrboxplot and one function within it. Let me now if it's okay to commit this. (I am cleaning the docstrings).

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.07%) to 81.18% when pulling 24d56a4 on tupui:hdr-boxplot into 6625458 on statsmodels:master.

1 similar comment
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.07%) to 81.18% when pulling 24d56a4 on tupui:hdr-boxplot into 6625458 on statsmodels:master.

@tupui

tupui commented Aug 21, 2017

Copy link
Copy Markdown
Contributor Author

@josef-pkt seems okay to me, let me know If I need to do something else :)

@josef-pkt

Copy link
Copy Markdown
Member

another iteration reading through it without understanding all the details:

  • unit tests for scipy 0.14 on travis error because of missing differential_evolution. I think we ignore this, and you can catch the import error (and add a skip test to the unit tests). docstring should mention that it requires recent scipy that has differential evolution
    (The alternative would be to provide an option for a different optimization, but scipy 0.14 is already pretty old.)
  • no unit tests: For plots we use most of the time only smoke tests which catch at least compatility errors (e.g. with numpy and scipy). The extra results hdr_res could be properly unit tested. Is there an R package that produces the same result?
  • The main naming issues that was bothering me when reading/skimming through the code is optimize for the bandwidth choice. I think a more specific keyword or option would be better. Initially I didn't understand what the keyword referred to.

Overall, it looks good in my opinion, but I don't have any experience with differential evolution.

(Maybe: attribute versus dictionary access to results. Maybe instead of returning a dict for hdr_res we should return an instance of a simple class that just holds attributes. We do this in some of the hypothesis tests but I don't think we have a clean consistent pattern across types of functions yet. I got reminded of this because differential evolution results have a .x that you use)

@tupui

tupui commented Aug 21, 2017 •

Copy link
Copy Markdown
Contributor Author

Thanks for the feedbacks.

  • Yeah I thing that scipy 0.14 is pretty old, so if It is okay with you we can catch the error and exit. Another option would be to use classical gradient optimization as fallback.
  • Indeed, for the tests I was waiting for confirmation on the code base. I currently have ~8 tests (in pytest, hope it is okay) checking for "smoke" but also checking on hdr_res. If I understood correctly, you are saying that we can have a class that wrap the function and hold as attributes hdr_res? There is an R package that do this : hdrcde. It has been written by Hyndman (for the paper). But I have not looked at the code. I can only say that I get the same results on the same dataset (elnino).
  • For the naming, you are right. I suggest : bw. So we let the user choose from KDEMultivariate's options. Actually, I will remove the function _kernel_smoothing. It serves nothing here.

Will do all that for the next run.

@josef-pkt

Copy link
Copy Markdown
Member

If I understood correctly, you are saying that we can have a class that wrap the function and hold as attributes hdr_res

No, what I meant was replacing the dict of hdr_res with a instance of a class that just defines attributes
I don't find a good example right now, but contingency tables uses a _Bunch class with a string method to list the attributes
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/contingency_tables.py#L59

@tupui

tupui commented Sep 22, 2017

Copy link
Copy Markdown
Contributor Author

There seems to be an issue with python <3.5 regarding pop on OrderedDict. I am looking at it.

@tupui

tupui commented Sep 23, 2017 •

Copy link
Copy Markdown
Contributor Author

From my tests, it seems that there was an issue in Matplotlib 1.4 with fill_between. Labels are not displayed. Even in the old doc the legend does not show. Indeed PolyCollection was not supported by label() see this SO.

Actually, you are already using a hack in regression/recursive_ls.py line 461:

# Only add CI to legend for the first plot
                if i == 0:
                    # Proxy artist for fill_between legend entry
                    # See http://matplotlib.org/1.3.1/users/legend_guide.html
                    p = plt.Rectangle((0, 0), 1, 1,
                                      fc=ci_poly.get_facecolor()[0])

                    handles.append(p)
                    labels.append(ci_label)

@coveralls

coveralls commented Sep 23, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.3%) to 81.559% when pulling 2e4c0cb on tupui:hdr-boxplot into 6625458 on statsmodels:master.

@tupui

tupui commented Sep 23, 2017 •

Copy link
Copy Markdown
Contributor Author

@josef-pkt Sounds good to me. Anything to add?

@tupui

tupui commented Oct 6, 2017

Copy link
Copy Markdown
Contributor Author

@josef-pkt Did you get some time to check this? :)

@josef-pkt

Copy link
Copy Markdown
Member

No, I had forgotten, or didn't realize that you were finished. (I would have remembered or gotten reminded when I work again on my todo list for 0.9.)
Brief skim through the changes looks good. I will run the examples and look again tomorrow, and hopefully merge.

@tupui

tupui commented Oct 9, 2017

Copy link
Copy Markdown
Contributor Author

@josef-pkt OK no problem. Let me know if I can be of any help anywhere else :)

@josef-pkt

Copy link
Copy Markdown
Member

Sorry for the delay, but with long weekend with 3 kids at home and issue triaging, I didn't get around it yet.

@tupui

tupui commented Oct 11, 2017

Copy link
Copy Markdown
Contributor Author

@josef-pkt No problem I fully understand :)

Comment thread statsmodels/graphics/functional.py Outdated

# Plots
ax.plot(np.array([xdata] * n_samples).T, data.T,
c='c', alpha=.1, label='dataset')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we ever want to have these labels?
When I reformat the legend to 2-columns ax.legend(ncol=2) (as I had done in my previous review), then I get a very large number of "dataset" in the legend, maybe one for each year.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Indeed, these can be described in the figure's caption. Will remove it.

data = np.asarray(data)
if xdata is None:
xdata = np.arange(data.shape[1])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

suggestion for use with pandas, before converting to array on line 309, store the index as labels, e.g.
if isinstance(xdata, pd.DataFrame) and labels is None:
labels = xdata.index
(maybe needs labels = np.asarray(xdata.index) )

alternative would be
if hasattr(xdata, 'index') and labels is None:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done using your snippet bellow

@josef-pkt

Copy link
Copy Markdown
Member

If labels is None, then I get a legend with a very large number of "dataset" labels.
BTW: I'm using matplotlib '1.5.3', and don't know if the behavior has changes.

Except for labels everything looks good,
Direct pandas (label) support would be nice but not necessary for the merge (e.g. the other plot functions also don't use an available index as labels)

@josef-pkt

josef-pkt commented Oct 12, 2017 •

Copy link
Copy Markdown
Member

one possibility:
if labels is None: then create some artificial labels that are just the array index.
Then the main part of the function does not need to distinguish whether labels are available or not.

for example simple int labels seem to work
fig3, res3 = sm.graphics.hdrboxplot(df, labels=np.arange(len(df)))

@josef-pkt

Copy link
Copy Markdown
Member

I'm finished with this review, and will be away from a computer for the next few hours.

The main suggestions are

remove "dataset" labels

if label is None:
     if hasattr(data, 'index'): 
        labels = data.index
     else: 
        labels = np.arange(len(data))

Then the rest should behave by default as expected

Comment thread statsmodels/graphics/functional.py Outdated

by_label = OrderedDict(zip(labels, handles))
if len(outliers) != 0:
by_label.pop('dataset')

@josef-pkt josef-pkt Oct 12, 2017 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is now either redundant or will raise
I guess

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

oh I missed this one!

@josef-pkt

Copy link
Copy Markdown
Member

looks good now

I tried out the latest checkout. A simple call with a dataframe df produces a nice default
fig3, res3 = sm.graphics.hdrboxplot(df)

I guess there are cosmetic/option improvements that can be made to the functional plots, but it is now similar in style to fboxplot. However, hdr identifies and shows fewer outlier years.

@josef-pkt

Copy link
Copy Markdown
Member

I cancelled and restarted one of the travis jobs that never even started to build. Everything else is green.

I think it's ready to merge.
However, I'd like to rebase and squash it into a new PR. For the plot function there are too many commits. but I don't want to loose the information in this PR because I haven't tried to figure out the algorithm and the more general structure more than superficially.
@tupui If rebasing on master and squashing is easy to do for you, then you could open a new PR, otherwise I will do it tomorrow.

This follows now a similar or the same pattern as other plot functions. But some of this or related to this would fit also in statsmodels.functional with a class based, model oriented style.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.4%) to 81.64% when pulling 07313ea on tupui:hdr-boxplot into 6625458 on statsmodels:master.

@tupui

tupui commented Oct 13, 2017

Copy link
Copy Markdown
Contributor Author

@josef-pkt I am not sure about rebasing + squashing have never done that so maybe you should do it so I can see what you have done for next time :)

@josef-pkt

Copy link
Copy Markdown
Member

rebased version merged in #4049

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.

6 participants