1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
| import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Ridge from sklearn.model_selection import cross_val_score, learning_curve from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error, r2_score import seaborn as sns from scipy import stats
np.random.seed(42)
def generate_gene_expression_data(n_samples=200, n_genes=15, noise_level=0.3): """ Generate synthetic gene expression data with realistic characteristics. Parameters: ----------- n_samples : int Number of samples (e.g., different conditions or time points) n_genes : int Number of regulator genes noise_level : float Standard deviation of Gaussian noise added to measurements Returns: -------- X : ndarray, shape (n_samples, n_genes) Gene expression levels for regulator genes y : ndarray, shape (n_samples,) Target gene expression levels true_coefficients : ndarray True coefficients used to generate the target """ mean = np.zeros(n_genes) correlation = 0.3 cov = np.eye(n_genes) * (1 - correlation) + np.ones((n_genes, n_genes)) * correlation X = np.random.multivariate_normal(mean, cov, n_samples) true_coefficients = np.zeros(n_genes) true_coefficients[0:5] = [2.5, -1.8, 3.2, -2.1, 1.5] true_coefficients[5:8] = [0.8, -0.6, 0.9] y_true = X @ true_coefficients noise = np.random.normal(0, noise_level, n_samples) y = y_true + noise return X, y, true_coefficients
X, y, true_coefs = generate_gene_expression_data(n_samples=200, n_genes=15, noise_level=0.5)
split_idx = 150 X_train, X_test = X[:split_idx], X[split_idx:] y_train, y_test = y[:split_idx], y[split_idx:]
scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test)
print("Dataset Information:") print(f"Training samples: {X_train.shape[0]}") print(f"Test samples: {X_test.shape[0]}") print(f"Number of genes: {X_train.shape[1]}") print(f"Target expression range: [{y.min():.2f}, {y.max():.2f}]") print("\n" + "="*70 + "\n")
alphas = np.logspace(-3, 3, 50)
cv_scores_mean = [] cv_scores_std = []
print("Performing hyperparameter optimization...") print("Testing {} alpha values from {:.4f} to {:.2f}".format(len(alphas), alphas[0], alphas[-1]))
for alpha in alphas: model = Ridge(alpha=alpha) scores = cross_val_score(model, X_train_scaled, y_train, cv=5, scoring='neg_mean_squared_error') rmse_scores = np.sqrt(-scores) cv_scores_mean.append(rmse_scores.mean()) cv_scores_std.append(rmse_scores.std())
cv_scores_mean = np.array(cv_scores_mean) cv_scores_std = np.array(cv_scores_std)
optimal_idx = np.argmin(cv_scores_mean) optimal_alpha = alphas[optimal_idx] optimal_cv_score = cv_scores_mean[optimal_idx]
print(f"\nOptimal alpha: {optimal_alpha:.4f}") print(f"CV RMSE at optimal alpha: {optimal_cv_score:.4f}") print("\n" + "="*70 + "\n")
alpha_underreg = alphas[max(0, optimal_idx - 15)] alpha_optimal = optimal_alpha alpha_overreg = alphas[min(len(alphas)-1, optimal_idx + 15)]
models = { 'Under-regularized': Ridge(alpha=alpha_underreg), 'Optimal': Ridge(alpha=alpha_optimal), 'Over-regularized': Ridge(alpha=alpha_overreg) }
results = {} for name, model in models.items(): model.fit(X_train_scaled, y_train) y_train_pred = model.predict(X_train_scaled) y_test_pred = model.predict(X_test_scaled) train_rmse = np.sqrt(mean_squared_error(y_train, y_train_pred)) test_rmse = np.sqrt(mean_squared_error(y_test, y_test_pred)) train_r2 = r2_score(y_train, y_train_pred) test_r2 = r2_score(y_test, y_test_pred) results[name] = { 'model': model, 'alpha': model.alpha, 'train_rmse': train_rmse, 'test_rmse': test_rmse, 'train_r2': train_r2, 'test_r2': test_r2, 'coefficients': model.coef_, 'y_test_pred': y_test_pred } print(f"{name} (alpha={model.alpha:.4f}):") print(f" Training RMSE: {train_rmse:.4f}") print(f" Test RMSE: {test_rmse:.4f}") print(f" Training R²: {train_r2:.4f}") print(f" Test R²: {test_r2:.4f}") print(f" Overfitting gap: {abs(train_rmse - test_rmse):.4f}") print()
fig = plt.figure(figsize=(18, 12)) gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3)
ax1 = fig.add_subplot(gs[0, :]) ax1.semilogx(alphas, cv_scores_mean, 'b-', linewidth=2, label='Mean CV RMSE') ax1.fill_between(alphas, cv_scores_mean - cv_scores_std, cv_scores_mean + cv_scores_std, alpha=0.2, color='b', label='±1 std dev') ax1.axvline(optimal_alpha, color='r', linestyle='--', linewidth=2, label=f'Optimal α = {optimal_alpha:.4f}') ax1.axvline(alpha_underreg, color='orange', linestyle=':', linewidth=1.5, alpha=0.7) ax1.axvline(alpha_overreg, color='purple', linestyle=':', linewidth=1.5, alpha=0.7) ax1.set_xlabel('Regularization Parameter (α)', fontsize=12, fontweight='bold') ax1.set_ylabel('Cross-Validation RMSE', fontsize=12, fontweight='bold') ax1.set_title('Hyperparameter Optimization: Cross-Validation Curve', fontsize=14, fontweight='bold') ax1.legend(fontsize=10) ax1.grid(True, alpha=0.3)
ax2 = fig.add_subplot(gs[1, 0]) model_names = list(results.keys()) train_rmses = [results[name]['train_rmse'] for name in model_names] test_rmses = [results[name]['test_rmse'] for name in model_names]
x_pos = np.arange(len(model_names)) width = 0.35
bars1 = ax2.bar(x_pos - width/2, train_rmses, width, label='Training', color='steelblue', alpha=0.8) bars2 = ax2.bar(x_pos + width/2, test_rmses, width, label='Test', color='coral', alpha=0.8)
ax2.set_xlabel('Model Configuration', fontsize=11, fontweight='bold') ax2.set_ylabel('RMSE', fontsize=11, fontweight='bold') ax2.set_title('Training vs Test Error', fontsize=12, fontweight='bold') ax2.set_xticks(x_pos) ax2.set_xticklabels(model_names, rotation=15, ha='right') ax2.legend(fontsize=9) ax2.grid(True, alpha=0.3, axis='y')
for bars in [bars1, bars2]: for bar in bars: height = bar.get_height() ax2.text(bar.get_x() + bar.get_width()/2., height, f'{height:.3f}', ha='center', va='bottom', fontsize=8)
ax3 = fig.add_subplot(gs[1, 1]) train_r2s = [results[name]['train_r2'] for name in model_names] test_r2s = [results[name]['test_r2'] for name in model_names]
bars1 = ax3.bar(x_pos - width/2, train_r2s, width, label='Training', color='green', alpha=0.7) bars2 = ax3.bar(x_pos + width/2, test_r2s, width, label='Test', color='red', alpha=0.7)
ax3.set_xlabel('Model Configuration', fontsize=11, fontweight='bold') ax3.set_ylabel('R² Score', fontsize=11, fontweight='bold') ax3.set_title('Coefficient of Determination (R²)', fontsize=12, fontweight='bold') ax3.set_xticks(x_pos) ax3.set_xticklabels(model_names, rotation=15, ha='right') ax3.legend(fontsize=9) ax3.grid(True, alpha=0.3, axis='y') ax3.set_ylim([0, 1.0])
for bars in [bars1, bars2]: for bar in bars: height = bar.get_height() ax3.text(bar.get_x() + bar.get_width()/2., height, f'{height:.3f}', ha='center', va='bottom', fontsize=8)
ax4 = fig.add_subplot(gs[1, 2]) overfitting_gaps = [abs(results[name]['train_rmse'] - results[name]['test_rmse']) for name in model_names] colors = ['orange', 'green', 'purple'] bars = ax4.bar(model_names, overfitting_gaps, color=colors, alpha=0.7)
ax4.set_xlabel('Model Configuration', fontsize=11, fontweight='bold') ax4.set_ylabel('|Train RMSE - Test RMSE|', fontsize=11, fontweight='bold') ax4.set_title('Overfitting Gap Analysis', fontsize=12, fontweight='bold') ax4.set_xticklabels(model_names, rotation=15, ha='right') ax4.grid(True, alpha=0.3, axis='y')
for bar in bars: height = bar.get_height() ax4.text(bar.get_x() + bar.get_width()/2., height, f'{height:.3f}', ha='center', va='bottom', fontsize=9)
ax5 = fig.add_subplot(gs[2, :]) gene_indices = np.arange(len(true_coefs)) width = 0.2
bars1 = ax5.bar(gene_indices - width*1.5, true_coefs, width, label='True Coefficients', color='black', alpha=0.8) bars2 = ax5.bar(gene_indices - width*0.5, results['Under-regularized']['coefficients'], width, label='Under-regularized', color='orange', alpha=0.7) bars3 = ax5.bar(gene_indices + width*0.5, results['Optimal']['coefficients'], width, label='Optimal', color='green', alpha=0.7) bars4 = ax5.bar(gene_indices + width*1.5, results['Over-regularized']['coefficients'], width, label='Over-regularized', color='purple', alpha=0.7)
ax5.set_xlabel('Gene Index', fontsize=11, fontweight='bold') ax5.set_ylabel('Coefficient Value', fontsize=11, fontweight='bold') ax5.set_title('Learned Coefficients vs True Coefficients', fontsize=12, fontweight='bold') ax5.set_xticks(gene_indices) ax5.legend(fontsize=9, loc='upper right') ax5.grid(True, alpha=0.3, axis='y') ax5.axhline(y=0, color='k', linestyle='-', linewidth=0.5)
plt.suptitle('Gene Expression Model: Hyperparameter Optimization Analysis', fontsize=16, fontweight='bold', y=0.995)
plt.tight_layout() plt.show()
fig2, axes = plt.subplots(1, 3, figsize=(18, 5))
for idx, (name, result) in enumerate(results.items()): ax = axes[idx] ax.scatter(y_test, result['y_test_pred'], alpha=0.6, s=80, color=colors[idx], edgecolors='black', linewidth=0.5) min_val = min(y_test.min(), result['y_test_pred'].min()) max_val = max(y_test.max(), result['y_test_pred'].max()) ax.plot([min_val, max_val], [min_val, max_val], 'r--', linewidth=2, label='Perfect Prediction') slope, intercept, r_value, p_value, std_err = stats.linregress(y_test, result['y_test_pred']) line_x = np.array([min_val, max_val]) line_y = slope * line_x + intercept ax.plot(line_x, line_y, 'b-', linewidth=2, alpha=0.7, label='Fitted Line') ax.set_xlabel('Actual Expression', fontsize=11, fontweight='bold') ax.set_ylabel('Predicted Expression', fontsize=11, fontweight='bold') ax.set_title(f'{name}\nR² = {result["test_r2"]:.3f}, RMSE = {result["test_rmse"]:.3f}', fontsize=12, fontweight='bold') ax.legend(fontsize=9) ax.grid(True, alpha=0.3) ax.set_aspect('equal', adjustable='box')
plt.suptitle('Prediction Quality: Actual vs Predicted Gene Expression', fontsize=14, fontweight='bold') plt.tight_layout() plt.show()
fig3, axes = plt.subplots(1, 3, figsize=(18, 5))
for idx, (name, result) in enumerate(results.items()): ax = axes[idx] train_sizes, train_scores, val_scores = learning_curve( Ridge(alpha=result['alpha']), X_train_scaled, y_train, cv=5, scoring='neg_mean_squared_error', train_sizes=np.linspace(0.1, 1.0, 10), n_jobs=-1 ) train_rmse_mean = np.sqrt(-train_scores.mean(axis=1)) train_rmse_std = np.sqrt(-train_scores).std(axis=1) val_rmse_mean = np.sqrt(-val_scores.mean(axis=1)) val_rmse_std = np.sqrt(-val_scores).std(axis=1) ax.plot(train_sizes, train_rmse_mean, 'o-', color='blue', linewidth=2, markersize=8, label='Training RMSE') ax.fill_between(train_sizes, train_rmse_mean - train_rmse_std, train_rmse_mean + train_rmse_std, alpha=0.2, color='blue') ax.plot(train_sizes, val_rmse_mean, 'o-', color='red', linewidth=2, markersize=8, label='Validation RMSE') ax.fill_between(train_sizes, val_rmse_mean - val_rmse_std, val_rmse_mean + val_rmse_std, alpha=0.2, color='red') ax.set_xlabel('Training Set Size', fontsize=11, fontweight='bold') ax.set_ylabel('RMSE', fontsize=11, fontweight='bold') ax.set_title(f'{name} (α = {result["alpha"]:.4f})', fontsize=12, fontweight='bold') ax.legend(fontsize=9, loc='best') ax.grid(True, alpha=0.3)
plt.suptitle('Learning Curves: Model Performance vs Training Set Size', fontsize=14, fontweight='bold') plt.tight_layout() plt.show()
print("="*70) print("Analysis Complete!") print("="*70)
|