Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run PLSR plot #101

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions pf2/figures/figureA9.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@
from sklearn.metrics import accuracy_score
import seaborn as sns
from ..data_import import convert_to_patients, import_meta
from ..predict import predict_mortality
from ..predict import predict_mortality, predict_mortality_all
from .common import subplotLabel, getSetup
from sklearn.metrics import RocCurveDisplay
from sklearn.metrics import accuracy_score, roc_auc_score
from pf2.figures.commonFuncs.plotGeneral import bal_combine_bo_covid


def makeFigure():
Expand All @@ -21,23 +22,29 @@ def makeFigure():

X = anndata.read_h5ad("/opt/northwest_bal/full_fitted.h5ad")

meta = import_meta()
conversions = convert_to_patients(X)
meta = import_meta(drop_duplicates=False)
conversions = convert_to_patients(X, sample=True)

patient_factor = pd.DataFrame(
X.uns["Pf2_A"],
index=conversions,
columns=np.arange(X.uns["Pf2_A"].shape[1]) + 1,
)
meta = meta.loc[patient_factor.index, :]
meta.set_index("sample_id", inplace=True)

shared_indices = patient_factor.index.intersection(meta.index)
patient_factor = patient_factor.loc[shared_indices, :]
meta = meta.loc[shared_indices, :]


roc_auc = [False, True]
for i in range(2):
plsr_acc_df = pd.DataFrame([])
for j in range(3):
df = plsr_acc_proba(
patient_factor, meta, n_components=j + 1, roc_auc=roc_auc[i]
)
print(df)
df["Component"] = j + 1
plsr_acc_df = pd.concat([plsr_acc_df, df], axis=0)

Expand Down Expand Up @@ -65,6 +72,10 @@ def plsr_acc_proba(patient_factor_matrix, meta_data, n_components=2, roc_auc=Tru
probabilities, labels = predict_mortality(
patient_factor_matrix, n_components=n_components, meta=meta_data, proba=True
)

probabilities_all, labels_all = predict_mortality_all(
patient_factor_matrix, n_components=n_components, meta=meta_data, proba=True
)

probabilities = probabilities.round().astype(int)
meta_data = meta_data.loc[~meta_data.index.duplicated()].loc[labels.index]
Expand All @@ -73,16 +84,16 @@ def plsr_acc_proba(patient_factor_matrix, meta_data, n_components=2, roc_auc=Tru
score = roc_auc_score
else:
score = accuracy_score

covid_acc = score(
labels.loc[meta_data.loc[:, "patient_category"] == "COVID-19"],
probabilities.loc[meta_data.loc[:, "patient_category"] == "COVID-19"],
labels.loc[meta_data.loc[:, "patient_category"] == "COVID-19"].to_numpy().astype(int),
probabilities.loc[meta_data.loc[:, "patient_category"] == "COVID-19"].to_numpy(),
)
Comment on lines 88 to 91
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid typing headaches later, let's use to_numpy() for either all of the probabilities variables or none of them.

nc_acc = score(
labels.loc[meta_data.loc[:, "patient_category"] != "COVID-19"],
labels.loc[meta_data.loc[:, "patient_category"] != "COVID-19"].to_numpy().astype(int),
probabilities.loc[meta_data.loc[:, "patient_category"] != "COVID-19"],
)
acc = score(labels, probabilities)
acc = score(labels_all.to_numpy().astype(int), probabilities_all.round().astype(int))

acc_df.loc[0, :] = [acc, covid_acc, nc_acc]

Expand All @@ -97,17 +108,17 @@ def plot_plsr_auc_roc(patient_factor_matrix, meta_data, ax):
meta_data = meta_data.loc[~meta_data.index.duplicated()].loc[labels.index]

RocCurveDisplay.from_predictions(
labels.loc[meta_data.loc[:, "patient_category"] == "COVID-19"],
labels.loc[meta_data.loc[:, "patient_category"] == "COVID-19"].to_numpy().astype(int),
probabilities.loc[meta_data.loc[:, "patient_category"] == "COVID-19"],
ax=ax,
name="C19",
)
RocCurveDisplay.from_predictions(
labels.loc[meta_data.loc[:, "patient_category"] != "COVID-19"],
labels.loc[meta_data.loc[:, "patient_category"] != "COVID-19"].to_numpy().astype(int),
probabilities.loc[meta_data.loc[:, "patient_category"] != "COVID-19"],
ax=ax,
name="nC19",
)
RocCurveDisplay.from_predictions(
labels, probabilities, plot_chance_level=True, ax=ax, name="Overall"
labels.to_numpy().astype(int), probabilities, plot_chance_level=True, ax=ax, name="Overall"
)
41 changes: 41 additions & 0 deletions pf2/predict.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,44 @@ def predict_mortality(
else:
predicted = predictions.round().astype(int)
return accuracy_score(labels, predicted), labels, (c_plsr, nc_plsr)


def predict_mortality_all(
data: pd.DataFrame, meta: pd.DataFrame, proba: bool = False, n_components=2
):
"""
Predicts mortality via cross-validation.

Parameters:
data (pd.DataFrame): data to predict
meta (pd.DataFrame): patient meta-data
proba (bool, default:False): return probability of prediction

Returns:
if proba:
probabilities (pd.Series): predicted probability of mortality for
patients
labels (pd.Series): classification targets
else:
accuracy (float): prediction accuracy
models (tuple[COVID, Non-COVID]): fitted PLSR models
"""
if not isinstance(data, pd.DataFrame):
data = pd.DataFrame(data)

data = data.loc[meta.loc[:, "patient_category"] != "Non-Pneumonia Control", :]
meta = meta.loc[meta.loc[:, "patient_category"] != "Non-Pneumonia Control", :]
labels = data.index.to_series().replace(meta.loc[:, "binary_outcome"])
labels = pd.Series(index=labels.index, data=labels.to_numpy().astype(int))

predictions = pd.Series(index=data.index)
predictions[:], all_plsr = run_plsr(
data, labels, proba=proba, n_components=n_components
)

if proba:
return predictions, labels

else:
predicted = predictions.round().astype(int)
return accuracy_score(labels, predicted), labels, all_plsr
Loading