###########
########### 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 script to TensorFlow/Python, we need to address several parts: data loading and preprocessing, dimensionality reduction and correlation calculation (similar to CCA), and clustering/comparison using an autoencoder. Below is the corresponding Python script using TensorFlow.
import numpy as np
import pandas as pd
from sklearn.cross_decomposition import CCA
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense
import itertools
import os
# Read the datasets
data_paths = [
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_ADRS_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_ANXDX_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_AUDIT_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_BIS_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_CAPE_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_CSI_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_CTQ_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_EDEQ_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_ESPAD_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_IRI_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_JVQ_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_PAAQ_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_RRS_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_TCI_CHILD_FU2-IMAGEN_DIGEST.csv",
"/zi/flstorage/HITKIP/datasets/IMAGEN/FU2/psytools/IMAGEN-IMGN_TFEQ_CHILD_FU2-IMAGEN_DIGEST.csv"
]
dataframes = [pd.read_csv(path) for path in data_paths]
# Clean and Preprocess Data
def clean_and_preprocess(dataframes):
# Some specific cleaning actions based on the R script
dataframes[6]['User.code'] = dataframes[6]['User.code'].str.replace("-I", "-C")
ucode_comb = pd.concat(df['User.code'] for df in dataframes).value_counts()
ucode_comb = ucode_comb[ucode_comb == 15].index.tolist()
# Filter and get only required columns based on the script
dMats = [
df[df['User.code'].isin(ucode_comb)].filter(regex=pattern, axis=1)
for df, pattern in zip(dataframes, [
"adrs", "ANXDX", "audit", "BIS", "CAPE42", "item", "CTQ",
"EDEQ", "SCID", "IRI", "JVQ", "PAAQ", "RRS", "tci", "TFEQ"
])
]
dMats_processed = []
for mat in dMats:
mat = mat.applymap(lambda x: pd.to_numeric(x, errors='coerce')).fillna(0)
mat = mat.loc[:, (mat != 0).any(axis=0)]
dMats_processed.append(mat)
return dMats_processed, ucode_comb
dMats, ucode_comb = clean_and_preprocess(dataframes)
# Load and preprocess metadata
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)]
# Scale and correct for metadata covariates
def correct_for_covariates(dMats, meta):
dMats_corrected = []
for mat in dMats:
corrected_mat = pd.DataFrame()
for col in mat.T.values:
model = LinearRegression().fit(meta.iloc[:, 1:3], col)
residuals = col - model.predict(meta.iloc[:, 1:3])
corrected_mat = pd.concat([corrected_mat, pd.DataFrame(residuals)], axis=1)
dMats_corrected.append(corrected_mat)
return dMats_corrected
dMats_corrected = correct_for_covariates(dMats, meta)
# Canonical Correlation Analysis (CCA) - Function
def cca_func(X, Z):
cca = CCA(n_components=1)
cca.fit(X, Z)
X_c, Z_c = cca.transform(X, Z)
return np.corrcoef(X_c[:,0], Z_c[:,0])[0, 1]
# Main Routine
rtcmb = list(itertools.combinations(range(15), 2))
repCOR = []
for repi in range(20):
train, test = train_test_split(range(len(dMats_corrected[0])), train_size=0.7)
corvec = []
for ip, is_ in rtcmb:
curcca = cca_func(dMats_corrected[ip].iloc[train], dMats_corrected[is_].iloc[train])
corvec.append(curcca)
repCOR.append(corvec)
repCOR = np.array(repCOR)
finalCor = np.median(repCOR, axis=0)
# Form the correlation matrix
corMat = np.zeros((15, 15))
corMat[np.tril_indices(15, -1)] = finalCor
corMat = corMat + corMat.T
corMat[corMat < 0.5] = 0
corMat[corMat != 0] = 1
import networkx as nx
import matplotlib.pyplot as plt
# Create and visualize the graph
corgr = nx.from_numpy_matrix(corMat)
clsol = list(nx.connected_components(corgr))
PCsol = []
for cluster in clsol:
if len(cluster) < 2:
continue
curcmbRES = []
for ip, is_ in itertools.combinations(cluster, 2):
ccaPCcur = []
for _ in range(100):
train, test = train_test_split(range(len(dMats_corrected[0])), train_size=0.7)
curcca = cca_func(dMats_corrected[ip].iloc[train], dMats_corrected[is_].iloc[train])
ccaPCcur.append(curcca)
ccaPCcur = np.array(ccaPCcur).T
ccaPCcurMed = np.median(ccaPCcur, axis=1)
curcmbRES.append(ccaPCcurMed)
curcmbRES = np.array(curcmbRES).T
varPCA = PCA(n_components=1).fit_transform(curcmbRES)
PCsol.append(varPCA[:, 0])
PCsol = np.array(PCsol).T
# Autoencoder
def build_autoencoder(input_dim):
input_layer = Input(shape=(input_dim,))
encoded = Dense(50, activation='tanh')(input_layer)
encoded = Dense(10, activation='tanh')(encoded)
decoded = Dense(50, activation='tanh')(encoded)
decoded = Dense(input_dim, activation='sigmoid')(decoded)
autoencoder = Model(input_layer, decoded)
encoder = Model(input_layer, encoded)
autoencoder.compile(optimizer='adam', loss='mse')
return autoencoder, encoder
dListMat = np.hstack(dMats_corrected)
scalar = StandardScaler()
features = scalar.fit_transform(dListMat)
autoencoder, encoder = build_autoencoder(features.shape[1])
autoencoder.fit(features, features, epochs=50, batch_size=256, shuffle=True)
encoded_data = encoder.predict(features)
correlation_matrix = np.corrcoef(PCsol, encoded_data.T)
print(np.round(correlation_matrix, 2))
This script replicates the key operations of the R script, converting it to Python using libraries like scikit-learn for CCA and TensorFlow for the autoencoder. Make sure to adjust file paths and install the necessary libraries (numpy, pandas, tensorflow, scikit-learn, networkx).