Instructions to use mineself2016/GeneMamba with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use mineself2016/GeneMamba with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="mineself2016/GeneMamba", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("mineself2016/GeneMamba", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Remove stale path: examples/downstream/11_zero_shot_logreg.py
Browse files
examples/downstream/11_zero_shot_logreg.py
DELETED
|
@@ -1,98 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Zero-shot downstream baseline:
|
| 3 |
-
1) Extract frozen GeneMamba embeddings
|
| 4 |
-
2) Train LogisticRegression on train split
|
| 5 |
-
3) Evaluate on test split
|
| 6 |
-
|
| 7 |
-
Expected h5ad columns:
|
| 8 |
-
- obs['celltype']
|
| 9 |
-
- obs['partition'] with values in {'train', 'test'}
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
import argparse
|
| 13 |
-
import numpy as np
|
| 14 |
-
import scanpy as sc
|
| 15 |
-
import torch
|
| 16 |
-
from sklearn.linear_model import LogisticRegression
|
| 17 |
-
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
|
| 18 |
-
from sklearn.preprocessing import LabelEncoder
|
| 19 |
-
from transformers import AutoModel
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def build_ranked_input_ids(adata, symbol2id, seq_len=2048, pad_id=1):
|
| 23 |
-
gene_names = np.array(adata.var_names)
|
| 24 |
-
X = adata.X
|
| 25 |
-
out = np.full((adata.n_obs, seq_len), pad_id, dtype=np.int64)
|
| 26 |
-
|
| 27 |
-
for i in range(adata.n_obs):
|
| 28 |
-
row = X[i]
|
| 29 |
-
if hasattr(row, "toarray"):
|
| 30 |
-
expr = row.toarray().ravel()
|
| 31 |
-
else:
|
| 32 |
-
expr = np.asarray(row).ravel()
|
| 33 |
-
|
| 34 |
-
nz = np.where(expr > 0)[0]
|
| 35 |
-
if len(nz) == 0:
|
| 36 |
-
continue
|
| 37 |
-
|
| 38 |
-
genes = gene_names[nz]
|
| 39 |
-
vals = expr[nz]
|
| 40 |
-
order = np.argsort(-vals)
|
| 41 |
-
ranked_genes = genes[order]
|
| 42 |
-
ids = [symbol2id[g] for g in ranked_genes if g in symbol2id][:seq_len]
|
| 43 |
-
out[i, : len(ids)] = ids
|
| 44 |
-
|
| 45 |
-
return out
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def main():
|
| 49 |
-
parser = argparse.ArgumentParser()
|
| 50 |
-
parser.add_argument("--model_path", required=True)
|
| 51 |
-
parser.add_argument("--h5ad", required=True)
|
| 52 |
-
parser.add_argument("--symbol2id_npy", default=None, help="Optional .npy dumped dict path")
|
| 53 |
-
parser.add_argument("--seq_len", type=int, default=2048)
|
| 54 |
-
parser.add_argument("--batch_size", type=int, default=64)
|
| 55 |
-
args = parser.parse_args()
|
| 56 |
-
|
| 57 |
-
adata = sc.read_h5ad(args.h5ad)
|
| 58 |
-
assert "celltype" in adata.obs, "h5ad must include obs['celltype']"
|
| 59 |
-
assert "partition" in adata.obs, "h5ad must include obs['partition']"
|
| 60 |
-
|
| 61 |
-
if args.symbol2id_npy is None:
|
| 62 |
-
raise ValueError("Please provide --symbol2id_npy (dict saved by np.save(..., allow_pickle=True))")
|
| 63 |
-
|
| 64 |
-
symbol2id = np.load(args.symbol2id_npy, allow_pickle=True).item()
|
| 65 |
-
|
| 66 |
-
input_ids = build_ranked_input_ids(adata, symbol2id, seq_len=args.seq_len)
|
| 67 |
-
labels = LabelEncoder().fit_transform(adata.obs["celltype"].values)
|
| 68 |
-
|
| 69 |
-
model = AutoModel.from_pretrained(args.model_path, trust_remote_code=True)
|
| 70 |
-
model.eval().cuda()
|
| 71 |
-
|
| 72 |
-
embeds = []
|
| 73 |
-
with torch.no_grad():
|
| 74 |
-
for s in range(0, input_ids.shape[0], args.batch_size):
|
| 75 |
-
batch = torch.tensor(input_ids[s : s + args.batch_size], dtype=torch.long, device="cuda")
|
| 76 |
-
out = model(batch)
|
| 77 |
-
embeds.append(out.pooled_embedding.detach().cpu().numpy())
|
| 78 |
-
embeds = np.concatenate(embeds, axis=0)
|
| 79 |
-
|
| 80 |
-
train_mask = adata.obs["partition"].values == "train"
|
| 81 |
-
test_mask = adata.obs["partition"].values == "test"
|
| 82 |
-
|
| 83 |
-
X_train, y_train = embeds[train_mask], labels[train_mask]
|
| 84 |
-
X_test, y_test = embeds[test_mask], labels[test_mask]
|
| 85 |
-
|
| 86 |
-
clf = LogisticRegression(max_iter=2000)
|
| 87 |
-
clf.fit(X_train, y_train)
|
| 88 |
-
pred = clf.predict(X_test)
|
| 89 |
-
|
| 90 |
-
print("accuracy:", accuracy_score(y_test, pred))
|
| 91 |
-
print("micro_f1:", f1_score(y_test, pred, average="micro"))
|
| 92 |
-
print("macro_f1:", f1_score(y_test, pred, average="macro"))
|
| 93 |
-
print("precision_weighted:", precision_score(y_test, pred, average="weighted", zero_division=0))
|
| 94 |
-
print("recall_weighted:", recall_score(y_test, pred, average="weighted", zero_division=0))
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
if __name__ == "__main__":
|
| 98 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|