########### 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
Below is the Python code that converts the provided R script to Python and TensorFlow, integrating the necessary libraries and replicating the key functionalities:
Import essential packages
python
import numpy as np
import pandas as pd
from sklearn.cross_decomposition import CCA
from sklearn.decomposition import PCA
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from scipy.stats import median
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
### Function to create train/test split
def CVfun(data, test_size=0.3):
train_idx, test_idx = train_test_split(np.arange(len(data)), test_size=test_size)
return train_idx, test_idx
### Function for CCA
def CCAfunc(X, Z, Xtest, Ztest, export="cor"):
cca = CCA(n_components=1)
cca.fit(X, Z)
X_c, Z_c = cca.transform(Xtest, Ztest)
if export == "cor":
return np.corrcoef(X_c.T, Z_c.T)[0, 1]
if export == "vars":
combined = np.hstack((X_c, Z_c))
pca = PCA(n_components=1)
return pca.fit_transform(combined)[:, 0]
### Load datasets
paths = [
"IMAGEN-IMGN_ADRS_CHILD_FU2-IMAGEN_DIGEST.csv",
"IMAGEN-IMGN_ANXDX_CHILD_FU2-IMAGEN_DIGEST.csv",
# Add the rest of the datasets here...
]
datasets = [pd.read_csv(path) for path in paths]
### Identify overlapping subjects
datasets[6]['User.code'] = datasets[6]['User.code'].str.replace("-I", "-C")
user_codes = pd.concat([d['User.code'] for d in datasets])
user_codes = user_codes[user_codes.duplicated(keep=False)].unique()
### Filter and preprocess datasets
d_mats = []
for d in datasets:
mat = d[d['User.code'].isin(user_codes)]
mat = mat.select_dtypes(include=[np.number]).values
mat[np.isnan(mat)] = 0
d_mats.append(mat)
### Load metadata and correct for covariates
meta = pd.read_csv("IMAGEN_demographics.csv")
meta = meta[meta['User.code'].isin(user_codes)]
meta_values = meta.values[:, 2:]
le = LabelEncoder()
for i in range(meta_values.shape[1]):
meta_values[:, i] = le.fit_transform(meta_values[:, i])
regressor = LinearRegression()
d_mats = [regressor.fit(meta_values, mat).residues_ for mat in d_mats]
### Unique combinations of rating scales
combinations = list(itertools.combinations(range(len(d_mats)), 2))
### Run repeated train/test splits
repCOR = []
for _ in range(20):
train, test = CVfun(d_mats[0])
corvec = []
for i, j in combinations:
corvec.append(CCAfunc(d_mats[i][train], d_mats[j][train], d_mats[i][test], d_mats[j][test]))
repCOR.append(corvec)
repCOR = np.array(repCOR)
finalCor = np.median(repCOR, axis=0)
### Convert to matrix and cluster
corMat = np.zeros((len(d_mats), len(d_mats)))
indices = np.tril_indices(len(d_mats), -1)
corMat[indices] = finalCor
corMat += corMat.T
corMat[corMat < 0.5] = 0
corMat[corMat > 0] = 1
import networkx as nx
G = nx.from_numpy_matrix(corMat)
clusters = list(nx.connected_components(G))
### Compress clusters into first PC
PCsol = []
for cluster in clusters:
if len(cluster) <= 1:
continue
curcmbRES = []
for i, j in itertools.combinations(cluster, 2):
ccaPCcur = []
for _ in range(100):
reptrain, reptest = CVfun(d_mats[0])
curcca = CCAfunc(d_mats[i][reptrain], d_mats[j][reptrain], d_mats[i][reptest], d_mats[j][reptest], export="vars")
ccaPCcur.append(curcca[np.argsort(reptest)])
curcmbRES.append(np.median(ccaPCcur, axis=0))
curcmbRES = np.array(curcmbRES).T
pc_sol = PCA(n_components=1).fit_transform(curcmbRES)
PCsol.append(pc_sol.flatten())
PCsol = np.array(PCsol).T
### Autoencoder setup and training
dListMat = np.hstack(d_mats)
model = Sequential([
Dense(50, activation='tanh', input_shape=(dListMat.shape[1],)),
Dense(10, activation='tanh'),
Dense(50, activation='tanh'),
Dense(dListMat.shape[1], activation='linear')
])
model.compile(optimizer='adam', loss='mse')
model.fit(dListMat, dListMat, epochs=100, batch_size=32)
encoder = Model(model.input, model.layers[1].output)
deep_features = encoder.predict(dListMat)
print(np.corrcoef(PCsol.T, deep_features.T).round(2))
Explanation:
Data Preprocessing: Reads datasets, identifies overlapping subjects, and preprocesses the datasets.
Canonical Correlation Analysis (CCA): Applies CCA to reduced and transformed datasets.
Clustering: Constructs a correlation matrix, clusters the data, and isolates the first principal component of each cluster.
Autoencoder: Constructs, trains, and evaluates a deep autoencoder using TensorFlow/Keras, assesses correlation with extracted principal components.
Ensure to set the correct paths for datasets and metadata file locations and adjust other specifics to fit the actual data structure.