Machine Learning
Biopython sits upstream of the ML stack: it parses biological data into tables and features (sequences, k-mers, physico-chemical properties, expression values) that scikit-learn, XGBoost, and deep learning frameworks consume. The recipe is always: Biopython for data, scikit-learn for the model, and domain logic for evaluation.
Sequence Features: k-mers
from collections import Counter
def kmer_vector(seq, k=4):
kmers = [seq[i:i + k] for i in range(len(seq) - k + 1)]
return Counter(kmers)
# build a feature matrix over many sequences
seqs = ["ATGCATGC", "GGCCGGCC"]
all_k = sorted(set(k for s in seqs for k in kmer_vector(s, 4)))
X = [[kmer_vector(s, 4).get(k, 0) for k in all_k] for s in seqs]
print(all_k)
print(X)
A Classification Pipeline
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
# X: feature matrix, y: labels (e.g., pathogen vs commensal)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
print(classification_report(y_test, model.predict(X_test)))
Physico-Chemical Features (Proteins)
from Bio.SeqUtils.ProtParam import ProteinAnalysis
aa = ProteinAnalysis("MKTAYIAKQRQISFVKSHFSR")
print(aa.gravy()) # isoelectric point estimate
print(aa.aromaticity()) # fraction aromatic
print(aa.charge()) # net charge at pH 7
ProteinAnalysis gives GRAVY, aromaticity, instability, and charge - useful features for predicting solubility, membrane association, or enzyme class.
Evaluation That Respects Biology
- Split by sample, not by row, when sequences from the same organism are correlated - otherwise you leak information.
- Report per-class precision/recall, not just accuracy, for imbalanced taxonomic labels.
- Validate on a truly held-out set (different species or time point) before claiming generalization.
End-to-End Example
- Parse FASTA with SeqIO; compute k-mer and property features per sequence.
- Assemble X (features) and y (labels) as NumPy arrays.
- Train/test split by organism; fit a scikit-learn model.
- Evaluate with classification_report; inspect top feature importances.
Summary
Use Biopython as the feature engine for ML: k-mer counts from sequences, ProteinAnalysis physico-chemical properties, and alignment-based statistics feed scikit-learn models. The critical discipline is biological splitting (by organism/sample) and per-class evaluation - the model is only as honest as the split.