Upload 10 files
Browse files- .Rhistory +14 -0
- .gitattributes +1 -0
- PCA.py +66 -0
- Training_Data_Generation.R +15 -0
- bar.py +22 -0
- best_model.pth +3 -0
- hyperparameters.py +169 -0
- methane.py +257 -0
- use_pre_pca.py +36 -0
- webplot.png +3 -0
- webplot.py +81 -0
.Rhistory
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
library(readr)
|
| 2 |
+
# 读取数据
|
| 3 |
+
mathylation <- read.csv("pca_principal_components.csv")
|
| 4 |
+
data <- read_tsv("TCGA-ACC.survival.tsv", na = c("NaN", "null", ""))
|
| 5 |
+
data <- read_tsv("TCGA-LGG.survival.tsv", na = c("NaN", "null", ""))
|
| 6 |
+
data = data[data$OS == 1, ]
|
| 7 |
+
# 更改列名
|
| 8 |
+
colnames(mathylation)[1] = 'sample'
|
| 9 |
+
# 合并数据
|
| 10 |
+
data = merge(data, mathylation, by = 'sample')
|
| 11 |
+
data = data[, -c(1, 2, 3)]
|
| 12 |
+
data[is.na(data)] <- 0
|
| 13 |
+
# 保存结果
|
| 14 |
+
write.csv(data, 'data.csv')
|
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
webplot.png filter=lfs diff=lfs merge=lfs -text
|
PCA.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
from sklearn.decomposition import PCA
|
| 3 |
+
from sklearn.preprocessing import StandardScaler
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
from mpl_toolkits.mplot3d import Axes3D
|
| 6 |
+
import os
|
| 7 |
+
import joblib
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
script_path = os.path.abspath(__file__)
|
| 11 |
+
script_dir = os.path.dirname(script_path)
|
| 12 |
+
os.chdir(script_dir)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
file_path = 'TCGA-LGG.methylation450.tsv'
|
| 16 |
+
df = pd.read_csv(file_path, sep='\t', index_col=0)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
df.dropna(inplace=True)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
scaler = StandardScaler()
|
| 24 |
+
scaled_data = scaler.fit_transform(df.T)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
pca = PCA(n_components=50)
|
| 28 |
+
principal_components = pca.fit_transform(scaled_data)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
pca_model_path = 'pca_model.pkl'
|
| 32 |
+
joblib.dump(pca, pca_model_path)
|
| 33 |
+
print(f"PCA模型已保存为 {pca_model_path}")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
loadings = pd.DataFrame(pca.components_.T, columns=[f'PC{i+1}' for i in range(pca.n_components_)], index=df.index)
|
| 37 |
+
loadings.to_csv('pca_loadings.csv')
|
| 38 |
+
print("主成分载荷矩阵已保存为 pca_loadings.csv")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
sample_ids = df.columns
|
| 42 |
+
principal_df = pd.DataFrame(data=principal_components, columns=[f'Principal Component {i+1}' for i in range(50)], index=sample_ids)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
fig = plt.figure(figsize=(10, 8))
|
| 46 |
+
ax = fig.add_subplot(111, projection='3d')
|
| 47 |
+
ax.scatter(principal_df['Principal Component 1'], principal_df['Principal Component 2'], principal_df['Principal Component 3'])
|
| 48 |
+
|
| 49 |
+
for i, sample_id in enumerate(sample_ids):
|
| 50 |
+
ax.text(principal_df['Principal Component 1'][i], principal_df['Principal Component 2'][i], principal_df['Principal Component 3'][i], sample_id)
|
| 51 |
+
|
| 52 |
+
ax.set_xlabel('Principal Component 1')
|
| 53 |
+
ax.set_ylabel('Principal Component 2')
|
| 54 |
+
ax.set_zlabel('Principal Component 3')
|
| 55 |
+
ax.set_title('3D PCA of Methylation Data')
|
| 56 |
+
plt.show()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
output_file_path = 'pca_principal_components.csv'
|
| 60 |
+
principal_df.to_csv(output_file_path)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
explained_variance = pca.explained_variance_ratio_
|
| 64 |
+
print(f"Explained variance by each component: {explained_variance}")
|
| 65 |
+
|
| 66 |
+
print(f"50个主成分已保存为 {output_file_path}")
|
Training_Data_Generation.R
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
library(readr)
|
| 2 |
+
|
| 3 |
+
mathylation <- read.csv("pca_principal_components.csv")
|
| 4 |
+
|
| 5 |
+
data <- read_tsv("TCGA-LGG.survival.tsv", na = c("NaN", "null", ""))
|
| 6 |
+
data = data[data$OS == 1, ]
|
| 7 |
+
|
| 8 |
+
colnames(mathylation)[1] = 'sample'
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
data = merge(data, mathylation, by = 'sample')
|
| 12 |
+
data = data[, -c(1, 2, 3)]
|
| 13 |
+
data[is.na(data)] <- 0
|
| 14 |
+
|
| 15 |
+
write.csv(data, 'data.csv')
|
bar.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import matplotlib.pyplot as plt
|
| 2 |
+
import numpy as np
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
script_path = os.path.abspath(__file__)
|
| 6 |
+
script_dir = os.path.dirname(script_path)
|
| 7 |
+
os.chdir(script_dir)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
cmap = plt.colormaps['viridis']
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
fig, ax = plt.subplots(figsize=(2, 6))
|
| 14 |
+
norm = plt.Normalize(vmin=0, vmax=10000)
|
| 15 |
+
fig.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), cax=ax, orientation='vertical')
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
output_path = 'colorbar_purple_yellow.png'
|
| 19 |
+
plt.savefig(output_path, bbox_inches='tight', dpi=300)
|
| 20 |
+
plt.close()
|
| 21 |
+
|
| 22 |
+
output_path
|
best_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import optuna
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.optim as optim
|
| 5 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import numpy as np
|
| 8 |
+
from sklearn.model_selection import train_test_split
|
| 9 |
+
from sklearn.preprocessing import StandardScaler
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
script_path = os.path.abspath(__file__)
|
| 15 |
+
script_dir = os.path.dirname(script_path)
|
| 16 |
+
os.chdir(script_dir)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 20 |
+
print(f"Using device: {device}")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
data = pd.read_csv('data.csv')
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
X = data.drop(columns=['OS.time']).values
|
| 27 |
+
y = data['OS.time'].values
|
| 28 |
+
|
| 29 |
+
scaler = StandardScaler()
|
| 30 |
+
X_scaled = scaler.fit_transform(X)
|
| 31 |
+
|
| 32 |
+
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
|
| 33 |
+
|
| 34 |
+
X_train_tensor = torch.tensor(X_train, dtype=torch.float32).to(device)
|
| 35 |
+
y_train_tensor = torch.tensor(y_train, dtype=torch.float32).view(-1, 1).to(device)
|
| 36 |
+
X_test_tensor = torch.tensor(X_test, dtype=torch.float32).to(device)
|
| 37 |
+
y_test_tensor = torch.tensor(y_test, dtype=torch.float32).view(-1, 1).to(device)
|
| 38 |
+
|
| 39 |
+
train_dataset = TensorDataset(X_train_tensor, y_train_tensor)
|
| 40 |
+
test_dataset = TensorDataset(X_test_tensor, y_test_tensor)
|
| 41 |
+
|
| 42 |
+
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
|
| 43 |
+
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class SimpleNN(nn.Module):
|
| 47 |
+
def __init__(self, input_dim, hidden_dim, num_layers, dropout_rate):
|
| 48 |
+
super(SimpleNN, self).__init__()
|
| 49 |
+
self.layers = nn.ModuleList()
|
| 50 |
+
last_dim = input_dim
|
| 51 |
+
for _ in range(num_layers):
|
| 52 |
+
self.layers.append(nn.Linear(last_dim, hidden_dim))
|
| 53 |
+
self.layers.append(nn.ReLU())
|
| 54 |
+
self.layers.append(nn.Dropout(dropout_rate))
|
| 55 |
+
last_dim = hidden_dim
|
| 56 |
+
self.layers.append(nn.Linear(last_dim, 1))
|
| 57 |
+
|
| 58 |
+
def forward(self, x):
|
| 59 |
+
for layer in self.layers:
|
| 60 |
+
x = layer(x)
|
| 61 |
+
return x
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def weights_init(m):
|
| 65 |
+
if isinstance(m, nn.Linear):
|
| 66 |
+
nn.init.kaiming_uniform_(m.weight)
|
| 67 |
+
nn.init.zeros_(m.bias)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def objective(trial):
|
| 71 |
+
|
| 72 |
+
num_layers = trial.suggest_int('num_layers', 2, 5)
|
| 73 |
+
hidden_dim = trial.suggest_int('hidden_dim', 50, 200)
|
| 74 |
+
dropout_rate = trial.suggest_float('dropout_rate', 0.2, 0.5)
|
| 75 |
+
momentum = trial.suggest_float('momentum', 0.5, 0.9)
|
| 76 |
+
num_epochs = trial.suggest_int('num_epochs', 6000, 10000)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
model = SimpleNN(X_train.shape[1], hidden_dim, num_layers, dropout_rate).to(device)
|
| 80 |
+
model.apply(weights_init)
|
| 81 |
+
|
| 82 |
+
criterion = nn.MSELoss()
|
| 83 |
+
optimizer = optim.SGD(model.parameters(), lr=0.0001, momentum=momentum)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
for epoch in range(num_epochs):
|
| 87 |
+
model.train()
|
| 88 |
+
for inputs, targets in train_loader:
|
| 89 |
+
optimizer.zero_grad()
|
| 90 |
+
outputs = model(inputs)
|
| 91 |
+
loss = criterion(outputs, targets)
|
| 92 |
+
loss.backward()
|
| 93 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 94 |
+
optimizer.step()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
model.eval()
|
| 98 |
+
test_loss = 0
|
| 99 |
+
with torch.no_grad():
|
| 100 |
+
for inputs, targets in test_loader:
|
| 101 |
+
outputs = model(inputs)
|
| 102 |
+
test_loss += criterion(outputs, targets).item() * inputs.size(0)
|
| 103 |
+
|
| 104 |
+
test_loss /= len(test_loader.dataset)
|
| 105 |
+
|
| 106 |
+
trial.report(test_loss, epoch)
|
| 107 |
+
|
| 108 |
+
if trial.should_prune():
|
| 109 |
+
raise optuna.exceptions.TrialPruned()
|
| 110 |
+
|
| 111 |
+
return test_loss
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
study = optuna.create_study(direction='minimize')
|
| 115 |
+
study.optimize(objective, n_trials=200)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
print(f"Best trial parameters: {study.best_trial.params}")
|
| 119 |
+
print(f"Best trial test loss: {study.best_trial.value}")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
import optuna.visualization as vis
|
| 123 |
+
|
| 124 |
+
vis.plot_param_importances(study).show()
|
| 125 |
+
|
| 126 |
+
vis.plot_parallel_coordinate(study).show()
|
| 127 |
+
|
| 128 |
+
best_params = study.best_trial.params
|
| 129 |
+
|
| 130 |
+
model = SimpleNN(X_train.shape[1], best_params['hidden_dim'], best_params['num_layers'], best_params['dropout_rate']).to(device)
|
| 131 |
+
model.apply(weights_init)
|
| 132 |
+
|
| 133 |
+
criterion = nn.MSELoss()
|
| 134 |
+
optimizer = optim.SGD(model.parameters(), lr=0.0001, momentum=best_params['momentum'])
|
| 135 |
+
|
| 136 |
+
test_losses = []
|
| 137 |
+
for epoch in range(best_params['num_epochs']):
|
| 138 |
+
model.train()
|
| 139 |
+
for inputs, targets in train_loader:
|
| 140 |
+
optimizer.zero_grad()
|
| 141 |
+
outputs = model(inputs)
|
| 142 |
+
loss = criterion(outputs, targets)
|
| 143 |
+
loss.backward()
|
| 144 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 145 |
+
optimizer.step()
|
| 146 |
+
|
| 147 |
+
model.eval()
|
| 148 |
+
test_loss = 0
|
| 149 |
+
with torch.no_grad():
|
| 150 |
+
for inputs, targets in test_loader:
|
| 151 |
+
outputs = model(inputs)
|
| 152 |
+
test_loss += criterion(outputs, targets).item() * inputs.size(0)
|
| 153 |
+
|
| 154 |
+
test_loss /= len(test_loader.dataset)
|
| 155 |
+
|
| 156 |
+
if epoch % 100 == 0:
|
| 157 |
+
test_losses.append(test_loss)
|
| 158 |
+
print(f'Epoch {epoch+1}, Test Loss: {test_loss}')
|
| 159 |
+
|
| 160 |
+
print("Training completed with best hyperparameters.")
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
plt.figure(figsize=(10, 5))
|
| 164 |
+
plt.plot(range(1, len(test_losses) * 100, 100), test_losses, label='Test Loss')
|
| 165 |
+
plt.xlabel('Epoch')
|
| 166 |
+
plt.ylabel('Test Loss')
|
| 167 |
+
plt.title('Test Loss over Epochs')
|
| 168 |
+
plt.legend()
|
| 169 |
+
plt.show()
|
methane.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import matplotlib.cm as cm
|
| 5 |
+
from sklearn.model_selection import train_test_split
|
| 6 |
+
from sklearn.preprocessing import StandardScaler
|
| 7 |
+
from sklearn.metrics import r2_score
|
| 8 |
+
from scipy.stats import pearsonr
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.optim as optim
|
| 12 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
script_path = os.path.abspath(__file__)
|
| 17 |
+
script_dir = os.path.dirname(script_path)
|
| 18 |
+
os.chdir(script_dir)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
data = pd.read_csv('data.csv')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
X = data.drop(columns=['OS.time']).values
|
| 25 |
+
y = data['OS.time'].values
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
print(np.isnan(X).sum(), np.isnan(y).sum())
|
| 29 |
+
print(np.isinf(X).sum(), np.isinf(y).sum())
|
| 30 |
+
|
| 31 |
+
scaler = StandardScaler()
|
| 32 |
+
X_scaled = scaler.fit_transform(X)
|
| 33 |
+
|
| 34 |
+
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
|
| 35 |
+
|
| 36 |
+
X_train_tensor = torch.tensor(X_train, dtype=torch.float32)
|
| 37 |
+
y_train_tensor = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)
|
| 38 |
+
X_test_tensor = torch.tensor(X_test, dtype=torch.float32)
|
| 39 |
+
y_test_tensor = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)
|
| 40 |
+
|
| 41 |
+
train_dataset = TensorDataset(X_train_tensor, y_train_tensor)
|
| 42 |
+
test_dataset = TensorDataset(X_test_tensor, y_test_tensor)
|
| 43 |
+
|
| 44 |
+
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
|
| 45 |
+
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class SimpleNN(nn.Module):
|
| 49 |
+
def __init__(self, input_dim):
|
| 50 |
+
super(SimpleNN, self).__init__()
|
| 51 |
+
self.fc1 = nn.Linear(input_dim, 100)
|
| 52 |
+
self.dropout1 = nn.Dropout(0.5)
|
| 53 |
+
self.fc2 = nn.Linear(100, 100)
|
| 54 |
+
self.dropout2 = nn.Dropout(0.5)
|
| 55 |
+
self.fc3 = nn.Linear(100, 1)
|
| 56 |
+
|
| 57 |
+
def forward(self, x):
|
| 58 |
+
x = torch.relu(self.fc1(x))
|
| 59 |
+
x = self.dropout1(x)
|
| 60 |
+
x = torch.relu(self.fc2(x))
|
| 61 |
+
x = self.dropout2(x)
|
| 62 |
+
x = self.fc3(x)
|
| 63 |
+
return x
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def weights_init(m):
|
| 67 |
+
if isinstance(m, nn.Linear):
|
| 68 |
+
nn.init.kaiming_uniform_(m.weight)
|
| 69 |
+
nn.init.zeros_(m.bias)
|
| 70 |
+
|
| 71 |
+
model = SimpleNN(X_train.shape[1])
|
| 72 |
+
model.apply(weights_init)
|
| 73 |
+
|
| 74 |
+
criterion = nn.MSELoss()
|
| 75 |
+
optimizer = optim.SGD(model.parameters(), lr=0.0001, momentum=0.9)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
best_test_loss = float('inf')
|
| 79 |
+
best_model_state = None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
num_epochs = 10000
|
| 83 |
+
train_losses = []
|
| 84 |
+
test_losses = []
|
| 85 |
+
all_predictions = []
|
| 86 |
+
gradients = []
|
| 87 |
+
r2_scores = []
|
| 88 |
+
|
| 89 |
+
for epoch in range(num_epochs):
|
| 90 |
+
model.train()
|
| 91 |
+
train_loss = 0.0
|
| 92 |
+
epoch_gradients = []
|
| 93 |
+
for inputs, targets in train_loader:
|
| 94 |
+
optimizer.zero_grad()
|
| 95 |
+
outputs = model(inputs)
|
| 96 |
+
loss = criterion(outputs, targets)
|
| 97 |
+
loss.backward()
|
| 98 |
+
|
| 99 |
+
for param in model.parameters():
|
| 100 |
+
epoch_gradients.append(param.grad.abs().mean().item())
|
| 101 |
+
|
| 102 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 103 |
+
optimizer.step()
|
| 104 |
+
train_loss += loss.item()
|
| 105 |
+
|
| 106 |
+
train_loss /= len(train_loader)
|
| 107 |
+
train_losses.append(train_loss)
|
| 108 |
+
gradients.append(epoch_gradients)
|
| 109 |
+
print(f'Epoch {epoch+1}, Train Loss: {train_loss}')
|
| 110 |
+
|
| 111 |
+
model.eval()
|
| 112 |
+
test_loss = 0.0
|
| 113 |
+
predictions = []
|
| 114 |
+
with torch.no_grad():
|
| 115 |
+
for inputs, targets in test_loader:
|
| 116 |
+
outputs = model(inputs)
|
| 117 |
+
loss = criterion(outputs, targets)
|
| 118 |
+
test_loss += loss.item()
|
| 119 |
+
predictions.append(outputs.numpy())
|
| 120 |
+
|
| 121 |
+
test_loss /= len(test_loader)
|
| 122 |
+
test_losses.append(test_loss)
|
| 123 |
+
all_predictions.append(predictions)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
predictions_flat = np.concatenate(predictions).flatten()
|
| 127 |
+
r2 = r2_score(y_test, predictions_flat)
|
| 128 |
+
r2_scores.append(r2)
|
| 129 |
+
print(f'Epoch {epoch+1}, R^2: {r2}')
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
if test_loss < best_test_loss:
|
| 133 |
+
best_test_loss = test_loss
|
| 134 |
+
best_model_state = model.state_dict()
|
| 135 |
+
torch.save(best_model_state, 'best_model.pth')
|
| 136 |
+
print(f'Saved new best model at epoch {epoch+1} with test loss {test_loss}')
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
plt.figure(figsize=(10, 5))
|
| 143 |
+
plt.plot(range(1, num_epochs + 1), train_losses, label='Train Loss')
|
| 144 |
+
plt.plot(range(1, num_epochs + 1), test_losses, label='Test Loss')
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
window_size = 50
|
| 148 |
+
train_losses_ma = pd.Series(train_losses).rolling(window=window_size).mean()
|
| 149 |
+
test_losses_ma = pd.Series(test_losses).rolling(window=window_size).mean()
|
| 150 |
+
|
| 151 |
+
plt.plot(range(1, num_epochs + 1), train_losses_ma, label='Train Loss (MA)', linestyle='--')
|
| 152 |
+
plt.plot(range(1, num_epochs + 1), test_losses_ma, label='Test Loss (MA)', linestyle='--')
|
| 153 |
+
|
| 154 |
+
plt.xlabel('Epoch')
|
| 155 |
+
plt.ylabel('Loss')
|
| 156 |
+
plt.title('Train and Test Loss with Moving Average')
|
| 157 |
+
plt.legend()
|
| 158 |
+
plt.savefig('train_test_loss.png')
|
| 159 |
+
plt.close()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
final_predictions = np.array(all_predictions[-1]).flatten()
|
| 163 |
+
actuals = y_test_tensor.numpy().flatten()
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
correlation, p_value = pearsonr(actuals, final_predictions)
|
| 167 |
+
print(f'Pearson Correlation: {correlation}')
|
| 168 |
+
print(f'P-value: {p_value}')
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
plt.figure(figsize=(10, 5))
|
| 172 |
+
plt.scatter(actuals, final_predictions, color='blue', label=f'Predictions vs Actuals (r={correlation:.2f}, p={p_value:.2g})')
|
| 173 |
+
plt.plot([min(actuals), max(actuals)], [min(actuals), max(actuals)], color='red', linestyle='--', label='Ideal Fit')
|
| 174 |
+
plt.xlabel('Actual OS.time')
|
| 175 |
+
plt.ylabel('Predicted OS.time')
|
| 176 |
+
plt.title('Predictions vs Actuals')
|
| 177 |
+
plt.legend()
|
| 178 |
+
plt.savefig('predictions_vs_actuals.png')
|
| 179 |
+
plt.close()
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
errors = final_predictions - actuals
|
| 183 |
+
plt.figure(figsize=(10, 5))
|
| 184 |
+
plt.hist(errors, bins=30, color='purple', alpha=0.7)
|
| 185 |
+
plt.xlabel('Prediction Error')
|
| 186 |
+
plt.ylabel('Frequency')
|
| 187 |
+
plt.title('Error Distribution')
|
| 188 |
+
plt.savefig('error_distribution.png')
|
| 189 |
+
plt.close()
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
actuals = y_test_tensor.numpy()
|
| 193 |
+
colors = cm.viridis(np.linspace(0, 1, num_epochs))
|
| 194 |
+
|
| 195 |
+
plt.figure(figsize=(10, 5))
|
| 196 |
+
plt.plot(actuals, label='Actual Values', color='b', marker='o', linestyle='-')
|
| 197 |
+
|
| 198 |
+
for i in range(0, num_epochs, max(1, num_epochs // 100)):
|
| 199 |
+
predictions = np.array(all_predictions[i]).flatten()
|
| 200 |
+
plt.plot(predictions, label=f'Epoch {i+1}', color=colors[i], linestyle='--')
|
| 201 |
+
|
| 202 |
+
plt.xlabel('Sample Index')
|
| 203 |
+
plt.ylabel('OS.time')
|
| 204 |
+
plt.title('Actual vs Predicted Values Over Time')
|
| 205 |
+
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
|
| 206 |
+
plt.savefig('actual_vs_predicted_over_time.png')
|
| 207 |
+
plt.close()
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
for i, layer in enumerate(model.children()):
|
| 211 |
+
if isinstance(layer, nn.Linear):
|
| 212 |
+
plt.figure(figsize=(10, 5))
|
| 213 |
+
plt.hist(layer.weight.detach().numpy().flatten(), bins=30, alpha=0.6, color='blue')
|
| 214 |
+
plt.xlabel(f'Layer {i+1} Weights')
|
| 215 |
+
plt.ylabel('Frequency')
|
| 216 |
+
plt.title(f'Weight Distribution of Layer {i+1}')
|
| 217 |
+
plt.savefig(f'layer_{i+1}_weight_distribution.png')
|
| 218 |
+
plt.close()
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
importances = np.abs(model.fc1.weight.detach().numpy()).sum(axis=0)
|
| 222 |
+
indices = np.argsort(importances)
|
| 223 |
+
|
| 224 |
+
plt.figure(figsize=(10, 5))
|
| 225 |
+
plt.barh(range(X_train.shape[1]), importances[indices], align='center')
|
| 226 |
+
plt.xlabel('Importance')
|
| 227 |
+
plt.ylabel('Feature Index')
|
| 228 |
+
plt.title('Feature Importances in the First Layer')
|
| 229 |
+
plt.savefig('feature_importances.png')
|
| 230 |
+
plt.close()
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
for i, layer in enumerate(model.children()):
|
| 234 |
+
if isinstance(layer, nn.Linear):
|
| 235 |
+
plt.figure(figsize=(10, 5))
|
| 236 |
+
plt.imshow(layer.weight.detach().numpy(), aspect='auto', cmap='viridis')
|
| 237 |
+
plt.colorbar()
|
| 238 |
+
plt.title(f'Weight Heatmap of Layer {i+1}')
|
| 239 |
+
plt.xlabel('Input Features')
|
| 240 |
+
plt.ylabel('Neurons')
|
| 241 |
+
plt.savefig(f'layer_{i+1}_weight_heatmap.png')
|
| 242 |
+
plt.close()
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
plt.figure(figsize=(10, 5))
|
| 246 |
+
plt.plot(range(1, num_epochs + 1), r2_scores, label='R^2 Score')
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
r2_scores_ma = pd.Series(r2_scores).rolling(window=window_size).mean()
|
| 250 |
+
plt.plot(range(1, num_epochs + 1), r2_scores_ma, label='R^2 Score (MA)', linestyle='--')
|
| 251 |
+
|
| 252 |
+
plt.xlabel('Epoch')
|
| 253 |
+
plt.ylabel('R^2 Score')
|
| 254 |
+
plt.title('R^2 Score over Epochs')
|
| 255 |
+
plt.legend()
|
| 256 |
+
plt.savefig('r2_over_epochs.png')
|
| 257 |
+
plt.close()
|
use_pre_pca.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
from sklearn.preprocessing import StandardScaler
|
| 3 |
+
import joblib
|
| 4 |
+
import os
|
| 5 |
+
script_path=os.path.abspath(__file__)
|
| 6 |
+
script_dir=os.path.dirname(script_path)
|
| 7 |
+
os.chdir(script_dir)
|
| 8 |
+
|
| 9 |
+
pca_model_path = 'pca_model.pkl'
|
| 10 |
+
loaded_pca = joblib.load(pca_model_path)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
file_path = 'TCGA-LGG.methylation450.tsv'
|
| 15 |
+
new_data = pd.read_csv(file_path, sep='\t', index_col=0)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
new_data.dropna(inplace=True)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
scaler = StandardScaler()
|
| 23 |
+
scaled_new_data = scaler.fit_transform(new_data.T)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
new_principal_components = loaded_pca.transform(scaled_new_data)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
sample_ids = new_data.columns
|
| 30 |
+
new_principal_df = pd.DataFrame(data=new_principal_components, columns=[f'Principal Component {i+1}' for i in range(loaded_pca.n_components_)], index=sample_ids)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
print(new_principal_df)
|
| 34 |
+
|
| 35 |
+
output_file_path = 'pca_principal_components.csv'
|
| 36 |
+
new_principal_df.to_csv(output_file_path)
|
webplot.png
ADDED
|
Git LFS Details
|
webplot.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import networkx as nx
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import numpy as np
|
| 6 |
+
import os
|
| 7 |
+
script_path=os.path.abspath(__file__)
|
| 8 |
+
script_dir=os.path.dirname(script_path)
|
| 9 |
+
os.chdir(script_dir)
|
| 10 |
+
class SimpleNN(nn.Module):
|
| 11 |
+
def __init__(self, input_dim):
|
| 12 |
+
super(SimpleNN, self).__init__()
|
| 13 |
+
self.fc1 = nn.Linear(input_dim, 100)
|
| 14 |
+
self.dropout1 = nn.Dropout(0.5)
|
| 15 |
+
self.fc2 = nn.Linear(100, 100)
|
| 16 |
+
self.dropout2 = nn.Dropout(0.5)
|
| 17 |
+
self.fc3 = nn.Linear(100, 1)
|
| 18 |
+
|
| 19 |
+
def forward(self, x):
|
| 20 |
+
x = torch.relu(self.fc1(x))
|
| 21 |
+
x = self.dropout1(x)
|
| 22 |
+
x = torch.relu(self.fc2(x))
|
| 23 |
+
x = self.dropout2(x)
|
| 24 |
+
x = self.fc3(x)
|
| 25 |
+
return x
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
input_dim = 51
|
| 29 |
+
model = SimpleNN(input_dim)
|
| 30 |
+
model.load_state_dict(torch.load('best_model.pth'))
|
| 31 |
+
model.eval()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
weights = []
|
| 35 |
+
weights.append(model.fc1.weight.detach().numpy())
|
| 36 |
+
weights.append(model.fc2.weight.detach().numpy())
|
| 37 |
+
weights.append(model.fc3.weight.detach().numpy())
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
layers = [input_dim, 100, 100, 1]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def draw_neural_network(layers, weights):
|
| 44 |
+
G = nx.Graph()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
pos = {}
|
| 48 |
+
layer_nodes = []
|
| 49 |
+
for i, num_nodes in enumerate(layers):
|
| 50 |
+
layer_nodes.append([])
|
| 51 |
+
for j in range(num_nodes):
|
| 52 |
+
node_name = f'L{i}_N{j}'
|
| 53 |
+
layer_nodes[-1].append(node_name)
|
| 54 |
+
pos[node_name] = (i, -j + num_nodes // 2)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
edges = []
|
| 58 |
+
edge_colors = []
|
| 59 |
+
for i in range(len(layers) - 1):
|
| 60 |
+
for j, node in enumerate(layer_nodes[i]):
|
| 61 |
+
for k, next_node in enumerate(layer_nodes[i+1]):
|
| 62 |
+
weight = weights[i][k, j]
|
| 63 |
+
edges.append((node, next_node))
|
| 64 |
+
edge_colors.append(weight)
|
| 65 |
+
|
| 66 |
+
G.add_edges_from(edges)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
plt.figure(figsize=(10, 10))
|
| 70 |
+
nx.draw(G, pos, with_labels=False, node_size=700, node_color='lightblue',
|
| 71 |
+
edge_color=edge_colors, edge_cmap=plt.cm.viridis,
|
| 72 |
+
width=2, edge_vmin=min(edge_colors), edge_vmax=max(edge_colors))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
for key, value in pos.items():
|
| 76 |
+
plt.text(value[0], value[1] + 0.1, key, ha='center', va='center')
|
| 77 |
+
|
| 78 |
+
plt.title("Neural Network Visualization")
|
| 79 |
+
plt.show()
|
| 80 |
+
|
| 81 |
+
draw_neural_network(layers, weights)
|