Repository navigation
Description
Describe the bug
Changing the order of response variables in the Y matrix results in different selection of CCA axes. The loading vector of the first response variable is always parallel to the first CCA axis.
Steps/Code to Reproduce
import numpy as np
from sklearn.cross_decomposition import CCA
# Generate random data
np.random.seed(0)
data = np.random.rand(10, 10)
# Generate random set of response variables
np.random.seed(1)
test = np.random.rand(10, 6)
# Change order of response variables
test2 = np.copy(test)
test2[:, 3:] = test[:, :3]
test2[:, :3] = test[:, 3:]
# Perform the CCA for both response variable datasets
cca = CCA(n_components=2)
cca.fit(data, test)
d = cca.transform(data)
y = cca.y_loadings_
cca2 = CCA(n_components=2)
cca2.fit(data, test2)
d2 = cca2.transform(data)
y2 = cca2.y_loadings_
# Print first five rows of X scores and first Y loading vector for both cases
print(d[:5])
print(d2[:5])
print(y[0])
print(y2[0])Expected Results
As both cca and cca2 objects are built on the same data, I expect the resulting CCA scores of observations (d and d2) be identical or nearly so in both cases. The direction of the loading vector of the first response variable (y and y2) is most probably not parallel to any of the "real" CCA axes, so I do not expect the loadings close to 0, 1 or -1.
Actual Results
The scores in the first rows of d and d2 are obviously different. In my case the first five rows are like
[[-0.13226527 0.39666035]
[ 0.47686754 -0.44630239]
[ 0.42884673 -0.56030583]
[ 0.59795741 -0.61033328]
[-1.34483863 -0.74278071]]
and
[[-0.22933487 0.76123766]
[ 0.03491544 0.23805463]
[ 0.18202364 0.35970863]
[ 0.51478239 0.20467545]
[-0.52352471 -0.12359243]]
, respectively.
Both y and y2 loading vectors for the first variable are parallel to the first CCA axis or nearly so:
[-1.000000e+00 -4.188481e-15]
and
[ 1.00000000e+00 -1.00802462e-14]
, respectively.
Versions
System:
python: 3.7.4 (default, Aug 9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)]
executable: c:\anaconda3\python.exe
machine: Windows-10-10.0.18362-SP0
Python dependencies:
pip: 20.3
setuptools: 50.3.2.post20201201
sklearn: 0.23.2
numpy: 1.19.2
scipy: 1.5.2
Cython: 0.29.21
pandas: 1.1.3
matplotlib: 3.1.3
joblib: 0.17.0
threadpoolctl: 2.1.0
Built with OpenMP: True
Activity
taprs commentedon Dec 19, 2020
This may be related to an old (yet still open) issue: #14169
glemaitre commentedon Dec 22, 2021
I don't think that this is a bug but it comes from the fact that we need to compute the pseudo-inverse of
Xthat will be ill-defined forn_featuresclose ton_samples. I see the following comment in the code:By increasing the number of samples, I can observe that we get a similar transform:
This thing is not documented anywhere so I think that it should be good to have a note in the documentation.
DOC Add numerical stability note to CCA when n_features > n_samples
DOC Add numerical stability note to CCA when n_features > n_samples