How to get the first canonical correlation from sklearn's CCA module?
Well, with some help looking at the source code in pyrcca I managed to create this snippet of code to get out the first canonical correlation.
cca = CCA(n_components=1)
U_c, V_c = cca.fit_transform(U, V)
result = np.corrcoef(U_c.T, V_c.T)[0,1]
Hope this helps someone else.
Note: The pyrcca package mentioned above runs slightly quicker than sci-kit learn's, due to heavier usage of multi-core processing for anyone who was curious. Also they have implemented kernel CCA unlike sklearn.
Given your transformed matrices U_c
and V_c
, you can indeed retrieve canonical component correlations like you did, and more generally for a CCA with n_comp
CCs:
result = np.corrcoef(U_c.T, V_c.T).diagonal(offset=n_comp)
Now, you do not have to tranform
your data yourself, it has been done during the fitting procedure at least for the training data. The score are stored in the CCA
instance by scikit-learn, so:
score = np.diag(np.corrcoef(cca.x_scores_, cca.y_scores_, rowvar=False)[:n_comp, n_comp:])
Will give the same result, a vector of n_comp
scalar values, corresponding to the score, or correlations between each pair of canonical components.