###########
########### Build pairwise canonical correlation anaylsis across rating scales in IMAGEN
########### Build network and reproduce connections across datasets
########### Each connected subgraph is a dimension along which patients could be clustered
########### Check whether the same dimensions can be extracted via text encoder
To convert the given R code into a TensorFlow-compatible Python script, we'll need to reimplement some parts using the appropriate TensorFlow and other Python libraries. The task will involve implementing functionalities for canonical correlation analysis (CCA), preparing the data, performing the train/test split, computing correlations, building adjacency matrices, and leveraging TensorFlow for autoencoder training.
Here's a step-by-step conversion of the R code into Python using TensorFlow:
Loading Libraries and Data:
import pandas as pd
import numpy as np
from sklearn.cross_decomposition import CCA
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import networkx as nx
# Load datasets
d1 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_ADRS_CHILD_FU2-IMAGEN_DIGEST.csv")
d2 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_ANXDX_CHILD_FU2-IMAGEN_DIGEST.csv")
d3 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_AUDIT_CHILD_FU2-IMAGEN_DIGEST.csv")
d4 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_BIS_CHILD_FU2-IMAGEN_DIGEST.csv")
d5 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_CAPE_CHILD_FU2-IMAGEN_DIGEST.csv")
d6 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_CSI_CHILD_FU2-IMAGEN_DIGEST.csv")
d7 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_CTQ_CHILD_FU2-IMAGEN_DIGEST.csv")
d8 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_EDEQ_CHILD_FU2-IMAGEN_DIGEST.csv")
d9 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_ESPAD_CHILD_FU2-IMAGEN_DIGEST.csv")
d10 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_IRI_CHILD_FU2-IMAGEN_DIGEST.csv")
d11 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_JVQ_CHILD_FU2-IMAGEN_DIGEST.csv")
d12 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_PAAQ_CHILD_FU2-IMAGEN_DIGEST.csv")
d13 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_RRS_CHILD_FU2-IMAGEN_DIGEST.csv")
d14 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_TCI_CHILD_FU2-IMAGEN_DIGEST.csv")
d15 = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_TFEQ_CHILD_FU2-IMAGEN_DIGEST.csv")
# Load and match metadata
meta = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU3/participants/IMAGEN_demographics.csv")
ucode_comb_MOD = [code.replace("-C", "") for code in ucode_comb]
meta = meta[meta.iloc[:, 0].isin(ucode_comb_MOD)]
# Regress out covariates
def regress_out_covariates(df, meta):
result = pd.DataFrame()
for col in df.columns:
lm = LinearRegression()
lm.fit(meta.iloc[:, [1, 2]], df[col])
residuals = df[col] - lm.predict(meta.iloc[:, [1, 2]])
result[col] = residuals
return result
dList = [regress_out_covariates(df, meta) for df in dList]
from itertools import combinations
# Run repeated train/test splits
rtcmb = list(combinations(range(15), 2))
repCOR = []
for _ in range(20):
# Train/test split
train, test = CVfun(dList[0])
corvec = []
for ip, is_ in rtcmb:
curcca = CCAfunc(dList[ip].iloc[train, :], dList[is_].iloc[train, :],
dList[ip].iloc[test, :], dList[is_].iloc[test, :], export="cor")
corvec.append(curcca)
repCOR.append(corvec)
# Median correlation across splits
finalCor = np.median(repCOR, axis=0)
# Convert to matrix and threshold
corMat = np.zeros((15, 15))
indices = np.tril_indices(15, -1)
corMat[indices] = finalCor
corMat = corMat + corMat.T
corMat[corMat < 0.5] = 0
corMat[corMat != 0] = 1
# Cluster the graph
graph = nx.from_numpy_matrix(corMat)
components = list(nx.connected_components(graph))
# Compress clusters into first PC
PCsol = []
for component in components:
if len(component) < 2:
continue
curcmbRES = np.zeros((len(dList[0]), ))
for ip, is_ in combinations(component, 2):
ccaPCcur = []
for _ in range(100):
train, test = CVfun(dList[0])
curcca = CCAfunc(dList[ip].iloc[train, :], dList[is_].iloc[train, :],
dList[ip].iloc[test, :], dList[is_].iloc[test, :], export="vars")
curcca_matched = np.full(len(dList[0]), np.nan)
curcca_matched[test] = curcca
ccaPCcur.append(curcca_matched)
ccaPCcur = np.array(ccaPCcur).mean(axis=0, where=~np.isnan(ccaPCcur))
curcmbRES = np.column_stack([curcmbRES, ccaPCcur])
pca = PCA(n_components=1)
pca.fit(curcmbRES)
PCsol.append(pca.components_[0])
PCsol = np.vstack(PCsol).T
Building and Evaluating Autoencoder:
# Combine data
dListMat = np.hstack(dList)
# Normalize data
scaler = StandardScaler()
dListMat = scaler.fit_transform(dListMat)
# Build and train autoencoder
model = Sequential([
Dense(50, activation='tanh', input_shape=(dListMat.shape[1],)),
Dense(10, activation='tanh', name='bottleneck'),
Dense(50, activation='tanh'),
Dense(dListMat.shape[1], activation='linear')
])
model.compile(optimizer='adam', loss='mse')
model.fit(dListMat, dListMat, epochs=100, batch_size=256, verbose=0)
# Extract bottleneck layer
encoder = tf.keras.Model(model.input, model.get_layer('bottleneck').output)
ae1_codings = encoder.predict(dListMat)
# Correlation between PCsol and autoencoder features
print(np.round(np.corrcoef(PCsol.T, ae1_codings.T)[:PCsol.shape[1], PCsol.shape[1]:], 2))
This Python script covers the primary functionalities of the original R script, including data loading and preprocessing, canonical correlation analysis, clustering, and autoencoder training using TensorFlow. Make sure to adjust any file paths and environment settings to match your own setup.