Q&A 20 How do you train a Support Vector Machine (SVM) for microbiome classification?
20.1 Explanation
Support Vector Machines (SVM) are powerful classifiers for high-dimensional biological data. They find a decision boundary (hyperplane) that maximizes class separation.
SVMs are well-suited for microbiome data because: - They can handle many features (OTUs) - Work with kernel functions for non-linear separation - Often perform well with sparse data
20.2 Python Code
import pandas as pd
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.model_selection import train_test_split
# Load and prepare data
otu_df = pd.read_csv("data/otu_table_filtered.tsv", sep="\t", index_col=0).T
meta_df = pd.read_csv("data/sample_metadata.tsv", sep="\t")
data = pd.merge(otu_df, meta_df, left_index=True, right_on="sample_id")
X = data[otu_df.columns]
y = data["group"].map({"Control": 0, "Treatment": 1})
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Train SVM
model = SVC(kernel='linear', probability=True, random_state=42)
model.fit(X_train, y_train)
# Predict and evaluate
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
cm = confusion_matrix(y_test, y_pred)
print(f"Accuracy: {acc:.2f}")
print("Confusion Matrix:")
print(cm)
20.3 R Code (caret)
library(tidyverse)
library(caret)
otu_df <- read.delim("data/otu_table_filtered.tsv", row.names = 1)
meta_df <- read.delim("data/sample_metadata.tsv")
otu_df <- otu_df[, meta_df$sample_id]
otu_df <- t(otu_df)
data <- cbind(as.data.frame(otu_df), group = meta_df$group)
# Encode group and split
data$group <- as.factor(data$group)
set.seed(42)
trainIndex <- createDataPartition(data$group, p = .7, list = FALSE)
train <- data[trainIndex, ]
test <- data[-trainIndex, ]
# Train SVM
svm_model <- train(group ~ ., data = train, method = "svmLinear", trControl = trainControl(method = "cv", number = 5))
# Predict and evaluate
pred <- predict(svm_model, newdata = test)
confusionMatrix(pred, test$group)
Confusion Matrix and Statistics
Reference
Prediction Control Treatment
Control 0 0
Treatment 1 1
Accuracy : 0.5
95% CI : (0.0126, 0.9874)
No Information Rate : 0.5
P-Value [Acc > NIR] : 0.75
Kappa : 0
Mcnemar's Test P-Value : 1.00
Sensitivity : 0.0
Specificity : 1.0
Pos Pred Value : NaN
Neg Pred Value : 0.5
Prevalence : 0.5
Detection Rate : 0.0
Detection Prevalence : 0.0
Balanced Accuracy : 0.5
'Positive' Class : Control