DNA序列k-mer特征提取及KNN分类模型应用
import numpy as np from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from Bio import SeqIO from scipy.sparse import lil_matrix
k-mer方法将DNA序列转换为特征向量
def kmer_to_feature(sequence, k=3): for i in range(len(sequence) - k + 1): kmer = sequence[i:i+k] if 'N' not in kmer: index = 0 for base in kmer: if base == 'A': index = index * 4 + 0 elif base == 'C': index = index * 4 + 1 elif base == 'G': index = index * 4 + 2 elif base == 'T': index = index * 4 + 3 yield index
读取FASTA文件
def read_fasta_file(file_path): with open(file_path) as f: while True: chunk = list(SeqIO.parse(f, 'fasta')) if not chunk: break sequences = [str(record.seq) for record in chunk] labels = [record.id for record in chunk] yield sequences, labels
读取数据集
sequences_all = [] labels_all = [] for sequences, labels in read_fasta_file('MJ.fasta'): sequences_all += sequences labels_all += labels X = lil_matrix((len(labels_all), 4**3), dtype=np.float32) y = [] for i, sequence in enumerate(sequences_all): for j, index in enumerate(kmer_to_feature(sequence)): X[i, index] = 1.0 y.append(labels_all[i]) y = np.array(y)
划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=43)
训练和测试模型
k_values = [1, 3, 5, 7, 9] for k in k_values: knn = KNeighborsClassifier(n_neighbors=k) knn.fit(X_train, y_train) y_pred = knn.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print('For k =', k, ', accuracy is', accuracy
原文地址: https://www.cveoy.top/t/topic/lKLg 著作权归作者所有。请勿转载和采集!