{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# %pip install matplotlib seaborn networkx" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# !conda install -c conda-forge pygraphviz -y" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "metadata": {} }, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "import seaborn as sns\n", "import networkx as nx\n", "import matplotlib.pyplot as plt\n", "\n", "from math import pi\n", "from scipy.interpolate import make_interp_spline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## AMVL WorkFlow" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# Create a directed graph\n", "G = nx.DiGraph()\n", "\n", "# Define nodes\n", "nodes = {\n", " \"Input\": \"Input Matrices and Parameters\",\n", " \"Step1_Start\": \"Step 1: Bounded Matrix Completion (BMC)\",\n", " \"BMC\": \"Perform BMC to obtain T_mc\",\n", " \"GIP\": \"Compute GIP Similarities (Grr, Gdd)\",\n", " \"Step2_Start\": \"Step 2: Matrix Factorization with Similarity Regularization\",\n", " \"Combine_Similarity\": \"Combine GIP and Input Similarities\",\n", " \"Remove_Diagonal\": \"Remove Diagonal Elements (Wrr_ML, Wdd_ML)\",\n", " \"MSBMF\": \"Perform MSBMF (Matrix Factorization)\",\n", " \"Step3_Start\": \"Step 3: Multi-View Learning (MVL)\",\n", " \"Update_Similarity\": \"Update Similarity Matrices (SR, SD)\",\n", " \"Predict_MVL\": \"Generate Multi-View Prediction (F_mv)\",\n", " \"Step4_Start\": \"Step 4: Final Combination\",\n", " \"Combine_Results\": \"Combine Thresholded Results and F_mv\",\n", " \"Clip_Values\": \"Ensure Values in Range [0, 1]\",\n", " \"Output\": \"Output Final Prediction Matrix (F_final)\"\n", "}\n", "\n", "# Add edges\n", "edges = [\n", " (\"Input\", \"Step1_Start\"),\n", " (\"Step1_Start\", \"BMC\"),\n", " (\"BMC\", \"GIP\"),\n", " (\"GIP\", \"Step2_Start\"),\n", " (\"Step2_Start\", \"Combine_Similarity\"),\n", " (\"Combine_Similarity\", \"Remove_Diagonal\"),\n", " (\"Remove_Diagonal\", \"MSBMF\"),\n", " (\"MSBMF\", \"Step3_Start\"),\n", " (\"Step3_Start\", \"Update_Similarity\"),\n", " (\"Update_Similarity\", \"Predict_MVL\"),\n", " (\"Predict_MVL\", \"Step4_Start\"),\n", " (\"Step4_Start\", \"Combine_Results\"),\n", " (\"Combine_Results\", \"Clip_Values\"),\n", " (\"Clip_Values\", \"Output\")\n", "]\n", "\n", "# Add nodes and edges to the graph\n", "for node, label in nodes.items():\n", " G.add_node(node, label=label)\n", "G.add_edges_from(edges)\n", "\n", "# Define positions using graphviz layout\n", "pos = nx.nx_agraph.graphviz_layout(G, prog=\"dot\")\n", "\n", "# Draw the graph\n", "plt.figure(figsize=(12, 8))\n", "nx.draw(G, pos, with_labels=True, labels=nx.get_node_attributes(G, 'label'),\n", " node_size=5000, node_color=\"lightblue\", font_size=9, font_weight=\"bold\", arrows=True)\n", "plt.title(\"AdaMVL Workflow\", fontsize=14)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Benchmark 5+2" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Models and metrics\n", "models = ['AMVL', 'MLMC', 'MSBMF', 'HGIMC', 'ITRPCA', 'DRPADC', 'VDA-GKSBMF']\n", "# metrics = ['AUC', 'AUPR', 'F1']\n", "# Updated metrics list to include virtual metrics between each original metric\n", "metrics = ['AUC', 'Virtual1', 'AUPR', 'Virtual2', 'F1', 'Virtual3']" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Original data for each model across different datasets\n", "data = {\n", " 'Fdataset': {\n", " 'AMVL': [0.9587, 0.9656, 0.7131],\n", " 'MLMC': [0.9573, 0.9644, 0.6909],\n", " 'MSBMF': [0.9462, 0.9583, 0.6862],\n", " 'HGIMC': [0.9260, 0.9432, 0.6769],\n", " 'ITRPCA': [0.9333, 0.9399, 0.6323],\n", " 'DRPADC': [0.9112, 0.9350, 0.6704],\n", " 'VDA-GKSBMF': [0.9379, 0.9508, 0.6821],\n", " },\n", " 'Cdataset': {\n", " 'AMVL': [0.9702, 0.9753, 0.7213],\n", " 'MLMC': [0.9689, 0.9742, 0.6967],\n", " 'MSBMF': [0.9634, 0.9722, 0.6946],\n", " 'HGIMC': [0.9448, 0.9592, 0.6862],\n", " 'ITRPCA': [0.9500, 0.9553, 0.6408],\n", " 'DRPADC': [0.9269, 0.9460, 0.6778],\n", " 'VDA-GKSBMF': [0.9555, 0.9640, 0.6905],\n", " },\n", " 'Ydataset': {\n", " 'AMVL': [0.9709, 0.9749, 0.7222],\n", " 'MLMC': [0.9526, 0.9624, 0.6902],\n", " 'MSBMF': [0.9647, 0.9725, 0.6956],\n", " 'HGIMC': [0.9565, 0.9658, 0.6917],\n", " 'ITRPCA': [0.9473, 0.9512, 0.6371],\n", " 'DRPADC': [0.9555, 0.9648, 0.6911],\n", " 'VDA-GKSBMF': [0.9588, 0.9605, 0.6917],\n", " }\n", "}" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Rescaling F1 to the range of AUC and AUPR min and max for each dataset\n", "def rescale_f1_to_auc_aupr_range(data):\n", " scaled_data = {}\n", "\n", " for dataset, model_data in data.items():\n", " # Find the min and max across AUC and AUPR values for each dataset\n", " auc_aupr_values = [values[0:2] for values in model_data.values()]\n", " auc_aupr_min = min([min(values) for values in auc_aupr_values])\n", " auc_aupr_max = max([max(values) for values in auc_aupr_values])\n", " \n", " # Rescale F1 values within the range [auc_aupr_min, auc_aupr_max]\n", " f1_values = [values[2] for values in model_data.values()]\n", " min_f1_value = min(f1_values)\n", " max_f1_value = max(f1_values)\n", " \n", " # Rescale F1 values to the range of auc_aupr_min to auc_aupr_max\n", " def rescale_f1(value):\n", " return auc_aupr_min + (auc_aupr_max - auc_aupr_min) * (value - min_f1_value) / (max_f1_value - min_f1_value)\n", " \n", " # Update the dataset with rescaled F1 values\n", " scaled_data[dataset] = {}\n", " for model, values in model_data.items():\n", " scaled_f1 = rescale_f1(values[2])\n", " scaled_data[dataset][model] = [values[0], values[1], scaled_f1]\n", " \n", " return scaled_data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Apply the rescaling\n", "scaled_data_f1_to_auc_aupr_range = rescale_f1_to_auc_aupr_range(data)\n", "scaled_data_f1_to_auc_aupr_range" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Function to add virtual metrics between each original metric\n", "def add_virtual_metrics(data):\n", " extended_data = {}\n", " for dataset, model_data in data.items():\n", " extended_data[dataset] = {}\n", " for model, values in model_data.items():\n", " # Calculate virtual metrics as the average of each pair of consecutive original metrics\n", " virtual1 = (values[0] + values[1]) / 2\n", " virtual2 = (values[1] + values[2]) / 2\n", " virtual3 = (values[2] + values[0]) / 2\n", " # Extend the original values with the virtual metrics\n", " extended_values = [values[0], virtual1, values[1], virtual2, values[2], virtual3]\n", " extended_data[dataset][model] = extended_values\n", " return extended_data\n", "\n", "# Apply the function to add virtual metrics\n", "data_with_virtual_metrics = add_virtual_metrics(scaled_data_f1_to_auc_aupr_range)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# # Define Nature-style colors that are colorblind-friendly\n", "# nature_colors = [\n", "# '#E69F00', '#56B4E9', '#009E73', '#F0E442', '#0072B2', '#D55E00', '#CC79A7'\n", "# ]\n", "\n", "# def create_radar_chart(ax, dataset, data, models):\n", "# # Number of metrics\n", "# num_vars = len(metrics)\n", "# angles = [n / float(num_vars) * 2 * pi for n in range(num_vars)]\n", "# # Adding virtual points between each pair of metrics\n", "# extended_angles = []\n", "# for i in range(len(angles)):\n", "# extended_angles.append(angles[i])\n", "# if i < len(angles) - 1:\n", "# # Add a virtual point between every pair of metrics\n", "# extended_angles.append(angles[i] + (angles[(i + 1) % len(angles)] - angles[i]) * 0.5)\n", "# angles = extended_angles + extended_angles[:1] # Closing the loop for the radar chart\n", "\n", "# # Add virtual points between metrics in the data\n", "# extended_data = {}\n", "# for model in data[dataset]:\n", "# values = data[dataset][model]\n", "# extended_values = []\n", "# for i in range(len(values)):\n", "# extended_values.append(values[i])\n", "# if i < len(values) - 1:\n", "# # Add a value halfway between each metric to create the virtual points\n", "# extended_values.append((values[i] + values[(i + 1) % len(values)]) / 2)\n", "# extended_values += extended_values[:1] # Close the loop for the data\n", "# extended_data[model] = extended_values\n", "\n", "# # Draw one axe per metric + add labels\n", "# ax.set_theta_offset(pi / 2)\n", "# ax.set_theta_direction(-1)\n", "# ax.set_xticks(angles[:-1:2]) # Set ticks for original metrics only\n", "# ax.set_xticklabels(metrics)\n", "\n", "# # Customize the grid\n", "# ax.grid(color='gray', linestyle='--', linewidth=0.5)\n", "# ax.set_facecolor('#f7f7f7') # Light background color for better contrast\n", "\n", "# # Plot data for each model and save the line objects for the legend\n", "# lines = []\n", "# marker_styles = ['o', 's', 'D', '^', 'v', 'p', '*'] # Different markers for each model\n", "# line_styles = ['solid', 'dashed', 'dashdot', 'dotted'] # Different line styles\n", "\n", "# for idx, model in enumerate(models):\n", "# values = extended_data[model]\n", "# color = nature_colors[idx % len(nature_colors)] # Cycle through Nature-style colors\n", "# marker = marker_styles[idx % len(marker_styles)] # Cycle through marker styles\n", "# line_style = line_styles[idx % len(line_styles)] # Cycle through line styles\n", "# line = ax.plot(angles, values, linewidth=2 + 0.5 * (idx % 2), linestyle=line_style, label=model, color=color, marker=marker)\n", "# ax.fill(angles, values, color=color, alpha=0.15 + 0.1 * (idx % 3)) # Vary opacity for distinction\n", "# lines.append(line[0]) # Save the line for legend\n", "\n", "# # Set dynamic ylim based on the max and min of AUC, AUPR, and rescaled F1\n", "# dataset_values = [value for model_data in data[dataset].values() for value in model_data]\n", "# ax.set_ylim(min(dataset_values) - 5e-3, max(dataset_values) + 5e-5)\n", " \n", "# return lines" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Define Nature-style colors that are colorblind-friendly\n", "nature_colors = [\n", " '#E69F00', '#56B4E9', '#009E73', '#F0E442', '#0072B2', '#D55E00', '#CC79A7'\n", "]\n", "\n", "def create_radar_chart(ax, dataset, data, models):\n", " # Number of metrics\n", " num_vars = len(metrics)\n", " angles = [n / float(num_vars) * 2 * pi for n in range(num_vars)]\n", " angles += angles[:1] # Closing the loop for the radar chart\n", "\n", " # Draw one axe per metric + add labels\n", " ax.set_theta_offset(pi / 2)\n", " ax.set_theta_direction(-1)\n", " ax.set_xticks(angles[:-1])\n", " # ax.set_xticklabels(metrics)\n", " ax.set_xticklabels([metric if 'Virtual' not in metric else '' for metric in metrics])\n", "\n", " # Customize the grid\n", " ax.grid(color='gray', linestyle='--', linewidth=0.5)\n", " ax.set_facecolor('#f7f7f7') # Light background color for better contrast\n", "\n", " # Plot data for each model and save the line objects for the legend\n", " lines = []\n", " marker_styles = ['o', 's', 'D', '^', 'v', 'p', '*'] # Different markers for each model\n", " line_styles = ['solid', 'dashed', 'dashdot', 'dotted'] # Different line styles\n", "\n", " for idx, model in enumerate(models):\n", " values = data[dataset][model]\n", " values += values[:1] # Close the loop for the data\n", " color = nature_colors[idx % len(nature_colors)] # Cycle through Nature-style colors\n", " marker = marker_styles[idx % len(marker_styles)] # Cycle through marker styles\n", " line_style = line_styles[idx % len(line_styles)] # Cycle through line styles\n", " line = ax.plot(angles, values, linewidth=2 + 0.5 * (idx % 2), linestyle=line_style, label=model, color=color, marker=marker)\n", " ax.fill(angles, values, color=color, alpha=0.15 + 0.1 * (idx % 3)) # Vary opacity for distinction\n", " lines.append(line[0]) # Save the line for legend\n", "\n", " # Set dynamic ylim based on the max and min of AUC, AUPR, and rescaled F1\n", " dataset_values = [value for model_data in data[dataset].values() for value in model_data]\n", " ax.set_ylim(min(dataset_values) - 5e-3, max(dataset_values) + 5e-5)\n", " \n", " return lines" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# # Function to create radar chart with dynamic ylim and matching legend colors\n", "# def create_radar_chart(ax, dataset, data, models):\n", "# # Number of metrics\n", "# num_vars = len(metrics)\n", "# angles = [n / float(num_vars) * 2 * pi for n in range(num_vars)]\n", "# angles += angles[:1] # Closing the loop for the radar chart\n", "\n", "# # Draw one axe per metric + add labels\n", "# ax.set_theta_offset(pi / 2)\n", "# ax.set_theta_direction(-1)\n", "# ax.set_xticks(angles[:-1])\n", "# ax.set_xticklabels(metrics)\n", "\n", "# # Plot data for each model and save the line objects for the legend\n", "# lines = []\n", "# for model in models:\n", "# values = data[dataset][model]\n", "# values += values[:1] # Close the loop for the data\n", "# line = ax.plot(angles, values, linewidth=2, linestyle='solid', label=model)\n", "# ax.fill(angles, values, alpha=0.25)\n", "# lines.append(line[0]) # Save the line for legend\n", "\n", "# # Set dynamic ylim based on the max and min of AUC, AUPR, and rescaled F1\n", "# dataset_values = [values for model_data in data[dataset].values() for values in model_data]\n", "# ax.set_ylim(min(dataset_values) - 5e-3, max(dataset_values) + 5e-5)\n", " \n", "# return lines" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Create the overall figure with a 2x2 layout\n", "fig, axs = plt.subplots(2, 2, figsize=(12, 12), subplot_kw=dict(polar=True))\n", "\n", "# Create radar charts for each dataset with dynamic ylim and collect line objects for the legend\n", "datasets = list(data_with_virtual_metrics.keys())\n", "lines_1 = create_radar_chart(axs[0, 0], datasets[0], data_with_virtual_metrics, models)\n", "axs[0, 0].set_title(f'{datasets[0]}', size=15, y=1.1)\n", "\n", "lines_2 = create_radar_chart(axs[0, 1], datasets[1], data_with_virtual_metrics, models)\n", "axs[0, 1].set_title(f'{datasets[1]}', size=15, y=1.1)\n", "\n", "lines_3 = create_radar_chart(axs[1, 0], datasets[2], data_with_virtual_metrics, models)\n", "axs[1, 0].set_title(f'{datasets[2]}', size=15, y=1.1)\n", "\n", "# Adjust the fourth quadrant to display the legend with correct colors\n", "axs[1, 1].axis('off') # Turn off the polar axis for the legend area\n", "fig.legend(handles=lines_1, loc='center', bbox_to_anchor=(0.75, 0.25), fontsize=20) # Place the legend in the blank subplot\n", "\n", "# Show the plot\n", "plt.tight_layout()\n", "plt.show()\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# # Create the overall figure with a 2x2 layout\n", "# fig, axs = plt.subplots(2, 2, figsize=(12, 12), subplot_kw=dict(polar=True))\n", "\n", "# # Create radar charts for each dataset with dynamic ylim and collect line objects for the legend\n", "# datasets = list(scaled_data_f1_to_auc_aupr_range.keys())\n", "# lines_1 = create_radar_chart(axs[0, 0], datasets[0], scaled_data_f1_to_auc_aupr_range, models)\n", "# axs[0, 0].set_title(f'{datasets[0]}', size=15, y=1.1)\n", "\n", "# lines_2 = create_radar_chart(axs[0, 1], datasets[1], scaled_data_f1_to_auc_aupr_range, models)\n", "# axs[0, 1].set_title(f'{datasets[1]}', size=15, y=1.1)\n", "\n", "# lines_3 = create_radar_chart(axs[1, 0], datasets[2], scaled_data_f1_to_auc_aupr_range, models)\n", "# axs[1, 0].set_title(f'{datasets[2]}', size=15, y=1.1)\n", "\n", "# # Adjust the fourth quadrant to display the legend with correct colors\n", "# axs[1, 1].axis('off') # Turn off the polar axis for the legend area\n", "# fig.legend(handles=lines_1, loc='center', bbox_to_anchor=(0.75, 0.25), fontsize=20) # Place the legend in the blank subplot\n", "\n", "# # Show the plot\n", "# plt.tight_layout()\n", "# plt.show()\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "metadata": {} }, "outputs": [], "source": [ "fig.savefig(\"img/Figure 3.tiff\", dpi=300, format='tiff')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Embedding Validation" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# # LLM Metrics\n", "# heatmap_data = pd.DataFrame({\n", "# 'Fdataset': [0.8815, 0.8737, 0.8754, 0.8758, 0.8557, 0.8914, 0.8864, 0.8819, 0.8814, 0.8589, 0.6526, 0.6292, 0.6490, 0.6491, 0.6382],\n", "# 'Cdataset': [0.9057, 0.8892, 0.8931, 0.8996, 0.8887, 0.9161, 0.9034, 0.9029, 0.9103, 0.8915, 0.6652, 0.6394, 0.6590, 0.6621, 0.6554],\n", "# 'Ydataset': [0.9298, 0.9094, 0.9275, 0.9242, 0.9042, 0.9330, 0.9156, 0.9297, 0.9269, 0.9060, 0.6768, 0.6495, 0.6770, 0.6740, 0.6639]\n", "# }, index=['SVM AUC', 'RandomForest AUC', 'XGBoost AUC', 'LightGBM AUC', 'MLP AUC', \n", "# 'SVM AUPR', 'RandomForest AUPR', 'XGBoost AUPR', 'LightGBM AUPR', 'MLP AUPR', \n", "# 'SVM F1', 'RandomForest F1', 'XGBoost F1', 'LightGBM F1', 'MLP F1'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# # Split the dataframe into separate metrics to create different color maps\n", "# auc_data = heatmap_data.loc[['SVM AUC', 'RandomForest AUC', 'XGBoost AUC', 'LightGBM AUC', 'MLP AUC']].rename(index=lambda x: x.split()[0])\n", "# aupr_data = heatmap_data.loc[['SVM AUPR', 'RandomForest AUPR', 'XGBoost AUPR', 'LightGBM AUPR', 'MLP AUPR']].rename(index=lambda x: x.split()[0])\n", "# f1_data = heatmap_data.loc[['SVM F1', 'RandomForest F1', 'XGBoost F1', 'LightGBM F1', 'MLP F1']].rename(index=lambda x: x.split()[0])\n", "\n", "# # Set up the figure\n", "# fig, axes = plt.subplots(1, 3, figsize=(18, 9))\n", "\n", "# # AUC Heatmap\n", "# sns.heatmap(auc_data, annot=True, fmt=\".4f\", cmap=\"Blues\", linewidths=.5, ax=axes[0])\n", "# axes[0].set_title('AUC Performance', fontsize=14)\n", "# axes[0].set_ylabel(\"Models\", fontsize=14)\n", "\n", "# # AUPR Heatmap\n", "# sns.heatmap(aupr_data, annot=True, fmt=\".4f\", cmap=\"Greens\", linewidths=.5, ax=axes[1])\n", "# axes[1].set_title('AUPR Performance', fontsize=14)\n", "# axes[1].set_xlabel(\"Dataset\", fontsize=14)\n", "\n", "# # F1 Heatmap\n", "# sns.heatmap(f1_data, annot=True, fmt=\".4f\", cmap=\"Oranges\", linewidths=.5, ax=axes[2])\n", "# axes[2].set_title('F1 Performance', fontsize=14)\n", "\n", "# # Show the plot\n", "# plt.tight_layout()\n", "# plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Data for the three datasets with counts of drugs, diseases, and associations\n", "dataset_counts = pd.DataFrame({\n", " 'Dataset': ['Fdataset', 'Cdataset', 'Ydataset'],\n", " 'Drugs': [593, 663, 1478],\n", " 'Diseases': [313, 409, 655],\n", " 'Associations': [1933, 2352, 8448]\n", "})\n", "\n", "# LLM Metrics heatmap data\n", "heatmap_data = pd.DataFrame({\n", " 'Fdataset': [0.8815, 0.8737, 0.8754, 0.8758, 0.8557, 0.8914, 0.8864, 0.8819, 0.8814, 0.8589, 0.6526, 0.6292, 0.6490, 0.6491, 0.6382],\n", " 'Cdataset': [0.9057, 0.8892, 0.8931, 0.8996, 0.8887, 0.9161, 0.9034, 0.9029, 0.9103, 0.8915, 0.6652, 0.6394, 0.6590, 0.6621, 0.6554],\n", " 'Ydataset': [0.9298, 0.9094, 0.9275, 0.9242, 0.9042, 0.9330, 0.9156, 0.9297, 0.9269, 0.9060, 0.6768, 0.6495, 0.6770, 0.6740, 0.6639]\n", "}, index=['SVM AUC', 'RandomForest AUC', 'XGBoost AUC', 'LightGBM AUC', 'MLP AUC', \n", " 'SVM AUPR', 'RandomForest AUPR', 'XGBoost AUPR', 'LightGBM AUPR', 'MLP AUPR', \n", " 'SVM F1', 'RandomForest F1', 'XGBoost F1', 'LightGBM F1', 'MLP F1'])\n", "\n", "# Split the data for AUC, AUPR, and F1\n", "auc_data = heatmap_data.loc[['SVM AUC', 'RandomForest AUC', 'XGBoost AUC', 'LightGBM AUC', 'MLP AUC']].rename(index=lambda x: x.split()[0])\n", "aupr_data = heatmap_data.loc[['SVM AUPR', 'RandomForest AUPR', 'XGBoost AUPR', 'LightGBM AUPR', 'MLP AUPR']].rename(index=lambda x: x.split()[0])\n", "f1_data = heatmap_data.loc[['SVM F1', 'RandomForest F1', 'XGBoost F1', 'LightGBM F1', 'MLP F1']].rename(index=lambda x: x.split()[0])\n", "\n", "# Set up the figure with an extra subplot for dataset counts\n", "fig, axes = plt.subplots(1, 4, figsize=(24, 9), gridspec_kw={'wspace': 0.4})\n", "\n", "# AUC Heatmap\n", "sns.heatmap(auc_data, annot=True, fmt=\".4f\", cmap=\"Blues\", linewidths=.5, ax=axes[0])\n", "axes[0].set_title('AUC Performance', fontsize=14)\n", "axes[0].set_ylabel(\"Models\", fontsize=16, labelpad=10)\n", "\n", "# AUPR Heatmap\n", "sns.heatmap(aupr_data, annot=True, fmt=\".4f\", cmap=\"Greens\", linewidths=.5, ax=axes[1])\n", "axes[1].set_title('AUPR Performance', fontsize=14)\n", "\n", "# F1 Heatmap\n", "sns.heatmap(f1_data, annot=True, fmt=\".4f\", cmap=\"Oranges\", linewidths=.5, ax=axes[2])\n", "axes[2].set_title('F1 Performance', fontsize=14)\n", "\n", "# Dataset count bar plot with colors matched to heatmaps\n", "axes[3].bar(dataset_counts['Dataset'], dataset_counts['Drugs'], color='#2777B8', label='Drugs')\n", "axes[3].bar(dataset_counts['Dataset'], dataset_counts['Diseases'], color='#4BB062', label='Diseases', bottom=dataset_counts['Drugs'])\n", "axes[3].bar(dataset_counts['Dataset'], dataset_counts['Associations'], color='#FDA35C', label='Associations', \n", " bottom=dataset_counts['Drugs'] + dataset_counts['Diseases'])\n", "\n", "# Add line plots to indicate trends for each category\n", "axes[3].plot(dataset_counts['Dataset'], dataset_counts['Drugs'], color='#3A8AC2', marker='o', linestyle='-', label='Drugs (trend)')\n", "axes[3].plot(dataset_counts['Dataset'], dataset_counts['Diseases'] + dataset_counts['Drugs'], color='#2ca02c', marker='o', linestyle='-', label='Diseases (trend)')\n", "axes[3].plot(dataset_counts['Dataset'], dataset_counts['Associations'] + dataset_counts['Drugs'] + dataset_counts['Diseases'], \n", " color='#ff7f0e', marker='o', linestyle='-', label='Associations (trend)')\n", "\n", "axes[3].set_title('Dataset Composition', fontsize=14)\n", "axes[3].legend(loc='upper left')\n", "axes[3].spines['top'].set_visible(False)\n", "axes[3].spines['right'].set_visible(False)\n", "\n", "fig.text(0.5, 0.05, 'Datasets', ha='center', fontsize=16)\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "fig.savefig(\"img/Figure 5.tiff\", dpi=300, format='tiff', bbox_inches='tight')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# # KG Metrics\n", "# heatmap_data = pd.DataFrame({\n", "# 'Fdataset': [0.7523, 0.7684, 0.7725, 0.7710, 0.7227, 0.7453, 0.7729, 0.7685, 0.7721, 0.7092, 0.5834, 0.5807, 0.5947, 0.5947, 0.5684],\n", "# 'Cdataset': [0.7873, 0.8062, 0.8197, 0.8198, 0.7584, 0.7735, 0.8054, 0.8135, 0.8115, 0.7394, 0.6020, 0.5994, 0.6196, 0.6196, 0.5859],\n", "# 'Ydataset': [0.8649, 0.8552, 0.8667, 0.8600, 0.8264, 0.8594, 0.8397, 0.8550, 0.8496, 0.8230, 0.6423, 0.6155, 0.6431, 0.6397, 0.6235]\n", "# }, index=['SVM AUC', 'RandomForest AUC', 'XGBoost AUC', 'LightGBM AUC', 'MLP AUC', \n", "# 'SVM AUPR', 'RandomForest AUPR', 'XGBoost AUPR', 'LightGBM AUPR', 'MLP AUPR', \n", "# 'SVM F1', 'RandomForest F1', 'XGBoost F1', 'LightGBM F1', 'MLP F1'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# # Heatmap\n", "# fig = plt.figure(figsize=(10, 8))\n", "# sns.heatmap(heatmap_data, annot=True, fmt=\".3f\", cmap=\"YlGnBu\", cbar_kws={'label': 'Performance'}, linewidths=.5)\n", "# plt.title(\"Heatmap of Model Performance on Different Datasets\", fontsize=14)\n", "# plt.ylabel(\"Model and Metric\")\n", "# plt.xlabel(\"Dataset\")\n", "# # Show\n", "# plt.tight_layout()\n", "# plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# # Split the dataframe into separate metrics to create different color maps\n", "# auc_data = heatmap_data.loc[['SVM AUC', 'RandomForest AUC', 'XGBoost AUC', 'LightGBM AUC', 'MLP AUC']].rename(index=lambda x: x.split()[0])\n", "# aupr_data = heatmap_data.loc[['SVM AUPR', 'RandomForest AUPR', 'XGBoost AUPR', 'LightGBM AUPR', 'MLP AUPR']].rename(index=lambda x: x.split()[0])\n", "# f1_data = heatmap_data.loc[['SVM F1', 'RandomForest F1', 'XGBoost F1', 'LightGBM F1', 'MLP F1']].rename(index=lambda x: x.split()[0])\n", "\n", "# # Set up the figure\n", "# fig, axes = plt.subplots(1, 3, figsize=(18, 9))\n", "\n", "# # AUC Heatmap\n", "# sns.heatmap(auc_data, annot=True, fmt=\".4f\", cmap=\"Blues\", linewidths=.5, ax=axes[0])\n", "# axes[0].set_title('AUC Performance', fontsize=14)\n", "# axes[0].set_ylabel(\"Models\", fontsize=14)\n", "\n", "# # AUPR Heatmap\n", "# sns.heatmap(aupr_data, annot=True, fmt=\".4f\", cmap=\"Greens\", linewidths=.5, ax=axes[1])\n", "# axes[1].set_title('AUPR Performance', fontsize=14)\n", "# axes[1].set_xlabel(\"Dataset\", fontsize=14)\n", "\n", "# # F1 Heatmap\n", "# sns.heatmap(f1_data, annot=True, fmt=\".4f\", cmap=\"Oranges\", linewidths=.5, ax=axes[2])\n", "# axes[2].set_title('F1 Performance', fontsize=14)\n", "\n", "# # Show the plot\n", "# plt.tight_layout()\n", "# plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "# Data for the three datasets with counts of drugs, diseases, and associations\n", "dataset_counts = pd.DataFrame({\n", " 'Dataset': ['Fdataset', 'Cdataset', 'Ydataset'],\n", " 'Drugs': [593, 663, 1478],\n", " 'Diseases': [313, 409, 655],\n", " 'Associations': [1933, 2352, 8448]\n", "})\n", "\n", "# KG Metrics\n", "heatmap_data = pd.DataFrame({\n", " 'Fdataset': [0.7523, 0.7684, 0.7725, 0.7710, 0.7227, 0.7453, 0.7729, 0.7685, 0.7721, 0.7092, 0.5834, 0.5807, 0.5947, 0.5947, 0.5684],\n", " 'Cdataset': [0.7873, 0.8062, 0.8197, 0.8198, 0.7584, 0.7735, 0.8054, 0.8135, 0.8115, 0.7394, 0.6020, 0.5994, 0.6196, 0.6196, 0.5859],\n", " 'Ydataset': [0.8649, 0.8552, 0.8667, 0.8600, 0.8264, 0.8594, 0.8397, 0.8550, 0.8496, 0.8230, 0.6423, 0.6155, 0.6431, 0.6397, 0.6235]\n", "}, index=['SVM AUC', 'RandomForest AUC', 'XGBoost AUC', 'LightGBM AUC', 'MLP AUC', \n", " 'SVM AUPR', 'RandomForest AUPR', 'XGBoost AUPR', 'LightGBM AUPR', 'MLP AUPR', \n", " 'SVM F1', 'RandomForest F1', 'XGBoost F1', 'LightGBM F1', 'MLP F1'])\n", "\n", "# Split the data for AUC, AUPR, and F1\n", "auc_data = heatmap_data.loc[['SVM AUC', 'RandomForest AUC', 'XGBoost AUC', 'LightGBM AUC', 'MLP AUC']].rename(index=lambda x: x.split()[0])\n", "aupr_data = heatmap_data.loc[['SVM AUPR', 'RandomForest AUPR', 'XGBoost AUPR', 'LightGBM AUPR', 'MLP AUPR']].rename(index=lambda x: x.split()[0])\n", "f1_data = heatmap_data.loc[['SVM F1', 'RandomForest F1', 'XGBoost F1', 'LightGBM F1', 'MLP F1']].rename(index=lambda x: x.split()[0])\n", "\n", "# Set up the figure with an extra subplot for dataset counts\n", "fig, axes = plt.subplots(1, 4, figsize=(24, 9), gridspec_kw={'wspace': 0.4})\n", "\n", "# AUC Heatmap\n", "sns.heatmap(auc_data, annot=True, fmt=\".4f\", cmap=\"Blues\", linewidths=.5, ax=axes[0])\n", "axes[0].set_title('AUC Performance', fontsize=14)\n", "axes[0].set_ylabel(\"Models\", fontsize=16, labelpad=10)\n", "\n", "# AUPR Heatmap\n", "sns.heatmap(aupr_data, annot=True, fmt=\".4f\", cmap=\"Greens\", linewidths=.5, ax=axes[1])\n", "axes[1].set_title('AUPR Performance', fontsize=14)\n", "\n", "# F1 Heatmap\n", "sns.heatmap(f1_data, annot=True, fmt=\".4f\", cmap=\"Oranges\", linewidths=.5, ax=axes[2])\n", "axes[2].set_title('F1 Performance', fontsize=14)\n", "\n", "# Dataset count bar plot with colors matched to heatmaps\n", "axes[3].bar(dataset_counts['Dataset'], dataset_counts['Drugs'], color='#2777B8', label='Drugs')\n", "axes[3].bar(dataset_counts['Dataset'], dataset_counts['Diseases'], color='#4BB062', label='Diseases', bottom=dataset_counts['Drugs'])\n", "axes[3].bar(dataset_counts['Dataset'], dataset_counts['Associations'], color='#FDA35C', label='Associations', \n", " bottom=dataset_counts['Drugs'] + dataset_counts['Diseases'])\n", "\n", "# Add line plots to indicate trends for each category\n", "axes[3].plot(dataset_counts['Dataset'], dataset_counts['Drugs'], color='#3A8AC2', marker='o', linestyle='-', label='Drugs (trend)')\n", "axes[3].plot(dataset_counts['Dataset'], dataset_counts['Diseases'] + dataset_counts['Drugs'], color='#2ca02c', marker='o', linestyle='-', label='Diseases (trend)')\n", "axes[3].plot(dataset_counts['Dataset'], dataset_counts['Associations'] + dataset_counts['Drugs'] + dataset_counts['Diseases'], \n", " color='#ff7f0e', marker='o', linestyle='-', label='Associations (trend)')\n", "\n", "axes[3].set_title('Dataset Composition', fontsize=14)\n", "axes[3].legend(loc='upper left')\n", "axes[3].spines['top'].set_visible(False)\n", "axes[3].spines['right'].set_visible(False)\n", "\n", "fig.text(0.5, 0.05, 'Datasets', ha='center', fontsize=16)\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "metadata": {} }, "outputs": [], "source": [ "fig.savefig(\"img/Figure 4.tiff\", dpi=300, format='tiff', bbox_inches='tight')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Enhanced Input" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "metadata": {} }, "outputs": [], "source": [ "data_file = 'data/Benchmark/amvl_idrug.xlsx'\n", "df = pd.read_excel(data_file)\n", "df.head()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# Define a function to extract mean, lower, and upper bounds from the given data format\n", "def parse_performance(value):\n", " mean, ci = value.split(\" (\")\n", " lower, upper = ci[:-1].split(\" - \")\n", " return float(mean), float(lower), float(upper)\n", "\n", "# Define model combinations (metrics) explicitly\n", "metrics = df.columns[3:].to_list()\n", "\n", "# Filter data for Fdataset only\n", "fdataset_data = df[df[\"dataset\"] == \"iDrug\"]\n", "\n", "# Parse data for AUC, AUPR, and F1 metrics\n", "parsed_fdataset_data = []\n", "for _, row in fdataset_data.iterrows():\n", " for column in metrics:\n", " if column in row.index: # Ensure the column exists in the row\n", " mean, lower, upper = parse_performance(row[column])\n", " parsed_fdataset_data.append({\n", " \"metric\": row[\"metric\"],\n", " \"model\": column,\n", " \"mean\": mean,\n", " \"lower\": lower,\n", " \"upper\": upper\n", " })\n", "\n", "# Convert processed data to a new DataFrame\n", "parsed_fdataset_df = pd.DataFrame(parsed_fdataset_data)\n", "parsed_fdataset_df.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "colors = [\n", " '#AAD09D', # 浅绿\n", " '#66BC98', # 青绿\n", " '#E3EA96', # 浅黄\n", " '#FDCB89', # 新增:浅橙\n", " '#4DA8DA', # 新增:浅蓝\n", " '#3288BD', # 蓝色\n", " '#2C559A',\n", " '#F46D43', # 橙红\n", " '#C154C1', # 新增:紫色\n", " '#8A233F', # 深红\n", " '#6C3483' # 新增:深紫\n", "]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def draw_color(colors):\n", " # 图形设置\n", " fig, ax = plt.subplots(figsize=(10, 2))\n", " \n", " # 绘制每种颜色\n", " for i, color in enumerate(colors):\n", " ax.add_patch(plt.Rectangle((i, 0), 1, 1, color=color))\n", " ax.text(i + 0.5, -0.5, color, ha='center', fontsize=10) # 在颜色块下方显示颜色代码\n", " \n", " # 设置 x 和 y 的范围\n", " ax.set_xlim(0, len(colors))\n", " ax.set_ylim(-1, 1)\n", " \n", " # 去除坐标轴\n", " ax.axis('off')\n", " \n", " # 显示图形\n", " plt.show()\n", "\n", "draw_color(colors)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 准备模型和指标的唯一值\n", "models = parsed_fdataset_df[\"model\"].unique()\n", "metrics = parsed_fdataset_df[\"metric\"].unique()\n", "x = np.arange(len(models)) # 模型的 x 坐标\n", "\n", "# 设置子图布局\n", "fig, axs = plt.subplots(2, 2, figsize=(14, 10), dpi=300)\n", "axs = axs.flatten()\n", "\n", "# 遍历每个指标并绘制子图\n", "for idx, metric in enumerate([\"auc\", \"aupr\", \"f1\"]):\n", " ax = axs[idx]\n", " data = parsed_fdataset_df[parsed_fdataset_df[\"metric\"] == metric]\n", " means = data[\"mean\"]\n", " errors = [data[\"mean\"] - data[\"lower\"], data[\"upper\"] - data[\"mean\"]]\n", "\n", " # 绘制条形图\n", " ax.bar(x, means, width=0.4, yerr=errors, capsize=5, label=metric.upper(), color=colors[idx + 1])\n", "\n", " # 添加趋势线\n", " ax.plot(x, means, marker='o', color='red', linestyle='--', label=f\"Trendline\")\n", "\n", " # 子图定制\n", " ax.set_xticks(x)\n", " ax.set_xticklabels(models, rotation=45, ha=\"right\", fontsize=10)\n", " ax.set_ylabel(\"Performance\", fontsize=12)\n", " \n", " if metric == \"auc\":\n", " ax.set_ylim(0.964, 0.970)\n", " elif metric == \"aupr\":\n", " ax.set_ylim(0.968, 0.9715)\n", " elif metric == \"f1\":\n", " ax.set_ylim(0.705, 0.740)\n", " \n", " ax.legend(fontsize=10)\n", " ax.spines['top'].set_visible(False)\n", " ax.spines['right'].set_visible(False)\n", " ax.tick_params(axis='x', labelsize=10)\n", " ax.tick_params(axis='y', labelsize=10)\n", " ax.text(-0.12, 1.1, chr(97 + idx), transform=ax.transAxes, size=18, weight='bold') # 子图标注\n", "\n", "# 绘制总体图\n", "overall_ax = axs[3]\n", "overall_means = []\n", "for model in models:\n", " model_data = parsed_fdataset_df[parsed_fdataset_df[\"model\"] == model]\n", " overall_mean = model_data[\"mean\"].mean()\n", " overall_means.append(overall_mean)\n", "overall_means = np.array(overall_means)\n", "\n", "# 绘制总体条形图\n", "overall_ax.bar(x, overall_means, width=0.4, color=colors[4], label=\"Overall\")\n", "\n", "# 添加总体趋势线\n", "overall_ax.plot(x, overall_means, marker='o', color=colors[6], linestyle='--', label=\"Trendline\")\n", "\n", "# 总体图定制\n", "overall_ax.set_xticks(x)\n", "overall_ax.set_xticklabels(models, rotation=45, ha=\"right\", fontsize=10)\n", "overall_ax.set_ylabel(\"Mean Performance\", fontsize=12)\n", "overall_ax.set_ylim(0.88, 0.8930)\n", "overall_ax.legend(fontsize=10)\n", "overall_ax.spines['top'].set_visible(False)\n", "overall_ax.spines['right'].set_visible(False)\n", "overall_ax.tick_params(axis='x', labelsize=10)\n", "overall_ax.tick_params(axis='y', labelsize=10)\n", "overall_ax.text(-0.12, 1.1, 'd', transform=overall_ax.transAxes, size=18, weight='bold') # 子图标注\n", "\n", "# 调整布局并显示\n", "plt.tight_layout(w_pad=2)\n", "plt.savefig('img/Fig. 8.tiff', dpi=300)\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 2 }