Skip to content

WIP/ENH: add grouping (letter display) for pairwise comparison - #3674

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

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

Conversation

@josef-pkt

@josef-pkt josef-pkt commented May 17, 2017 •

Copy link
Copy Markdown
Member

update rebased version now in #9493

see #3669
form overlapping groups based on statistically significant pairwise comparison, or a distance matrix for significance

see docstring for details

has basic unit tests for 3 examples in Piepho 2004, no unit tests for options
API unclear, also might need restructuring (lazy letter assignment in results class?)
more convenience, pandas index, choosing alphabet, ... ?

Intended mainly as helper function to integrate with plot and summaries

location maybe temporary (multicomp is still in sandbox, and we cannot add it to stats.multicomp because of circular import if it's reused in multicomp and Tukey)

@coveralls

coveralls commented May 17, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.0008%) to 90.434% when pulling 48b99f2 on josef-pkt:pairwise_grouping into 90e2af8 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

just a thought:

add line display or line letter assignment assuming ordering by mean, and verify that is really correct (helper function in here)
I was reading http://jpktd.blogspot.ca/2013/03/multiple-comparison-and-tukey-hsd-or_25.html because somebody linked to it on stackoverflow. See comments in later part about common variance assumption in tukeyhsd and pairwise tests. Line display would be enough in those cases, and simpler to compute.
(In here we don't need to know the means, and ordering is only relevant for choosing among equivalent permutations of letters.)

@josef-pkt

Copy link
Copy Markdown
Member Author

no notebook, it was before I used notebooks for dev
script file try_tukey_grouping.py which includes original version of function and
the following example code (which was copied to unit tests, based on a quick look)

I don't see or remember what edges are in terms of multi-comparison results, all significant pairs ?

k = 4
edges = np.asarray([[1, 2], [1, 3], [1, 4], [2, 4]]) - 1
d = np.zeros((4, 4))
d[edges[:, 0], edges[:,1]] = 1
#d += np.diag(4)
d += d.T
d = 1 - d
print(d)

allsets = set(frozenset(np.nonzero(d[i])[0]) for i in range(k))


rem = [(to_remove(s, d), s) for s in allsets]
for i in rem: print(i)    

all_ = []
for s in allsets:
    if not to_remove(s, d):
        all_.append(s)

#all_ = list(allsets)
all_.sort(key=min)
print(all_)

alphabet = 'abcdefg'
letter = [] * 4
for i in range(4):
    ss = ''.join(alphabet[j] if i in set_j else ' ' for j, set_j in enumerate(all_))
    letter.append(ss)
    
print(letter)


edges2 = np.asarray([[1, 7], [1, 8], [2, 4], [2, 5], [3, 5]]) - 1
gr = group_pairwise(edges2, distance_matrix=None, k_groups=None, names=None)
print(gr)


edgesli = [[12, [5, 7, 10]],
           [16, [12]],
           [18, [3, 12]], 
           [20, [2, 3, 4, 5, 6, 7, 9, 10, 11, 13, 16, 18]]
          ]

edges3 = np.asarray([[i, j] for i, row in edgesli for j in row]) - 1
gr3 = group_pairwise(edges3, distance_matrix=None, k_groups=None, names=None)
print(gr3)

## to check with Piepho results table 2
# letters_piepho3 = [''.join(sorted(s.upper().replace('B', 'a')
#                    .replace('A', 'b').replace('C', 'c').replace('D', 'd'))) 
#                    for s in gr3.letter]

from numpy.testing import assert_

groupings = [
    frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 18}), 
    frozenset({0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18}), 
    frozenset({0, 1, 2, 3, 5, 7, 8, 10, 11, 12, 13, 14, 16, 18}), 
    frozenset({0, 7, 11, 13, 14, 16, 18, 19})]

assert_(gr3.groupings == groupings)

@josef-pkt

josef-pkt commented Jan 25, 2025 •

Copy link
Copy Markdown
Member Author

possibly misleading interpretation of letters
Having the same letter does not mean that groups have "equivalent" mean. It's not an equivalence test.
The hypothesis tests only provide evidence for rejections.

i.e. "The data does not allow us to distinguish means of groups with the same letter."

Notes section in PR #7332 :

        Notes
        -----
        The summary dataframe from a posthoc test (like Games Howell or Tukey HSD) defines
        a graph where nodes are group names and an edge connects two groups if they are not
        statistically significantly different. Then each connecting letters group is equivalent
        to a maximal clique in this graph.

Which means that if we use a pairwise equivalence test, TOST, then we need to look at rejected pairs for the set/clique formation. The edges are rejected pairs in that case.
update piepho's argorithm will not work, because it avoids rejected pairs to be in the same group. Equivalence requires that only rejected pairs are in the same group.
In standard case, only not being in the same grouping is based on tests. Being in the same grouping/clique might not mean much, the means could be really close, but also there just might not be enough information in the data to reject a large mean difference. A small group with large variance or standard error of mean might be in every clique. (in tukey-hsd only sample size differs across groups, games howell can have also variance differences.)

aside PR 7332 uses numbers instead of letters
The current code here has a limited number of letters in the fixed alphabet,
(We should use alpha numeric as fallback. Number of "cliques" should be limited by number of insignificant pairs, as check.)

I'm not sure how singleton cliques are handled. Do they get a letter?

@josef-pkt

josef-pkt commented Jan 25, 2025 •

Copy link
Copy Markdown
Member Author

also wrong unit test module:
stats/tests/test_multi.py is for multiple testing p-value correction.
The multiple comparison tests are in test_pairwise
The module here is tools, so unit tests could also be in some tools test module.
The integration tests will be in test_pairwise, once we have access to it as part of TukeyHSDResults method.

test_multi still has one function test_tukeyhsd

current limitation: groups need to be defined as consecutive integers, group identifier in edges is used for indexing
string group labels are not allowed.
(current tukey hsd result only has direct access string pairs.)

@josef-pkt

Copy link
Copy Markdown
Member Author

merge conflict in multitest looks very strange.
It looks like it will revert changes in main in unrelated code.

I think it will be safer to remove the unit tests from rebasing the commit, and add them as new commit.
Need new PR to avoid possibility of destroying this one.

@josef-pkt

josef-pkt commented Jan 26, 2025 •

Copy link
Copy Markdown
Member Author

TestPairwiseGrouping2 fails in assert of grouping
The sets are the same, but the order of sets in the list differs, first and second switch position.

Is there some indeterminacy in the order, or is this changes in environment (numpy, python)?

I will fix the unit test for now and see later if ordering fails again.

It's worse. If grouping order changes, then also the letter assignment changes, and unit test for it fail even worse. I guess letters a and b are interchanged.

update
sort criteria in code don't impose unique sequence, it uses min and len.
In the example the first two groupings have the same len and the same min

    # sort by smallest element to get deterministic representation
    # sort by len first to break ties in min
    # no sorting if both len and min are equal for several groupings
    all_.sort(key=len, reverse=True)
    all_.sort(key=min)

instead of min we should have list comparison that uses all elements, eg.

first 3 groupings are

frozenset({0, 3, 4, 5}),
frozenset({0, 2, 3, 5}),
frozenset({0, 1, 2, 5}),

same min, but {0, 1, 2, 5} should evaluate smaller than the others.

So, for this unit test case, there is no deterministic result wrt order and letter assignment.

I don't remember the details
Do we need frozedsets or can we transform them into a list for the return?
Sorting a list of lists would be easier.

update
possible solution: use temporary list
this seems to work
But it assumes that list of frozen set has increasing values of items (which it is in all the examples in the test cases)

all_
[frozenset({0, 3, 4, 5}),
 frozenset({0, 2, 3, 5}),
 frozenset({0, 1, 2, 5}),
 frozenset({1, 2, 5, 6, 7}),
 frozenset({2, 3, 5, 6, 7}),
 frozenset({3, 4, 5, 6, 7})]

all_.sort(key=lambda x: list(x))
all_
[frozenset({0, 1, 2, 5}),
 frozenset({0, 2, 3, 5}),
 frozenset({0, 3, 4, 5}),
 frozenset({1, 2, 5, 6, 7}),
 frozenset({2, 3, 5, 6, 7}),
 frozenset({3, 4, 5, 6, 7})]

another issue on order:
currently the intention is to have the sets ordered by lowest integers.
But what should the group indices be.

  • predefined order by user, which might be alphanumeric in names, e.g. in a group stats dataframe
    • this would be useful when we have ordered/ordinal groups
  • sorted by mean: In table or plot, having the groups sorted by increasing (or decreasing mean) would have similar groups next to each other, so letters of groups would also be closer to each other

Looking briefly at the examples in Piepho's article again:
It looks like he has the reversed ordering in terms of letter. The highest letters seem to be on top, and the lower letters start further down.
His group order are by predefined order.

@josef-pkt

josef-pkt commented Jan 27, 2025 •

Copy link
Copy Markdown
Member Author

update It looks like our function does not have the sweep step. Table 2 in Piepho, we match IA column but not either of the sweep columns.

another possible problem:
Piepho section 3: result of sweeping may depend on order of sweeps. His primary order is left to right, which should be right to left for me, IIUC.
He mentions investigating different orders or all permutation of orders for the sweep step.

So if we relabel group (integer) names and reorder, then the outcome might be different. :(
If we run the algorithm once with predefined order and once with mean order we are not guaranteed to get the same structural, "equivariant" result, i.e. result that differs only in labeling and order.

If we want to have the same structure with different order and labeling, then we would use a relabeling/reordering only after the structural results have been obtained.

or we give up on having different orders/labels, i.e. one of them will look not ordered/consecutive.
I guess we should use ordering by group means.

aside: use

from string import ascii_letters
ascii_letters, len(ascii_letters)
('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 52)

@josef-pkt

josef-pkt commented Jan 27, 2025 •

Copy link
Copy Markdown
Member Author

I'm giving up on ordering (for now)
new PR will have in rebased version

  • unique ordering with all_.sort(key=lambda x: sorted(list(x))) (I think I need the sorted list, but it was not necessary in example.
    Sorting first by length is not needed anymore, list sorting will be unique.
  • fix unit tests with new ordering (we compare with Piepho's structure but not oredering nor labeling. Even the test here already needed to relable Piepho's results)

@josef-pkt josef-pkt added the superseded Used for PRs with content that is superseded by a newer PR label Jan 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-stats superseded Used for PRs with content that is superseded by a newer PR type-enh

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants