###########
########### 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 R code to a Python equivalent using TensorFlow, we need to address the individual steps and corresponding methods in R and map them to their appropriate alternatives in Python.
Data Loading and Processing: We'll use pandas in Python.
Canonical Correlation Analysis (CCA): We'll use the scikit-learn library for CCA.
Graph Construction and Clustering: We'll employ the networkx and numpy libraries.
Autoencoder: We'll utilize tensorflow for building and training the autoencoder.
Here's the complete code:
import pandas as pd
import numpy as np
from sklearn.cross_decomposition import CCA
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
from scipy.stats import zscore
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense
import networkx as nx
# Load data
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")
# Identify overlapping subjects
d7['User.code'] = d7['User.code'].str.replace("-I", "-C")
# Combine user codes
ucode_comb = pd.concat([d['User.code'] for d in [d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15]]).value_counts()
ucode_comb = ucode_comb[ucode_comb == 15].index.tolist()
# Function to prepare dataset matrices
def prepare_data(d, ucode_comb, col_pattern):
matched_indices = d['User.code'].apply(lambda x: x if x in ucode_comb else None).dropna().index
data_mat = d.iloc[matched_indices, list(d.columns.str.contains(col_pattern))]
data_mat.fillna(0, inplace=True)
data_mat = data_mat.apply(pd.to_numeric, errors='coerce').fillna(0).values
return data_mat
# Prepare dataset matrices
d1Mat = prepare_data(d1, ucode_comb, "adrs")
d2Mat = prepare_data(d2, ucode_comb, "ANXDX")
d3Mat = prepare_data(d3, ucode_comb, "audit")
d4Mat = prepare_data(d4, ucode_comb, "BIS")
d5Mat = prepare_data(d5, ucode_comb, "CAPE42")
d6Mat = prepare_data(d6, ucode_comb, "item")
d7Mat = prepare_data(d7, ucode_comb, "CTQ")
d8Mat = prepare_data(d8, ucode_comb, "EDEQ")
d9Mat = prepare_data(d9, ucode_comb, "SCID")
d10Mat = prepare_data(d10, ucode_comb, "IRI")
d11Mat = prepare_data(d11, ucode_comb, "JVQ")
d12Mat = prepare_data(d12, ucode_comb, "PAAQ")
d13Mat = prepare_data(d13, ucode_comb, "RRS")
d14Mat = prepare_data(d14, ucode_comb, "tci")
d15Mat = prepare_data(d15, ucode_comb, "TFEQ")
dList = [d1Mat, d2Mat, d3Mat, d4Mat, d5Mat, d6Mat, d7Mat, d8Mat, d9Mat, d10Mat, d11Mat, d12Mat, d13Mat, d14Mat, d15Mat]
# Load metadata and match/correct for covariates
meta = pd.read_csv("/zi/flstorage/HITKIP/datasets/IMAGEN/FU3/participants/IMAGEN_demographics.csv")
ucode_comb_mod = [int(code.replace("-C", "")) for code in ucode_comb]
meta = meta[meta.iloc[:, 0].isin(ucode_comb_mod)].reset_index(drop=True)
for idx, data in enumerate(dList):
for col in range(data.shape[1]):
reg_data = np.vstack([zscore(data[:, col]), np.ones(len(data))]).T
beta = np.linalg.lstsq(np.hstack([reg_data, np.array(meta.iloc[:, 1:3])]), data[:, col], rcond=None)[0]
dList[idx][:, col] = data[:, col] - np.dot(np.hstack([reg_data, np.array(meta.iloc[:, 1:3])]), beta)
# Define CCA function
def cca_func(X, Z, X_test, Z_test):
cca = CCA(n_components=1)
cca.fit(X, Z)
X_c, Z_c = cca.transform(X_test, Z_test)
return np.corrcoef(X_c.T, Z_c.T)[0, 1]
# Train/Test split and running CCA
num_splits = 20
combinations = np.array(np.meshgrid(range(15), range(15))).T.reshape(-1, 2)
combinations = combinations[combinations[:, 0] < combinations[:, 1]]
rep_cor = []
for _ in range(num_splits):
train_indices, test_indices = train_test_split(range(len(dList[0])), test_size=0.3, random_state=_)
cor_vec = []
for combo in combinations:
ip, is_ = combo
cor_vec.append(cca_func(dList[ip][train_indices], dList[is_][train_indices],
dList[ip][test_indices], dList[is_][test_indices]))
rep_cor.append(cor_vec)
rep_cor = np.array(rep_cor)
final_cor = np.median(rep_cor, axis=0)
# Convert to correlation matrix and construct graph
cor_mat = np.zeros((15, 15))
cor_mat[np.tril_indices(15, -1)] = final_cor
cor_mat = cor_mat + cor_mat.T
threshold = 0.5
cor_mat[cor_mat < threshold] = 0
cor_mat[cor_mat >= threshold] = 1
graph = nx.from_numpy_matrix(cor_mat)
components = list(nx.connected_components(graph))
# Compress clusters into first PC
result = []
for component in components:
if len(component) < 2:
continue
sub_data = np.concatenate([dList[i] for i in component], axis=1)
medians = []
for j in range(sub_data.shape[1]):
corr = []
for _ in range(100):
train_idxs, test_idxs = train_test_split(range(len(sub_data)), test_size=0.3, random_state=_)
pca = PCA(n_components=1)
pca.fit(sub_data[train_idxs, j].reshape(-1, 1))
transformed = pca.transform(sub_data[test_idxs, j].reshape(-1, 1))
corr.append(np.median(transformed))
medians.append(np.mean(corr))
result.append(np.array(medians))
PC_sol = np.array(result).T
# Build and train autoencoder
dListMat = np.concatenate(dList, axis=1).astype(np.float32)
features = tf.data.Dataset.from_tensor_slices(dListMat).batch(128)
input_dim = dListMat.shape[1]
input_layer = Input(shape=(input_dim,))
encoded = Dense(50, activation='tanh')(input_layer)
bottleneck = Dense(10, activation='tanh')(encoded)
decoded = Dense(50, activation='tanh')(bottleneck)
output_layer = Dense(input_dim, activation='tanh')(decoded)
autoencoder = Model(inputs=input_layer, outputs=output_layer)
encoder = Model(inputs=input_layer, outputs=bottleneck)
autoencoder.compile(optimizer='adam', loss='mse')
autoencoder.fit(features, epochs=50)
# Extract deep features
ae_codings = encoder.predict(dListMat)
# Correlation between autoencoder features and PCsol
correlation_matrix = np.corrcoef(PC_sol.T, ae_codings.T)[:PC_sol.shape[1], PC_sol.shape[1]:]
print(np.round(correlation_matrix, 2))
Explanation:
Data Loading: Utilizes pandas to load CSV files into DataFrames.
Overlapping Subjects Identification: Filters out common subjects present across multiple datasets.
Data Cleaning and Correction: Replaces missing data with zeros and handles categorical variables.
CCA: Uses scikit-learn's CCA for Canonical Correlation Analysis, while training and testing on data splits.
Graph Construction: Builds a graph from the canonical correlations using networkx and clusters the graph.
Autoencoder: Constructs an autoencoder using tensorflow, trains it on the feature data, and extracts the encoded features.
Correlation Calculation: Compares the autoencoder's codings with the first principal components derived from the canonical variables using correlation coefficients.
Simply run the code in a Python environment, ensuring you have all the necessary dependencies (pandas, numpy, scikit-learn, tensorflow, networkx) installed. Each step matches its corresponding part in the provided R code to maintain the original algorithm's structure and logic.