gpbench 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gp_agent_tool/compute_dataset_feature.py +67 -0
- gp_agent_tool/config.py +65 -0
- gp_agent_tool/experience/create_masked_dataset_summary.py +97 -0
- gp_agent_tool/experience/dataset_summary_info.py +13 -0
- gp_agent_tool/experience/experience_info.py +12 -0
- gp_agent_tool/experience/get_matched_experience.py +111 -0
- gp_agent_tool/llm_client.py +119 -0
- gp_agent_tool/logging_utils.py +24 -0
- gp_agent_tool/main.py +347 -0
- gp_agent_tool/read_agent/__init__.py +46 -0
- gp_agent_tool/read_agent/nodes.py +674 -0
- gp_agent_tool/read_agent/prompts.py +547 -0
- gp_agent_tool/read_agent/python_repl_tool.py +165 -0
- gp_agent_tool/read_agent/state.py +101 -0
- gp_agent_tool/read_agent/workflow.py +54 -0
- gpbench/__init__.py +25 -0
- gpbench/_selftest.py +104 -0
- gpbench/method_class/BayesA/BayesA_class.py +141 -0
- gpbench/method_class/BayesA/__init__.py +5 -0
- gpbench/method_class/BayesA/_bayesfromR.py +96 -0
- gpbench/method_class/BayesA/_param_free_base_model.py +84 -0
- gpbench/method_class/BayesA/bayesAfromR.py +16 -0
- gpbench/method_class/BayesB/BayesB_class.py +140 -0
- gpbench/method_class/BayesB/__init__.py +5 -0
- gpbench/method_class/BayesB/_bayesfromR.py +96 -0
- gpbench/method_class/BayesB/_param_free_base_model.py +84 -0
- gpbench/method_class/BayesB/bayesBfromR.py +16 -0
- gpbench/method_class/BayesC/BayesC_class.py +141 -0
- gpbench/method_class/BayesC/__init__.py +4 -0
- gpbench/method_class/BayesC/_bayesfromR.py +96 -0
- gpbench/method_class/BayesC/_param_free_base_model.py +84 -0
- gpbench/method_class/BayesC/bayesCfromR.py +16 -0
- gpbench/method_class/CropARNet/CropARNet_class.py +186 -0
- gpbench/method_class/CropARNet/CropARNet_he_class.py +154 -0
- gpbench/method_class/CropARNet/__init__.py +5 -0
- gpbench/method_class/CropARNet/base_CropARNet_class.py +178 -0
- gpbench/method_class/Cropformer/Cropformer_class.py +308 -0
- gpbench/method_class/Cropformer/__init__.py +5 -0
- gpbench/method_class/Cropformer/cropformer_he_class.py +221 -0
- gpbench/method_class/DL_GWAS/DL_GWAS_class.py +250 -0
- gpbench/method_class/DL_GWAS/DL_GWAS_he_class.py +169 -0
- gpbench/method_class/DL_GWAS/__init__.py +5 -0
- gpbench/method_class/DNNGP/DNNGP_class.py +163 -0
- gpbench/method_class/DNNGP/DNNGP_he_class.py +138 -0
- gpbench/method_class/DNNGP/__init__.py +5 -0
- gpbench/method_class/DNNGP/base_dnngp_class.py +116 -0
- gpbench/method_class/DeepCCR/DeepCCR_class.py +172 -0
- gpbench/method_class/DeepCCR/DeepCCR_he_class.py +161 -0
- gpbench/method_class/DeepCCR/__init__.py +5 -0
- gpbench/method_class/DeepCCR/base_DeepCCR_class.py +209 -0
- gpbench/method_class/DeepGS/DeepGS_class.py +184 -0
- gpbench/method_class/DeepGS/DeepGS_he_class.py +150 -0
- gpbench/method_class/DeepGS/__init__.py +5 -0
- gpbench/method_class/DeepGS/base_deepgs_class.py +153 -0
- gpbench/method_class/EIR/EIR_class.py +276 -0
- gpbench/method_class/EIR/EIR_he_class.py +184 -0
- gpbench/method_class/EIR/__init__.py +5 -0
- gpbench/method_class/EIR/utils/__init__.py +0 -0
- gpbench/method_class/EIR/utils/array_output_modules.py +97 -0
- gpbench/method_class/EIR/utils/common.py +65 -0
- gpbench/method_class/EIR/utils/lcl_layers.py +235 -0
- gpbench/method_class/EIR/utils/logging.py +59 -0
- gpbench/method_class/EIR/utils/mlp_layers.py +92 -0
- gpbench/method_class/EIR/utils/models_locally_connected.py +642 -0
- gpbench/method_class/EIR/utils/transformer_models.py +546 -0
- gpbench/method_class/ElasticNet/ElasticNet_class.py +133 -0
- gpbench/method_class/ElasticNet/ElasticNet_he_class.py +91 -0
- gpbench/method_class/ElasticNet/__init__.py +5 -0
- gpbench/method_class/G2PDeep/G2PDeep_he_class.py +217 -0
- gpbench/method_class/G2PDeep/G2Pdeep_class.py +205 -0
- gpbench/method_class/G2PDeep/__init__.py +5 -0
- gpbench/method_class/G2PDeep/base_G2PDeep_class.py +209 -0
- gpbench/method_class/GBLUP/GBLUP_class.py +183 -0
- gpbench/method_class/GBLUP/__init__.py +5 -0
- gpbench/method_class/GEFormer/GEFormer_class.py +169 -0
- gpbench/method_class/GEFormer/GEFormer_he_class.py +137 -0
- gpbench/method_class/GEFormer/__init__.py +5 -0
- gpbench/method_class/GEFormer/gMLP_class.py +357 -0
- gpbench/method_class/LightGBM/LightGBM_class.py +224 -0
- gpbench/method_class/LightGBM/LightGBM_he_class.py +121 -0
- gpbench/method_class/LightGBM/__init__.py +5 -0
- gpbench/method_class/RF/RF_GPU_class.py +165 -0
- gpbench/method_class/RF/RF_GPU_he_class.py +124 -0
- gpbench/method_class/RF/__init__.py +5 -0
- gpbench/method_class/SVC/SVC_GPU.py +181 -0
- gpbench/method_class/SVC/SVC_GPU_he.py +106 -0
- gpbench/method_class/SVC/__init__.py +5 -0
- gpbench/method_class/SoyDNGP/AlexNet_206_class.py +179 -0
- gpbench/method_class/SoyDNGP/SoyDNGP_class.py +189 -0
- gpbench/method_class/SoyDNGP/SoyDNGP_he_class.py +112 -0
- gpbench/method_class/SoyDNGP/__init__.py +5 -0
- gpbench/method_class/XGBoost/XGboost_GPU_class.py +198 -0
- gpbench/method_class/XGBoost/XGboost_GPU_he_class.py +178 -0
- gpbench/method_class/XGBoost/__init__.py +5 -0
- gpbench/method_class/__init__.py +52 -0
- gpbench/method_class/rrBLUP/__init__.py +5 -0
- gpbench/method_class/rrBLUP/rrBLUP_class.py +140 -0
- gpbench/method_reg/BayesA/BayesA.py +116 -0
- gpbench/method_reg/BayesA/__init__.py +5 -0
- gpbench/method_reg/BayesA/_bayesfromR.py +96 -0
- gpbench/method_reg/BayesA/_param_free_base_model.py +84 -0
- gpbench/method_reg/BayesA/bayesAfromR.py +16 -0
- gpbench/method_reg/BayesB/BayesB.py +117 -0
- gpbench/method_reg/BayesB/__init__.py +5 -0
- gpbench/method_reg/BayesB/_bayesfromR.py +96 -0
- gpbench/method_reg/BayesB/_param_free_base_model.py +84 -0
- gpbench/method_reg/BayesB/bayesBfromR.py +16 -0
- gpbench/method_reg/BayesC/BayesC.py +115 -0
- gpbench/method_reg/BayesC/__init__.py +5 -0
- gpbench/method_reg/BayesC/_bayesfromR.py +96 -0
- gpbench/method_reg/BayesC/_param_free_base_model.py +84 -0
- gpbench/method_reg/BayesC/bayesCfromR.py +16 -0
- gpbench/method_reg/CropARNet/CropARNet.py +159 -0
- gpbench/method_reg/CropARNet/CropARNet_Hyperparameters.py +109 -0
- gpbench/method_reg/CropARNet/__init__.py +5 -0
- gpbench/method_reg/CropARNet/base_CropARNet.py +137 -0
- gpbench/method_reg/Cropformer/Cropformer.py +313 -0
- gpbench/method_reg/Cropformer/Cropformer_Hyperparameters.py +250 -0
- gpbench/method_reg/Cropformer/__init__.py +5 -0
- gpbench/method_reg/DL_GWAS/DL_GWAS.py +186 -0
- gpbench/method_reg/DL_GWAS/DL_GWAS_Hyperparameters.py +125 -0
- gpbench/method_reg/DL_GWAS/__init__.py +5 -0
- gpbench/method_reg/DNNGP/DNNGP.py +157 -0
- gpbench/method_reg/DNNGP/DNNGP_Hyperparameters.py +118 -0
- gpbench/method_reg/DNNGP/__init__.py +5 -0
- gpbench/method_reg/DNNGP/base_dnngp.py +101 -0
- gpbench/method_reg/DeepCCR/DeepCCR.py +149 -0
- gpbench/method_reg/DeepCCR/DeepCCR_Hyperparameters.py +110 -0
- gpbench/method_reg/DeepCCR/__init__.py +5 -0
- gpbench/method_reg/DeepCCR/base_DeepCCR.py +171 -0
- gpbench/method_reg/DeepGS/DeepGS.py +165 -0
- gpbench/method_reg/DeepGS/DeepGS_Hyperparameters.py +114 -0
- gpbench/method_reg/DeepGS/__init__.py +5 -0
- gpbench/method_reg/DeepGS/base_deepgs.py +98 -0
- gpbench/method_reg/EIR/EIR.py +258 -0
- gpbench/method_reg/EIR/EIR_Hyperparameters.py +178 -0
- gpbench/method_reg/EIR/__init__.py +5 -0
- gpbench/method_reg/EIR/utils/__init__.py +0 -0
- gpbench/method_reg/EIR/utils/array_output_modules.py +97 -0
- gpbench/method_reg/EIR/utils/common.py +65 -0
- gpbench/method_reg/EIR/utils/lcl_layers.py +235 -0
- gpbench/method_reg/EIR/utils/logging.py +59 -0
- gpbench/method_reg/EIR/utils/mlp_layers.py +92 -0
- gpbench/method_reg/EIR/utils/models_locally_connected.py +642 -0
- gpbench/method_reg/EIR/utils/transformer_models.py +546 -0
- gpbench/method_reg/ElasticNet/ElasticNet.py +123 -0
- gpbench/method_reg/ElasticNet/ElasticNet_he.py +83 -0
- gpbench/method_reg/ElasticNet/__init__.py +5 -0
- gpbench/method_reg/G2PDeep/G2PDeep_Hyperparameters.py +107 -0
- gpbench/method_reg/G2PDeep/G2Pdeep.py +166 -0
- gpbench/method_reg/G2PDeep/__init__.py +5 -0
- gpbench/method_reg/G2PDeep/base_G2PDeep.py +209 -0
- gpbench/method_reg/GBLUP/GBLUP_R.py +182 -0
- gpbench/method_reg/GBLUP/__init__.py +5 -0
- gpbench/method_reg/GEFormer/GEFormer.py +164 -0
- gpbench/method_reg/GEFormer/GEFormer_Hyperparameters.py +106 -0
- gpbench/method_reg/GEFormer/__init__.py +5 -0
- gpbench/method_reg/GEFormer/gMLP.py +341 -0
- gpbench/method_reg/LightGBM/LightGBM.py +237 -0
- gpbench/method_reg/LightGBM/LightGBM_Hyperparameters.py +77 -0
- gpbench/method_reg/LightGBM/__init__.py +5 -0
- gpbench/method_reg/MVP/MVP.py +182 -0
- gpbench/method_reg/MVP/MVP_Hyperparameters.py +126 -0
- gpbench/method_reg/MVP/__init__.py +5 -0
- gpbench/method_reg/MVP/base_MVP.py +113 -0
- gpbench/method_reg/RF/RF_GPU.py +174 -0
- gpbench/method_reg/RF/RF_Hyperparameters.py +163 -0
- gpbench/method_reg/RF/__init__.py +5 -0
- gpbench/method_reg/SVC/SVC_GPU.py +194 -0
- gpbench/method_reg/SVC/SVC_Hyperparameters.py +107 -0
- gpbench/method_reg/SVC/__init__.py +5 -0
- gpbench/method_reg/SoyDNGP/AlexNet_206.py +185 -0
- gpbench/method_reg/SoyDNGP/SoyDNGP.py +179 -0
- gpbench/method_reg/SoyDNGP/SoyDNGP_Hyperparameters.py +105 -0
- gpbench/method_reg/SoyDNGP/__init__.py +5 -0
- gpbench/method_reg/XGBoost/XGboost_GPU.py +188 -0
- gpbench/method_reg/XGBoost/XGboost_Hyperparameters.py +167 -0
- gpbench/method_reg/XGBoost/__init__.py +5 -0
- gpbench/method_reg/__init__.py +55 -0
- gpbench/method_reg/rrBLUP/__init__.py +5 -0
- gpbench/method_reg/rrBLUP/rrBLUP.py +123 -0
- gpbench-1.0.0.dist-info/METADATA +379 -0
- gpbench-1.0.0.dist-info/RECORD +188 -0
- gpbench-1.0.0.dist-info/WHEEL +5 -0
- gpbench-1.0.0.dist-info/entry_points.txt +2 -0
- gpbench-1.0.0.dist-info/top_level.txt +3 -0
- tests/test_import.py +80 -0
- tests/test_method.py +232 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import time
|
|
3
|
+
import psutil
|
|
4
|
+
import argparse
|
|
5
|
+
import random
|
|
6
|
+
import torch
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import swanlab
|
|
10
|
+
import pynvml
|
|
11
|
+
|
|
12
|
+
from sklearn.model_selection import StratifiedKFold
|
|
13
|
+
from sklearn.preprocessing import LabelEncoder
|
|
14
|
+
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
import cupy as cp
|
|
18
|
+
from cuml.svm import SVC as cuSVC
|
|
19
|
+
CUML_AVAILABLE = True
|
|
20
|
+
except ImportError:
|
|
21
|
+
from sklearn.svm import SVC
|
|
22
|
+
CUML_AVAILABLE = False
|
|
23
|
+
|
|
24
|
+
from . import SVC_GPU_he
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def parse_args():
|
|
28
|
+
parser = argparse.ArgumentParser()
|
|
29
|
+
parser.add_argument('--methods', type=str, default='SVR/')
|
|
30
|
+
parser.add_argument('--species', type=str, default='')
|
|
31
|
+
parser.add_argument('--phe', type=str, default='')
|
|
32
|
+
parser.add_argument('--data_dir', type=str, default='../../data/')
|
|
33
|
+
parser.add_argument('--result_dir', type=str, default='result/')
|
|
34
|
+
|
|
35
|
+
parser.add_argument('--C', type=float, default=1.0)
|
|
36
|
+
parser.add_argument('--kernel', type=str, default='rbf')
|
|
37
|
+
parser.add_argument('--gamma', type=str, default='scale')
|
|
38
|
+
parser.add_argument('--degree', type=int, default=3)
|
|
39
|
+
parser.add_argument('--use_gpu',default=True)
|
|
40
|
+
|
|
41
|
+
return parser.parse_args()
|
|
42
|
+
|
|
43
|
+
def set_seed(seed=42):
|
|
44
|
+
random.seed(seed)
|
|
45
|
+
np.random.seed(seed)
|
|
46
|
+
torch.manual_seed(seed)
|
|
47
|
+
|
|
48
|
+
def load_data(args):
|
|
49
|
+
X = np.load(os.path.join(args.data_dir, args.species, 'genotype.npz'))["arr_0"]
|
|
50
|
+
Y = np.load(os.path.join(args.data_dir, args.species, 'phenotype.npz'))["arr_0"]
|
|
51
|
+
print(f"Samples: {X.shape[0]}, SNPs: {X.shape[1]}")
|
|
52
|
+
return X, Y
|
|
53
|
+
|
|
54
|
+
def get_gpu_mem_by_pid(pid, handle):
|
|
55
|
+
procs = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
|
|
56
|
+
for p in procs:
|
|
57
|
+
if p.pid == pid:
|
|
58
|
+
return p.usedGpuMemory / 1024**2
|
|
59
|
+
return 0.0
|
|
60
|
+
|
|
61
|
+
def run_cv(args, X, y, handle=None):
|
|
62
|
+
result_dir = os.path.join(args.result_dir, args.methods + args.species)
|
|
63
|
+
os.makedirs(result_dir, exist_ok=True)
|
|
64
|
+
|
|
65
|
+
use_gpu = args.use_gpu and CUML_AVAILABLE
|
|
66
|
+
kf = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)
|
|
67
|
+
|
|
68
|
+
le = LabelEncoder()
|
|
69
|
+
y_all = le.fit_transform(y)
|
|
70
|
+
np.save(os.path.join(result_dir, 'label_mapping.npy'), le.classes_)
|
|
71
|
+
|
|
72
|
+
all_acc, all_prec, all_rec, all_f1 = [], [], [], []
|
|
73
|
+
start_time = time.time()
|
|
74
|
+
process = psutil.Process(os.getpid())
|
|
75
|
+
|
|
76
|
+
for fold, (train_idx, test_idx) in enumerate(kf.split(X, y_all)):
|
|
77
|
+
fold_start = time.time()
|
|
78
|
+
print(f"\n===== Fold {fold} =====")
|
|
79
|
+
|
|
80
|
+
X_train, X_test = X[train_idx], X[test_idx]
|
|
81
|
+
y_train, y_test = y_all[train_idx], y_all[test_idx]
|
|
82
|
+
|
|
83
|
+
if use_gpu:
|
|
84
|
+
X_train_gpu = cp.asarray(X_train, dtype=cp.float32)
|
|
85
|
+
X_test_gpu = cp.asarray(X_test, dtype=cp.float32)
|
|
86
|
+
y_train_gpu = cp.asarray(y_train, dtype=cp.int32)
|
|
87
|
+
|
|
88
|
+
model = cuSVC(
|
|
89
|
+
C=args.C,
|
|
90
|
+
kernel=args.kernel,
|
|
91
|
+
gamma=args.gamma,
|
|
92
|
+
degree=args.degree,
|
|
93
|
+
probability=True
|
|
94
|
+
)
|
|
95
|
+
model.fit(X_train_gpu, y_train_gpu)
|
|
96
|
+
y_pred = model.predict(X_test_gpu)
|
|
97
|
+
y_pred = cp.asnumpy(y_pred)
|
|
98
|
+
else:
|
|
99
|
+
model = SVC(
|
|
100
|
+
C=args.C,
|
|
101
|
+
kernel=args.kernel,
|
|
102
|
+
gamma=args.gamma,
|
|
103
|
+
degree=args.degree,
|
|
104
|
+
probability=True
|
|
105
|
+
)
|
|
106
|
+
model.fit(X_train, y_train)
|
|
107
|
+
y_pred = model.predict(X_test)
|
|
108
|
+
|
|
109
|
+
acc = accuracy_score(y_test, y_pred)
|
|
110
|
+
prec, rec, f1, _ = precision_recall_fscore_support(
|
|
111
|
+
y_test,
|
|
112
|
+
y_pred,
|
|
113
|
+
average="macro",
|
|
114
|
+
zero_division=0
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
all_acc.append(acc)
|
|
118
|
+
all_prec.append(prec)
|
|
119
|
+
all_rec.append(rec)
|
|
120
|
+
all_f1.append(f1)
|
|
121
|
+
|
|
122
|
+
fold_time = time.time() - fold_start
|
|
123
|
+
gpu_mem = get_gpu_mem_by_pid(os.getpid(), handle) if (use_gpu and handle) else 0.0 # 修正:检查handle
|
|
124
|
+
cpu_mem = process.memory_info().rss / 1024**2
|
|
125
|
+
|
|
126
|
+
print(
|
|
127
|
+
f"Fold {fold}: "
|
|
128
|
+
f"ACC={acc:.4f}, "
|
|
129
|
+
f"PREC={prec:.4f}, "
|
|
130
|
+
f"REC={rec:.4f}, "
|
|
131
|
+
f"F1={f1:.4f}, "
|
|
132
|
+
f"Time={fold_time:.2f}s, "
|
|
133
|
+
f"GPU={gpu_mem:.2f}MB, "
|
|
134
|
+
f"CPU={cpu_mem:.2f}MB"
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
df = pd.DataFrame({
|
|
138
|
+
"Y_test": le.inverse_transform(y_test),
|
|
139
|
+
"Y_pred": le.inverse_transform(y_pred)
|
|
140
|
+
})
|
|
141
|
+
df.to_csv(os.path.join(result_dir, f"fold{fold}.csv"), index=False)
|
|
142
|
+
|
|
143
|
+
# ===== Summary =====
|
|
144
|
+
print("\n===== CV Summary =====")
|
|
145
|
+
print(f"ACC : {np.mean(all_acc):.4f} ± {np.std(all_acc):.4f}")
|
|
146
|
+
print(f"PREC: {np.mean(all_prec):.4f} ± {np.std(all_prec):.4f}")
|
|
147
|
+
print(f"REC : {np.mean(all_rec):.4f} ± {np.std(all_rec):.4f}")
|
|
148
|
+
print(f"F1 : {np.mean(all_f1):.4f} ± {np.std(all_f1):.4f}")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def SVC_class():
|
|
152
|
+
set_seed(42)
|
|
153
|
+
pynvml.nvmlInit()
|
|
154
|
+
handle = pynvml.nvmlDeviceGetHandleByIndex(0)
|
|
155
|
+
|
|
156
|
+
args = parse_args()
|
|
157
|
+
all_species = ["Human/Sim/"]
|
|
158
|
+
|
|
159
|
+
for species in all_species:
|
|
160
|
+
args.species = species
|
|
161
|
+
X, Y = load_data(args)
|
|
162
|
+
label = Y[:, 0]
|
|
163
|
+
best_params = SVC_GPU_he.Hyperparameter(X, label)
|
|
164
|
+
args.C = best_params['C']
|
|
165
|
+
args.kernel = best_params['kernel']
|
|
166
|
+
args.gamma = best_params['gamma']
|
|
167
|
+
args.degree = best_params['degree']
|
|
168
|
+
|
|
169
|
+
start_time = time.time()
|
|
170
|
+
run_cv(args, X, label, handle)
|
|
171
|
+
|
|
172
|
+
elapsed_time = time.time() - start_time
|
|
173
|
+
print(f"Total running time: {elapsed_time:.2f} s")
|
|
174
|
+
print("Successfully finished!")
|
|
175
|
+
|
|
176
|
+
if CUML_AVAILABLE:
|
|
177
|
+
cp.get_default_memory_pool().free_all_blocks()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
if __name__ == "__main__":
|
|
181
|
+
SVC_class()
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import gc
|
|
2
|
+
import random
|
|
3
|
+
import time
|
|
4
|
+
import torch
|
|
5
|
+
import optuna
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from sklearn.model_selection import StratifiedKFold
|
|
9
|
+
from sklearn.preprocessing import LabelEncoder
|
|
10
|
+
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
import cupy as cp
|
|
14
|
+
from cuml.svm import SVC as cuSVC
|
|
15
|
+
CUML_AVAILABLE = True
|
|
16
|
+
except ImportError:
|
|
17
|
+
from sklearn.svm import SVC
|
|
18
|
+
CUML_AVAILABLE = False
|
|
19
|
+
|
|
20
|
+
def set_seed(seed=42):
|
|
21
|
+
random.seed(seed)
|
|
22
|
+
np.random.seed(seed)
|
|
23
|
+
torch.manual_seed(seed)
|
|
24
|
+
if torch.cuda.is_available():
|
|
25
|
+
torch.cuda.manual_seed_all(seed)
|
|
26
|
+
torch.backends.cudnn.deterministic = True
|
|
27
|
+
torch.backends.cudnn.benchmark = False
|
|
28
|
+
|
|
29
|
+
def run_cv_eval(data, label, C, kernel, gamma, degree):
|
|
30
|
+
kf = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)
|
|
31
|
+
|
|
32
|
+
le = LabelEncoder()
|
|
33
|
+
y_all = le.fit_transform(label)
|
|
34
|
+
|
|
35
|
+
accs, precs, recs, f1s = [], [], [], []
|
|
36
|
+
|
|
37
|
+
for fold, (train_idx, test_idx) in enumerate(kf.split(data, y_all)):
|
|
38
|
+
print(f"===== Fold {fold+1} =====")
|
|
39
|
+
X_train, X_test = data[train_idx], data[test_idx]
|
|
40
|
+
y_train, y_test = y_all[train_idx], y_all[test_idx]
|
|
41
|
+
|
|
42
|
+
if CUML_AVAILABLE:
|
|
43
|
+
X_train_gpu = cp.asarray(X_train, dtype=cp.float32)
|
|
44
|
+
X_test_gpu = cp.asarray(X_test, dtype=cp.float32)
|
|
45
|
+
y_train_gpu = cp.asarray(y_train, dtype=cp.int32)
|
|
46
|
+
|
|
47
|
+
model = cuSVC(
|
|
48
|
+
C=C,
|
|
49
|
+
kernel=kernel,
|
|
50
|
+
gamma=gamma,
|
|
51
|
+
degree=degree,
|
|
52
|
+
probability=True
|
|
53
|
+
)
|
|
54
|
+
model.fit(X_train_gpu, y_train_gpu)
|
|
55
|
+
y_pred = model.predict(X_test_gpu)
|
|
56
|
+
y_pred = cp.asnumpy(y_pred)
|
|
57
|
+
else:
|
|
58
|
+
model = SVC(
|
|
59
|
+
C=C,
|
|
60
|
+
kernel=kernel,
|
|
61
|
+
gamma=gamma,
|
|
62
|
+
degree=degree,
|
|
63
|
+
probability=True
|
|
64
|
+
)
|
|
65
|
+
model.fit(X_train, y_train)
|
|
66
|
+
y_pred = model.predict(X_test)
|
|
67
|
+
|
|
68
|
+
acc = accuracy_score(y_test, y_pred)
|
|
69
|
+
prec, rec, f1, _ = precision_recall_fscore_support(y_test, y_pred, average="macro", zero_division=0)
|
|
70
|
+
|
|
71
|
+
accs.append(acc)
|
|
72
|
+
precs.append(prec)
|
|
73
|
+
recs.append(rec)
|
|
74
|
+
f1s.append(f1)
|
|
75
|
+
|
|
76
|
+
print(f"Fold {fold+1}: acc={acc:.4f}, prec={prec:.4f}, rec={rec:.4f}, f1={f1:.4f}")
|
|
77
|
+
|
|
78
|
+
del model
|
|
79
|
+
if CUML_AVAILABLE:
|
|
80
|
+
cp.get_default_memory_pool().free_all_blocks()
|
|
81
|
+
gc.collect()
|
|
82
|
+
|
|
83
|
+
return (np.mean(accs), np.mean(precs), np.mean(recs), np.mean(f1s))
|
|
84
|
+
|
|
85
|
+
def Hyperparameter(data, label):
|
|
86
|
+
set_seed(42)
|
|
87
|
+
|
|
88
|
+
def objective(trial):
|
|
89
|
+
C = trial.suggest_loguniform("C", 1e-3, 1)
|
|
90
|
+
kernel = trial.suggest_categorical("kernel", ["rbf", "poly"])
|
|
91
|
+
gamma = trial.suggest_categorical("gamma", ["scale", "auto"])
|
|
92
|
+
degree = trial.suggest_int("degree", 1, 5)
|
|
93
|
+
|
|
94
|
+
acc, prec, rec, f1 = run_cv_eval(data=data, label=label, C=C,
|
|
95
|
+
kernel=kernel, gamma=gamma, degree=degree)
|
|
96
|
+
return f1
|
|
97
|
+
|
|
98
|
+
study = optuna.create_study(direction="maximize")
|
|
99
|
+
study.optimize(objective, n_trials=20)
|
|
100
|
+
|
|
101
|
+
print("\n===== Best Parameters =====")
|
|
102
|
+
print(study.best_params)
|
|
103
|
+
print("Best macro-F1:", study.best_value)
|
|
104
|
+
print("Successfully finished Optuna search")
|
|
105
|
+
|
|
106
|
+
return study.best_params
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from torch import nn
|
|
3
|
+
from torch.nn import Module
|
|
4
|
+
import numpy as np
|
|
5
|
+
class CA_Block(nn.Module):
|
|
6
|
+
def __init__(self, channel, h, w, reduction=16):
|
|
7
|
+
super(CA_Block, self).__init__()
|
|
8
|
+
|
|
9
|
+
self.h = h
|
|
10
|
+
self.w = w
|
|
11
|
+
|
|
12
|
+
self.avg_pool_x = nn.AdaptiveAvgPool2d((h, 1))
|
|
13
|
+
self.avg_pool_y = nn.AdaptiveAvgPool2d((1, w))
|
|
14
|
+
|
|
15
|
+
self.conv_1x1 = nn.Conv2d(in_channels=channel, out_channels=channel//reduction, kernel_size=1, stride=1, bias=False)
|
|
16
|
+
|
|
17
|
+
self.relu = nn.ReLU()
|
|
18
|
+
self.bn = nn.BatchNorm2d(channel//reduction)
|
|
19
|
+
|
|
20
|
+
self.F_h = nn.Conv2d(in_channels=channel//reduction, out_channels=channel, kernel_size=1, stride=1, bias=False)
|
|
21
|
+
self.F_w = nn.Conv2d(in_channels=channel//reduction, out_channels=channel, kernel_size=1, stride=1, bias=False)
|
|
22
|
+
|
|
23
|
+
self.sigmoid_h = nn.Sigmoid()
|
|
24
|
+
self.sigmoid_w = nn.Sigmoid()
|
|
25
|
+
|
|
26
|
+
def forward(self, x):
|
|
27
|
+
|
|
28
|
+
x_h = self.avg_pool_x(x).permute(0, 1, 3, 2)
|
|
29
|
+
x_w = self.avg_pool_y(x)
|
|
30
|
+
|
|
31
|
+
x_cat_conv_relu = self.relu(self.conv_1x1(torch.cat((x_h, x_w), 3)))
|
|
32
|
+
|
|
33
|
+
x_cat_conv_split_h, x_cat_conv_split_w = x_cat_conv_relu.split([self.h, self.w], 3)
|
|
34
|
+
|
|
35
|
+
s_h = self.sigmoid_h(self.F_h(x_cat_conv_split_h.permute(0, 1, 3, 2)))
|
|
36
|
+
s_w = self.sigmoid_w(self.F_w(x_cat_conv_split_w))
|
|
37
|
+
|
|
38
|
+
out = x * s_h.expand_as(x) * s_w.expand_as(x)
|
|
39
|
+
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
class AlexNet(nn.Module):
|
|
43
|
+
def __init__(self, num_classes):
|
|
44
|
+
super().__init__()
|
|
45
|
+
self.num_classes = num_classes
|
|
46
|
+
self.net = nn.Sequential(
|
|
47
|
+
|
|
48
|
+
nn.Conv2d(3,32,kernel_size=3,padding=1,padding_mode='reflect',stride=1,bias=False),
|
|
49
|
+
nn.BatchNorm2d(32),
|
|
50
|
+
nn.Dropout(0.3),
|
|
51
|
+
nn.ReLU(),
|
|
52
|
+
|
|
53
|
+
CA_Block(32,206,206,reduction=16),
|
|
54
|
+
|
|
55
|
+
nn.Conv2d(32,64,kernel_size=4,padding=1,padding_mode='reflect',stride=2,bias=False),
|
|
56
|
+
nn.BatchNorm2d(64),
|
|
57
|
+
nn.Dropout(0.3),
|
|
58
|
+
nn.ReLU(),
|
|
59
|
+
|
|
60
|
+
nn.Conv2d(64,64,kernel_size=3,padding=1,padding_mode='reflect',stride=2,bias=False),
|
|
61
|
+
nn.BatchNorm2d(64),
|
|
62
|
+
nn.Dropout(0.3),
|
|
63
|
+
nn.ReLU(),
|
|
64
|
+
|
|
65
|
+
nn.Conv2d(64,64,kernel_size=3,padding=1,padding_mode='reflect',stride=1,bias=False),
|
|
66
|
+
nn.BatchNorm2d(64),
|
|
67
|
+
nn.Dropout(0.3),
|
|
68
|
+
nn.ReLU(),
|
|
69
|
+
|
|
70
|
+
nn.Conv2d(64,128,kernel_size=3,padding=1,padding_mode='reflect',stride=1,bias=False),
|
|
71
|
+
nn.BatchNorm2d(128),
|
|
72
|
+
nn.Dropout(0.3),
|
|
73
|
+
nn.ReLU(),
|
|
74
|
+
|
|
75
|
+
nn.Conv2d(128,128,kernel_size=3,padding=1,padding_mode='reflect',stride=1,bias=False),
|
|
76
|
+
nn.BatchNorm2d(128),
|
|
77
|
+
nn.Dropout(0.3),
|
|
78
|
+
nn.ReLU(),
|
|
79
|
+
|
|
80
|
+
nn.Conv2d(128,256,kernel_size=2,stride=2,bias=False),
|
|
81
|
+
nn.BatchNorm2d(256),
|
|
82
|
+
nn.Dropout(0.3),
|
|
83
|
+
nn.ReLU(),
|
|
84
|
+
|
|
85
|
+
nn.Conv2d(256,256,kernel_size=3,padding=1,padding_mode='reflect',stride=1,bias=False),
|
|
86
|
+
nn.BatchNorm2d(256),
|
|
87
|
+
nn.Dropout(0.3),
|
|
88
|
+
nn.ReLU(),
|
|
89
|
+
|
|
90
|
+
nn.Conv2d(256,512,kernel_size=2,stride=2,bias=False),
|
|
91
|
+
nn.BatchNorm2d(512),
|
|
92
|
+
nn.Dropout(0.3),
|
|
93
|
+
nn.ReLU(),
|
|
94
|
+
|
|
95
|
+
nn.Conv2d(512,512,kernel_size=3,padding=1,padding_mode='reflect',stride=1,bias=False),
|
|
96
|
+
nn.BatchNorm2d(512),
|
|
97
|
+
nn.Dropout(0.3),
|
|
98
|
+
nn.ReLU(),
|
|
99
|
+
|
|
100
|
+
nn.Conv2d(512,1024,kernel_size=3,padding=1,padding_mode='reflect',stride=2,bias=False),
|
|
101
|
+
nn.BatchNorm2d(1024),
|
|
102
|
+
nn.Dropout(0.3),
|
|
103
|
+
nn.ReLU(),
|
|
104
|
+
|
|
105
|
+
nn.Conv2d(1024,1024,kernel_size=3,padding=1,padding_mode='reflect',stride=1,bias=False),
|
|
106
|
+
nn.BatchNorm2d(1024),
|
|
107
|
+
nn.Dropout(0.3),
|
|
108
|
+
nn.ReLU(),
|
|
109
|
+
|
|
110
|
+
CA_Block(1024,7,7,reduction=16),
|
|
111
|
+
|
|
112
|
+
nn.Flatten(),
|
|
113
|
+
nn.Dropout(0.3),
|
|
114
|
+
nn.ReLU(),
|
|
115
|
+
|
|
116
|
+
nn.Linear(50176, num_classes),
|
|
117
|
+
)
|
|
118
|
+
def forward(self, x):
|
|
119
|
+
x = x.permute(0, 3, 1, 2)
|
|
120
|
+
return self.net(x)
|
|
121
|
+
|
|
122
|
+
def train_model(self, train_loader, valid_loader, num_epochs, learning_rate, patience, device):
|
|
123
|
+
optimizer = torch.optim.Adam(self.parameters(), lr=learning_rate, weight_decay=1e-5)
|
|
124
|
+
criterion = nn.CrossEntropyLoss()
|
|
125
|
+
self.to(device)
|
|
126
|
+
|
|
127
|
+
best_loss = float('inf')
|
|
128
|
+
best_state = None
|
|
129
|
+
trigger_times = 0
|
|
130
|
+
|
|
131
|
+
for epoch in range(num_epochs):
|
|
132
|
+
self.train()
|
|
133
|
+
train_loss = 0.0
|
|
134
|
+
for inputs, labels in train_loader:
|
|
135
|
+
inputs, labels = inputs.to(device), labels.to(device).long() # long() for classification
|
|
136
|
+
optimizer.zero_grad()
|
|
137
|
+
outputs = self(inputs) # (B, num_classes)
|
|
138
|
+
loss = criterion(outputs, labels)
|
|
139
|
+
loss.backward()
|
|
140
|
+
optimizer.step()
|
|
141
|
+
train_loss += loss.item() * inputs.size(0)
|
|
142
|
+
|
|
143
|
+
self.eval()
|
|
144
|
+
valid_loss = 0.0
|
|
145
|
+
with torch.no_grad():
|
|
146
|
+
for inputs, labels in valid_loader:
|
|
147
|
+
inputs, labels = inputs.to(device), labels.to(device).long()
|
|
148
|
+
outputs = self(inputs)
|
|
149
|
+
loss = criterion(outputs, labels)
|
|
150
|
+
valid_loss += loss.item() * inputs.size(0)
|
|
151
|
+
|
|
152
|
+
train_loss /= len(train_loader.dataset)
|
|
153
|
+
valid_loss /= len(valid_loader.dataset)
|
|
154
|
+
|
|
155
|
+
# ---------- Early stopping ----------
|
|
156
|
+
if valid_loss < best_loss:
|
|
157
|
+
best_loss = valid_loss
|
|
158
|
+
best_state = self.state_dict()
|
|
159
|
+
trigger_times = 0
|
|
160
|
+
else:
|
|
161
|
+
trigger_times += 1
|
|
162
|
+
if trigger_times >= patience:
|
|
163
|
+
print(f"Early stopping at epoch {epoch+1}")
|
|
164
|
+
break
|
|
165
|
+
|
|
166
|
+
if best_state is not None:
|
|
167
|
+
self.load_state_dict(best_state)
|
|
168
|
+
return best_loss
|
|
169
|
+
|
|
170
|
+
def predict(self, test_loader):
|
|
171
|
+
self.eval()
|
|
172
|
+
y_pred = []
|
|
173
|
+
with torch.no_grad():
|
|
174
|
+
for inputs, _ in test_loader:
|
|
175
|
+
outputs = self(inputs) # (B, num_classes)
|
|
176
|
+
preds = torch.argmax(outputs, dim=1) # (B,)
|
|
177
|
+
y_pred.append(preds.cpu().numpy())
|
|
178
|
+
y_pred = np.concatenate(y_pred, axis=0)
|
|
179
|
+
return y_pred
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import time
|
|
3
|
+
import psutil
|
|
4
|
+
import swanlab
|
|
5
|
+
import argparse
|
|
6
|
+
import random
|
|
7
|
+
import torch
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
from sklearn.model_selection import StratifiedKFold, train_test_split
|
|
11
|
+
from sklearn.preprocessing import LabelEncoder
|
|
12
|
+
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
|
|
13
|
+
from .AlexNet_206_class import AlexNet
|
|
14
|
+
from torch.utils.data import DataLoader, TensorDataset
|
|
15
|
+
from . import SoyDNGP_he_class
|
|
16
|
+
import pynvml
|
|
17
|
+
|
|
18
|
+
def parse_args():
|
|
19
|
+
parser = argparse.ArgumentParser(description="Argument parser")
|
|
20
|
+
parser.add_argument('--methods', type=str, default='SoyDNGP/', help='Random seed')
|
|
21
|
+
parser.add_argument('--species', type=str, default='Chicken/', help='Species name')
|
|
22
|
+
parser.add_argument('--phe', type=str, default='', help='Dataset name')
|
|
23
|
+
parser.add_argument('--data_dir', type=str, default='../../data/')
|
|
24
|
+
parser.add_argument('--result_dir', type=str, default='result/')
|
|
25
|
+
|
|
26
|
+
parser.add_argument('--epochs', type=int, default=1000, help='Number of training rounds')
|
|
27
|
+
parser.add_argument('--batch_size', type=int, default=32, help='Batch size')
|
|
28
|
+
parser.add_argument('--learning_rate', type=float, default=0.01, help='Learning rate')
|
|
29
|
+
parser.add_argument('--patience', type=int, default=10, help='Patience for early stopping')
|
|
30
|
+
args = parser.parse_args()
|
|
31
|
+
return args
|
|
32
|
+
|
|
33
|
+
def get_data(dataframe):
|
|
34
|
+
data_matrix = np.array(dataframe)
|
|
35
|
+
total_sample, total_snp = data_matrix.shape
|
|
36
|
+
|
|
37
|
+
one_hot = np.zeros((total_sample, total_snp, 3), dtype=np.float32)
|
|
38
|
+
one_hot[data_matrix == 2] = [1, 1, 0]
|
|
39
|
+
one_hot[data_matrix == 1] = [1, 0, 1]
|
|
40
|
+
one_hot[data_matrix == 0] = [0, 1, 1]
|
|
41
|
+
|
|
42
|
+
target_snp = 206 * 206
|
|
43
|
+
if total_snp != target_snp:
|
|
44
|
+
print(f"⚠ SNP Number {total_snp} != {target_snp}")
|
|
45
|
+
new_one_hot = np.zeros((total_sample, target_snp, 3), dtype=np.float32)
|
|
46
|
+
copy_len = min(total_snp, target_snp)
|
|
47
|
+
new_one_hot[:, :copy_len] = one_hot[:, :copy_len]
|
|
48
|
+
one_hot = new_one_hot
|
|
49
|
+
|
|
50
|
+
one_hot = one_hot.reshape(total_sample, 206, 206, 3)
|
|
51
|
+
return one_hot
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def load_data(args):
|
|
55
|
+
xData = np.load(os.path.join(args.data_dir, args.species, 'genotype.npz'))["arr_0"]
|
|
56
|
+
yData = np.load(os.path.join(args.data_dir, args.species, 'phenotype.npz'))["arr_0"]
|
|
57
|
+
names = np.load(os.path.join(args.data_dir, args.species, 'phenotype.npz'))["arr_1"]
|
|
58
|
+
|
|
59
|
+
nsample = xData.shape[0]
|
|
60
|
+
nsnp = xData.shape[1]
|
|
61
|
+
print("Number of samples: ", nsample)
|
|
62
|
+
print("Number of SNPs: ", nsnp)
|
|
63
|
+
xData = get_data(xData)
|
|
64
|
+
return xData, yData, nsample, nsnp, names
|
|
65
|
+
|
|
66
|
+
def set_seed(seed=42):
|
|
67
|
+
random.seed(seed)
|
|
68
|
+
np.random.seed(seed)
|
|
69
|
+
torch.manual_seed(seed)
|
|
70
|
+
torch.cuda.manual_seed_all(seed)
|
|
71
|
+
torch.backends.cudnn.deterministic = True
|
|
72
|
+
torch.backends.cudnn.benchmark = False
|
|
73
|
+
|
|
74
|
+
def get_gpu_mem_by_pid(pid):
|
|
75
|
+
procs = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
|
|
76
|
+
for p in procs:
|
|
77
|
+
if p.pid == pid:
|
|
78
|
+
return p.usedGpuMemory / 1024**2
|
|
79
|
+
return 0.0
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def run_nested_cv(args, data, label, nsnp, num_classes, device):
|
|
83
|
+
result_dir = os.path.join(args.result_dir, args.methods + args.species + args.phe)
|
|
84
|
+
os.makedirs(result_dir, exist_ok=True)
|
|
85
|
+
print("Starting 10-fold cross-validation...")
|
|
86
|
+
kf = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)
|
|
87
|
+
|
|
88
|
+
all_acc, all_prec, all_rec, all_f1 = [], [], [], []
|
|
89
|
+
time_star = time.time()
|
|
90
|
+
for fold, (train_index, test_index) in enumerate(kf.split(data, label)):
|
|
91
|
+
print(f"Running fold {fold}...")
|
|
92
|
+
process = psutil.Process(os.getpid())
|
|
93
|
+
fold_start_time = time.time()
|
|
94
|
+
|
|
95
|
+
X_train, X_test = data[train_index], data[test_index]
|
|
96
|
+
y_train, y_test = label[train_index], label[test_index]
|
|
97
|
+
|
|
98
|
+
X_train_sub, X_valid, y_train_sub, y_valid = train_test_split(
|
|
99
|
+
X_train, y_train, test_size=0.1, stratify=y_train, random_state=42
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
x_train_tensor = torch.from_numpy(X_train_sub).float().to(device)
|
|
103
|
+
y_train_tensor = torch.from_numpy(y_train_sub).long().to(device)
|
|
104
|
+
x_valid_tensor = torch.from_numpy(X_valid).float().to(device)
|
|
105
|
+
y_valid_tensor = torch.from_numpy(y_valid).long().to(device)
|
|
106
|
+
x_test_tensor = torch.from_numpy(X_test).float().to(device)
|
|
107
|
+
y_test_tensor = torch.from_numpy(y_test).long().to(device)
|
|
108
|
+
|
|
109
|
+
train_data = TensorDataset(x_train_tensor, y_train_tensor)
|
|
110
|
+
valid_data = TensorDataset(x_valid_tensor, y_valid_tensor)
|
|
111
|
+
test_data = TensorDataset(x_test_tensor, y_test_tensor)
|
|
112
|
+
|
|
113
|
+
train_loader = DataLoader(train_data, args.batch_size, shuffle=True)
|
|
114
|
+
valid_loader = DataLoader(valid_data, args.batch_size, shuffle=False)
|
|
115
|
+
test_loader = DataLoader(test_data, args.batch_size, shuffle=False)
|
|
116
|
+
|
|
117
|
+
model = AlexNet(num_classes=num_classes)
|
|
118
|
+
model.train_model(train_loader, valid_loader, args.epochs, args.learning_rate, args.patience, device)
|
|
119
|
+
y_pred = model.predict(test_loader)
|
|
120
|
+
|
|
121
|
+
acc = accuracy_score(y_test, y_pred)
|
|
122
|
+
prec, rec, f1, _ = precision_recall_fscore_support(
|
|
123
|
+
y_test, y_pred, average="macro", zero_division=0
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
all_acc.append(acc)
|
|
127
|
+
all_prec.append(prec)
|
|
128
|
+
all_rec.append(rec)
|
|
129
|
+
all_f1.append(f1)
|
|
130
|
+
|
|
131
|
+
fold_time = time.time() - fold_start_time
|
|
132
|
+
fold_gpu_mem = get_gpu_mem_by_pid(os.getpid())
|
|
133
|
+
fold_cpu_mem = process.memory_info().rss / 1024**2
|
|
134
|
+
print(f'Fold {fold}: ACC={acc:.4f}, PREC={prec:.4f}, REC={rec:.4f}, F1={f1:.4f}, '
|
|
135
|
+
f'Time={fold_time:.2f}s, GPU={fold_gpu_mem:.2f}MB, CPU={fold_cpu_mem:.2f}MB')
|
|
136
|
+
|
|
137
|
+
if torch.cuda.is_available():
|
|
138
|
+
torch.cuda.empty_cache()
|
|
139
|
+
torch.cuda.reset_peak_memory_stats()
|
|
140
|
+
results_df = pd.DataFrame({'Y_test': y_test, 'Y_pred': y_pred})
|
|
141
|
+
results_df.to_csv(os.path.join(result_dir, f"fold{fold}.csv"), index=False)
|
|
142
|
+
|
|
143
|
+
print("\n===== Cross-validation summary =====")
|
|
144
|
+
print(f"Average ACC: {np.mean(all_acc):.4f} ± {np.std(all_acc):.4f}")
|
|
145
|
+
print(f"Average PREC: {np.mean(all_prec):.4f} ± {np.std(all_prec):.4f}")
|
|
146
|
+
print(f"Average REC: {np.mean(all_rec):.4f} ± {np.std(all_rec):.4f}")
|
|
147
|
+
print(f"Average F1 : {np.mean(all_f1):.4f} ± {np.std(all_f1):.4f}")
|
|
148
|
+
print(f"Time: {time.time() - time_star:.2f}s")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def SoyDNGP_class():
|
|
152
|
+
set_seed(42)
|
|
153
|
+
torch.cuda.empty_cache()
|
|
154
|
+
pynvml.nvmlInit()
|
|
155
|
+
handle = pynvml.nvmlDeviceGetHandleByIndex(0)
|
|
156
|
+
|
|
157
|
+
args = parse_args()
|
|
158
|
+
all_species = ["Human/Sim/"]
|
|
159
|
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
|
160
|
+
args.device = device
|
|
161
|
+
for i in range(len(all_species)):
|
|
162
|
+
args.species = all_species[i]
|
|
163
|
+
X, Y, nsamples, nsnp, names = load_data(args)
|
|
164
|
+
print("Starting:", args.methods + args.species)
|
|
165
|
+
|
|
166
|
+
label_raw = np.nan_to_num(Y[:, 0])
|
|
167
|
+
le = LabelEncoder()
|
|
168
|
+
label = le.fit_transform(label_raw)
|
|
169
|
+
num_classes = len(le.classes_)
|
|
170
|
+
|
|
171
|
+
best_params = SoyDNGP_he_class.Hyperparameter(X, label, nsnp, num_classes)
|
|
172
|
+
args.learning_rate = best_params['learning_rate']
|
|
173
|
+
args.batch_size = best_params['batch_size']
|
|
174
|
+
args.patience = best_params['patience']
|
|
175
|
+
|
|
176
|
+
start_time = time.time()
|
|
177
|
+
if torch.cuda.is_available():
|
|
178
|
+
torch.cuda.reset_peak_memory_stats()
|
|
179
|
+
process = psutil.Process(os.getpid())
|
|
180
|
+
|
|
181
|
+
run_nested_cv(args, data=X, label=label, nsnp=nsnp, num_classes=num_classes, device=device)
|
|
182
|
+
|
|
183
|
+
elapsed_time = time.time() - start_time
|
|
184
|
+
print(f"Running time: {elapsed_time:.2f}s")
|
|
185
|
+
print("successfully")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
if __name__ == "__main__":
|
|
189
|
+
SoyDNGP_class()
|