本团队提供生物医学领域专业的AI(机器学习、深度学习)技术支持服务。如果您有需求,请扫描文末二维码关注我们。
在对氨基酸序列数据进行深度学习模型构建时,首先需要将字符形式的序列数据进行编码操作。最简单的当然是One-hot编码,但会引入稀疏性问题。这里提供一种基于预训练模型的编码方法,代码如下:
import os
import pandas as pd
import numpy as np
from sentence_transformers import SentenceTransformer
import warnings
warnings.filterwarnings('ignore')
# 定义读取FASTA格式的氨基酸序列文件
def read_fasta(file_path):
with open(file_path, 'r') as file:
sequences = []
sequence_names = []
current_sequence = []
for line in file:
line = line.strip()
if line.startswith('>'):
if current_sequence:
sequences.append(''.join(current_sequence))
current_sequence = []
sequence_names.append(line[1:])
else:
current_sequence.append(line)
if current_sequence:
sequences.append(''.join(current_sequence))
# 返回两个list
# 第一个为序列名,第二个为序列
return sequence_names, sequences
# 将自动下载预训练模型,如果失败,需要手动从网站下载。
# 网站地址:https://huggingface.co/monsoon-nlp/protein-matryoshka-embeddings
model = SentenceTransformer('monsoon-nlp/protein-matryoshka-embeddings')
# 创建结果文件
outdir = 'embedding_results'
os.makedirs(outdir, exist_ok=True)
os.makedirs(f"{outdir}/SingleSeqEmbedding", exist_ok=True)
# 读取氨基酸序列
sequence_names, sequences = read_fasta('proteinSquence-zheng.txt')
print(f"共读入了 {len(sequence_names)} 条氨基酸序列")
# 将读入的序列转为CSV格式,并进行保存
df = pd.DataFrame({'seq_name': sequence_names,
'sequence': sequences
})
df.to_csv(f"{outdir}/sequences.csv", index=False)
# 每条序列单独编码
for idx, sequence in enumerate(sequences):
embedding = model.encode(sequence)
np.save(f'{outdir}/SingleSeqEmbedding/embedding_{idx}.npy', embedding)
# 所有序列编码为一个矩阵
embeddings = model.encode(sequences)
np.save(f'{outdir}/embeddings.npy', embeddings)
print('编码后的序列维度为: ', embeddings.shape)