python - 如何为 DNA 序列生成一个热编码?

标签 python arrays scikit-learn itertools one-hot-encoding

我想为一组 DNA 序列生成一个热编码。例如,序列 AGCTCCA 可以以转置方式表示如下。但是下面的代码将以水平方式生成一种热编码,我更喜欢以垂直形式进行编码。谁能帮我?

ACGTCCA 
1000001 - A
0100110 - C 
0010000 - G
0001000 - T

示例代码:
from sklearn.preprocessing import OneHotEncoder
import itertools

# two example sequences
seqs = ["ACGTCCA","CGGATTG"]


# split sequences to tokens
tokens_seqs = [seq.split("\\") for seq in seqs]

# convert list of of token-lists to one flat list of tokens
# and then create a dictionary that maps word to id of word,
# like {A: 1, B: 2} here
all_tokens = itertools.chain.from_iterable(tokens_seqs)
word_to_id = {token: idx for idx, token in enumerate(set(all_tokens))}

# convert token lists to token-id lists, e.g. [[1, 2], [2, 2]] here
token_ids = [[word_to_id[token] for token in tokens_seq] for tokens_seq in tokens_seqs]

# convert list of token-id lists to one-hot representation
vec = OneHotEncoder(n_values=len(word_to_id))
X = vec.fit_transform(token_ids)

print X.toarray()

但是,代码给了我输出:
[[ 0.  1.]
 [ 1.  0.]]

预期输出:
[[1. 0. 0. 0. 0. 0. 1. 0. 1. 0. 0. 1. 1. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 1. 0. 0. 0. 1. 0. 0. 0. 0. 1. 1. 0.]]

最佳答案

我建议以稍微更手动的方式进行:

import numpy as np

seqs = ["ACGTCCA","CGGATTG"]

CHARS = 'ACGT'
CHARS_COUNT = len(CHARS)

maxlen = max(map(len, seqs))
res = np.zeros((len(seqs), CHARS_COUNT * maxlen), dtype=np.uint8)

for si, seq in enumerate(seqs):
    seqlen = len(seq)
    arr = np.chararray((seqlen,), buffer=seq)
    for ii, char in enumerate(CHARS):
        res[si][ii*seqlen:(ii+1)*seqlen][arr == char] = 1

print res

这会给你你想要的结果:
[[1 0 0 0 0 0 1 0 1 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0]
 [0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 0 1 1 0]]

关于python - 如何为 DNA 序列生成一个热编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34263772/

相关文章:

python - 使用 openpyxl 创建条形图,x 轴上带有日期

python - wxPython wxScrolledWindow 函数引发 TypeError

python - 随机森林分类器分割错误

arrays - 循环中的数组可能会丢失精度误差

java - Java 获取 JSON 数组的方法

python - 如何导入sklearn.impute?

python - sklearn Python 和逻辑回归

python - shiboken 类型系统不继承类

python - 对 numpy 数组的选定行求和的简洁方法

java - 为什么不能在 while 循环中将 array[n] 与 null 进行比较?