【DNA数据学习】从DNA序列到模型预测
文章目录
- [从 DNA 序列到模型预测的 Jupyter 入门教程](#从 DNA 序列到模型预测的 Jupyter 入门教程)
-
- [1. 下载数据,打开 JupyterLab](#1. 下载数据,打开 JupyterLab)
-
- 把数据存到练习文件夹
- [创建 `Gene` 环境](#创建
Gene环境) - [第 1 格 确认环境和文件位置](#第 1 格 确认环境和文件位置)
- [2. 从 CSV 里取出一条 DNA](#2. 从 CSV 里取出一条 DNA)
-
- [第 2 格 看看表格的样子](#第 2 格 看看表格的样子)
- [第 3 格 把第一行拼成一条序列](#第 3 格 把第一行拼成一条序列)
- [第 4 格 把三类样本的中心画出来](#第 4 格 把三类样本的中心画出来)
- [第 5 格 看看三类各有多少条](#第 5 格 看看三类各有多少条)
- [3. 把 DNA 变成模型能用的数字](#3. 把 DNA 变成模型能用的数字)
-
- [第 6 格 亲手看一次独热编码](#第 6 格 亲手看一次独热编码)
- [第 7 格 用热图看编码里保留了什么](#第 7 格 用热图看编码里保留了什么)
- [4. 留出测试序列,再训练模型](#4. 留出测试序列,再训练模型)
-
- [第 8 格 去掉重复序列并划分数据](#第 8 格 去掉重复序列并划分数据)
- [第 9 格 看看每一类怎样分到两组](#第 9 格 看看每一类怎样分到两组)
- [第 10 格 训练逻辑回归](#第 10 格 训练逻辑回归)
- [5. 看模型怎样判断一条 DNA](#5. 看模型怎样判断一条 DNA)
-
- [第 11 格 先看编号 0 的测试样本](#第 11 格 先看编号 0 的测试样本)
- [第 12 格 拉动滑块换一条样本](#第 12 格 拉动滑块换一条样本)
- [6. 读懂模型在整批测试集上的表现](#6. 读懂模型在整批测试集上的表现)
-
- [第 13 格 对比准确率和混淆矩阵](#第 13 格 对比准确率和混淆矩阵)
从 DNA 序列到模型预测的 Jupyter 入门教程
给模型一条 60 个碱基长的 DNA 序列,它能判断序列正中间是不是剪接边界吗?这次练习就做这一件事。你会把 A、C、G、T 变成数字,用这些数字训练一个模型,再拖动滑块,看看它对不同 DNA 序列的判断。
剪接边界是外显子和内含子相接的位置。RNA 剪接时,细胞会把内含子从前体 mRNA 中去掉,再把两侧的外显子接起来。
剪接前 外显子 1 │ 内含子 │ 外显子 2
剪接后 外显子 1 ───────── 外显子 2
示例中两个 │ 都是剪接边界。沿着转录方向看,左边从外显子进入内含子,叫剪接供体位点(EI)。右边从内含子进入外显子,叫剪接受体位点(IE)。
数据来自 UCI 的灵长类 DNA 剪接位点数据集。官方 CSV 约 455 KB,包含 3,190 条固定长度的序列,每条都配有已知答案。用 Windows 电脑的 CPU 就能跑完。UCI 数据集说明

1. 下载数据,打开 JupyterLab
把数据存到练习文件夹
- 在自己的工作区新建一个名为
GeneSplicePractice的文件夹。 - 打开 UCI 的 CSV 链接,把文件保存到
GeneSplicePractice。如果浏览器直接显示一屏逗号分隔的文本,按Ctrl + S,将文件名存为data.csv。回到文件资源管理器,打开 查看 → 显示 → 文件扩展名 ,确认完整文件名是data.csv。下载 data.csv

创建 Gene 环境
本文环境以conda为例,在 Windows 开始菜单打开 Anaconda Prompt 或 Miniconda Prompt。
创建 Gene 环境
bat
conda create -n Gene python=3.12 -y
conda activate Gene
安装必要的工具包
bat
conda install -c conda-forge --override-channels jupyterlab pandas numpy scikit-learn matplotlib ipywidgets -y
安装完成后,在同一个文件夹,右键后选择在终端中打开,进入终端,再启动 JupyterLab。看到浏览器里的 JupyterLab 页面后,保持终端窗口打开。

bat
conda activate Gene
jupyter lab
进入后,点 Python 3 (ipykernel)。

如果弹出 Select Kernel 窗口,就选 Python 3 (ipykernel) 并点 Select 。在左侧文件列表右键单击刚出现的 Untitled.ipynb,选 Rename ,改名为 DNA剪接位点练习.ipynb。

接下来每遇到一个 python 代码块,就复制到一个新的代码单元格,按 Shift + Enter 运行并进入下一格。
第 1 格 确认环境和文件位置
python
import sys
from pathlib import Path
import ipywidgets as widgets
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn
from IPython.display import Markdown, display
from matplotlib.colors import ListedColormap
from matplotlib.ticker import PercentFormatter
%matplotlib inline
print("Python 版本", sys.version.split()[0])
print("Python 路径", sys.executable)
print("当前文件夹", Path.cwd())
print("找到 data.csv", Path("data.csv").is_file())
看到什么。 版本应是 3.12.x,Python 路径应指向 envs\Gene\python.exe,最后一行应显示 True。这说明当前笔记本正用 Gene 运行,而且相对路径 data.csv 能找到文件。

2. 从 CSV 里取出一条 DNA
第 2 格 看看表格的样子
python
data = pd.read_csv("data.csv", keep_default_na=False)
base_columns = [f"Base{position}" for position in range(1, 61)]
label_order = ["EI", "IE", "N"]
print("行数和列数", data.shape)
display(data[["class", "instancename", *base_columns[:6]]].head(3))
看到什么。 输出是 (3190, 62)。表格只预览前 3 行和前 6 个碱基位置。每一行是一条序列,class 是已知答案,instancename 是样本名,Base1 到 Base60 各放一个位置的碱基。这里先把 CSV 当成一张表来读。

第 3 格 把第一行拼成一条序列
python
samples = data[["class", "instancename"]].rename(
columns={"class": "label", "instancename": "sample_id"}
)
samples["sequence"] = data[base_columns].agg("".join, axis=1)
first = samples.iloc[0]
first_sequence = first["sequence"]
print("样本名", first["sample_id"])
print("碱基数", len(first_sequence))
print("中心位置", first_sequence[:30], "|", first_sequence[30:])
print("已知答案", first["label"])
看到什么。 第一条是 ATRINS-DONOR-521,长度 60,标签 EI。[:30] 取前 30 个字符,[30:] 取后半段。竖线是我们打印时加上的,标记第 30 和 31 位之间。
text
CCAGCTGCATCACAGGAGGCCAGCGAGCAG | GTCTGTTCCAAGGGCCTTCGAGCCAGTCTG

RNA 剪接会移去内含子,并把保留的外显子连起来。这份数据里的 E 表示外显子,I 表示内含子。我们看的是这两类片段在 DNA 序列中心的关系。
| 标签 | 第 30 和 31 位之间是什么位置 |
|---|---|
EI |
从外显子进入内含子,称为剪接供体位点 |
IE |
从内含子进入外显子,称为剪接受体位点 |
N |
两种剪接边界以外的位置 |
样本名中的 DONOR 已经提示了供体位点。训练时我们只把 sequence 里的碱基交给模型,用 label 提供答案。样本名用来查找记录。
第 4 格 把三类样本的中心画出来
python
base_colors = {
"A": "#f8d49d",
"C": "#b9d9f3",
"G": "#bfe6d1",
"T": "#d9cdf4",
"?": "#e0e5eb",
}
def draw_center(ax, sequence):
"""画出第 25 到 36 位,保留原来的碱基字母。"""
for position, base in enumerate(sequence[24:36], start=25):
ax.bar(position, 1, width=0.94, color=base_colors.get(base, base_colors["?"]))
ax.text(position, 0.5, base, ha="center", va="center", color="#16263a")
ax.axvline(30.5, color="#16263a", linewidth=2)
ax.set(xlim=(24.5, 36.5), ylim=(0, 1), xticks=range(25, 37), yticks=[])
fig, axes = plt.subplots(3, 1, figsize=(8, 2.9), sharex=True, layout="constrained")
for ax, label in zip(axes, label_order):
example = samples.loc[samples["label"] == label].iloc[0]
draw_center(ax, example["sequence"])
ax.set_ylabel(label, rotation=0, labelpad=18, va="center")
axes[-1].set_xlabel("Position")
plt.show()
怎么看图。 每行取自对应类别的第一条样本。横轴 Position 是原序列的位置,黑线左边到第 30 位,右边从第 31 位开始。先用眼睛比较黑线两侧的字母,再读左边的标签。每行只画出 12 位,完整的 60 位仍保存在 sequence 中。

第 5 格 看看三类各有多少条
python
label_counts = samples["label"].value_counts().reindex(label_order)
fig, ax = plt.subplots(figsize=(5.2, 3), layout="constrained")
bars = ax.bar(label_counts.index, label_counts.values, color="#4c78a8")
ax.bar_label(bars, padding=3, fmt="%d")
ax.set(ylabel="Samples", ylim=(0, label_counts.max() * 1.17))
plt.show()
怎么看。 EI 有 767 条,IE 有 768 条,N 有 1,655 条。这是原始表格的计数。N 的柱最高,所以在这批数据里,即使一直猜 N,也会猜对许多条。最后会把这个猜法和模型放在同一批测试数据上比较。
3. 把 DNA 变成模型能用的数字
第 6 格 亲手看一次独热编码
我们给每个位置画五个格子,列顺序固定为 A C G T ?。读到 A 就在 A 那格填 1,其余格子填 0。只亮起一个格子,所以叫独热编码 。CSV 的序列中还有少量 D、N、R、S,这些符号表示碱基有多种可能。本练习统一把它们记到 ? 那一列。出现在序列位置里的 N 表示碱基不确定,出现在 label 栏里的 N 表示中心位置属于其他类。
python
base_channels = list("ACGT?")
base_vectors = dict(zip(base_channels, np.eye(len(base_channels), dtype=np.uint8)))
def encode_sequence(sequence):
"""把每个字母换成对应的五个数字。"""
return np.array([base_vectors.get(base, base_vectors["?"]) for base in sequence])
short_sequence = "ACN"
display(pd.DataFrame(
encode_sequence(short_sequence), columns=base_channels, index=list(short_sequence)
).rename_axis("原字符"))
first_encoded = encode_sequence(first_sequence)
print("一条 DNA 的编码形状", first_encoded.shape)
print("铺平成一行后的形状", first_encoded.reshape(1, -1).shape)
怎么看表。 ACN 对应三行。第一行的 A 列是 1,第二行的 C 列是 1,第三行的 ? 列是 1。第一条真实 DNA 有 60 个位置,得到 (60, 5),再按顺序把这 60 行接起来,就得到 (1, 300)。这里的 reshape(1, -1) 表示整理成一行,由 NumPy 算出这一行需要多少列。

第 7 格 用热图看编码里保留了什么
python
center_encoded = first_encoded[24:36]
fig, ax = plt.subplots(figsize=(5, 5), layout="constrained")
ax.imshow(
center_encoded,
cmap=ListedColormap(["#f5f7fb", "#8bc1e7"]),
vmin=0,
vmax=1,
aspect="auto",
)
for row_index, row in enumerate(center_encoded):
for col_index, value in enumerate(row):
ax.text(col_index, row_index, str(value), ha="center", va="center", color="#16263a")
ax.axhline(5.5, color="#16263a", linewidth=2)
ax.set_xticks(range(5), base_channels)
ax.set_yticks(range(12), range(25, 37))
ax.set(xlabel="Encoding column", ylabel="Position")
plt.show()
怎么看图。 找到左侧的 31,横着看这一行,1 落在 G 列。
一个碱基从字母变成了数字,位置仍然能找回来。铺平后,第 31 位对应的五个数字也固定在同一段。
4. 留出测试序列,再训练模型
第 8 格 去掉重复序列并划分数据
如果一模一样的 DNA 同时出现在训练集和测试集里,测试时模型可能已经做过那道题。划分前,先把同标签的重复序列合并成一条。同一条 DNA 如果有不同标签,就把这条序列的所有记录移出本次练习。然后按类别比例留出约 20% 做测试。random_state=42 固定这次随机划分,方便跟教程对照。
python
from sklearn.model_selection import train_test_split
labels_per_sequence = samples.groupby("sequence")["label"].transform("nunique")
consistent_samples = samples.loc[labels_per_sequence == 1]
unique_samples = consistent_samples.drop_duplicates(subset="sequence")
train, test = train_test_split(
unique_samples,
test_size=0.2,
random_state=42,
stratify=unique_samples["label"],
)
train = train.reset_index(drop=True)
test = test.reset_index(drop=True)
print("原始样本数", len(samples))
print("去重和处理冲突后", len(unique_samples))
print("训练集", len(train), "测试集", len(test))
print("两组完全相同的 DNA 条数", len(set(train["sequence"]) & set(test["sequence"])))
看到什么。 处理后有 3004 条序列,训练集 2403 条,测试集 601 条,最后一行是 0。
第 9 格 看看每一类怎样分到两组
python
split_counts = pd.DataFrame({
"Train": train["label"].value_counts(),
"Test": test["label"].value_counts(),
}).reindex(label_order)
ax = split_counts.plot.bar(rot=0, figsize=(6.5, 3.5), color=["#4677a4", "#d89a48"])
for bars in ax.containers:
ax.bar_label(bars, padding=3, fmt="%d")
ax.set(xlabel="Class", ylabel="Samples", ylim=(0, split_counts.to_numpy().max() * 1.19))
ax.figure.tight_layout()
plt.show()
怎么看图。 单看 EI,相邻两根柱分别是训练和测试的数量。stratify 让每类大致按同样的比例分给两组。右边的 N 样本总数仍比较多,这与第 5 格看到的分布相符。

第 10 格 训练逻辑回归
逻辑回归在这里是一个分类模型。训练时,它根据已知标签学习每个位置的碱基与类别的关系。预测时,它接收一行编码数字,再给出对 EI、IE、N 的判断。
python
from sklearn.linear_model import LogisticRegression
def to_model_inputs(sequences):
"""每条序列占一行,每行有 300 个数字。"""
encoded = np.stack([encode_sequence(sequence) for sequence in sequences])
return encoded.reshape(len(encoded), -1)
X_train = to_model_inputs(train["sequence"])
X_test = to_model_inputs(test["sequence"])
y_train = train["label"]
y_test = test["label"]
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
probabilities = model.predict_proba(X_test)
print("训练输入", X_train.shape)
print("测试输入", X_test.shape)
print("模型认识的类别", list(model.classes_))
看到什么。 两组形状分别为 (2403, 300) 和 (601, 300)。X 代表模型输入,y 是已知答案。fit 只使用训练集,predict 对测试序列给出判断,predict_proba 给出模型分给三类的概率。测试集的标签留到对答案时再用。
5. 看模型怎样判断一条 DNA
第 11 格 先看编号 0 的测试样本
python
def show_prediction(sample_index):
sample = test.iloc[sample_index]
sequence = sample["sequence"]
guess = predictions[sample_index]
actual = sample["label"]
scores = pd.Series(probabilities[sample_index], index=model.classes_).reindex(label_order)
display(Markdown(
f"**测试编号 {sample_index} 模型预测 {guess} 已知答案 {actual}**\n\n"
f"`{sequence[:30]} | {sequence[30:]}`"
))
fig, (sequence_ax, score_ax) = plt.subplots(
2, 1, figsize=(7, 3.6), height_ratios=[1, 2.5], layout="constrained"
)
draw_center(sequence_ax, sequence)
sequence_ax.set_xlabel("Position")
colors = ["#33658a" if label == guess else "#b9ccdc" for label in label_order]
bars = score_ax.bar(label_order, scores, color=colors)
score_ax.bar_label(bars, labels=[f"{score:.1%}" for score in scores], padding=3)
score_ax.set(ylabel="Model probability", ylim=(0, 1.16), yticks=np.linspace(0, 1, 5))
score_ax.yaxis.set_major_formatter(PercentFormatter(xmax=1))
plt.show()
show_prediction(0)
怎么看图。 顶部是一条完整的 DNA 及其预测和已知答案。中间的条带把中心位置放大,下面三根柱是模型给三个类别的概率。实跑时编号 0 的已知答案和预测都是 N,所以最高柱出现在 N。

第 12 格 拉动滑块换一条样本
python
sample_slider = widgets.IntSlider(
value=0,
min=0,
max=len(test) - 1,
step=1,
description="测试编号",
continuous_update=False,
)
prediction_panel = widgets.interactive(show_prediction, sample_index=sample_slider)
display(prediction_panel)
怎么看图。 滑块一开始显示 0。点选滑块后可用右方向键换到 1,也可以拖动后松开鼠标。下面的 DNA、预测和已知答案会一起更新。编号从 0 到 600。实跑时切到 1,预测和已知答案都变成 EI。也可以在第 11 格把最后一行换成 show_prediction(1),重新运行那一格。
6. 读懂模型在整批测试集上的表现
第 13 格 对比准确率和混淆矩阵
我们用两种方法做同一批题。一种是刚训练的逻辑回归。另一种叫多数类对照,它只记住训练集里最常见的标签,每道题都猜这个标签。准确率就是猜对的条数除以测试总条数。
python
from sklearn.dummy import DummyClassifier
from sklearn.metrics import ConfusionMatrixDisplay, accuracy_score
baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(X_train, y_train)
baseline_accuracy = accuracy_score(y_test, baseline.predict(X_test))
model_accuracy = accuracy_score(y_test, predictions)
print("多数类对照", f"{baseline_accuracy:.1%}")
print("逻辑回归", f"{model_accuracy:.1%}")
fig, (accuracy_ax, matrix_ax) = plt.subplots(1, 2, figsize=(9.2, 3.7), layout="constrained")
bars = accuracy_ax.bar(
["Majority class", "Logistic regression"],
[baseline_accuracy, model_accuracy],
color=["#a6b9cb", "#33658a"],
)
accuracy_ax.bar_label(bars, labels=[f"{baseline_accuracy:.1%}", f"{model_accuracy:.1%}"], padding=3)
accuracy_ax.set(ylabel="Accuracy", ylim=(0, 1.16), yticks=np.linspace(0, 1, 5))
accuracy_ax.yaxis.set_major_formatter(PercentFormatter(xmax=1))
ConfusionMatrixDisplay.from_predictions(
y_test,
predictions,
labels=label_order,
cmap="Blues",
colorbar=False,
values_format="d",
ax=matrix_ax,
)
matrix_ax.set(xlabel="Predicted label", ylabel="True label")
plt.show()
怎么看图。 用官方 CSV 和 Gene 的 Python 3.12 实跑,左图的多数类对照为 55.1%,逻辑回归为 96.2%。右图的行是真实标签,列是模型预测 。沿着 EI 那行从左向右读,第一格是 131,表示 131 条真实 EI 被正确识别。第三格的 2 表示 2 条真实 EI 被猜成 N。沿着对角线相加,得到猜对的 578 条,再除以测试集的 601 条,就得到逻辑回归的准确率。

动手试一次。 拖动第 12 格的滑块,找一条预测和答案不同的序列。记下真实类别和预测类别,再回到右图,找到它对应的那一格。