使用 Python 编写 DNN 神经网络根据基因表达量预测患者是否患病

本项目使用 Python 编写 DNN 神经网络,根据基因表达量预测患者是否患病。使用贝叶斯优化对模型进行优化,并加入注意力机制。代码包含详细注释,使用 PyTorch 框架,绘制了准确率、损失和 ROC 图。

1. 准备工作

由于本项目需要使用贝叶斯优化对神经网络模型进行优化,需要先安装相应的包:'bayesian-optimization'

pip install bayesian-optimization

2. 数据读取

  1. 读入 Excel 表格,第一行为患者状态标志 'state'(1 为患病,0 为正常)和 16 个基因名称,第 0 列为患者是否患病的真值,其余列为基因的表达量。 路径为 'C:\Users\lenovo\Desktop\HIV\DNN神经网络测试\data1.xlsx'
import pandas as pd

data = pd.read_excel('C:\Users\lenovo\Desktop\HIV\DNN神经网络测试\data1.xlsx', header=0)
X = data.iloc[:, 1:].values  # 取第 1 列到最后一列
y = data.iloc[:, 0].values  # 取第 0 列

3. 使用贝叶斯优化对神经网络模型进行优化

from bayes_opt import BayesianOptimization

# 定义搜索空间
pbounds = {'input_dim': (16, 128), 'hidden_dim': (32, 512), 'hidden_layers': (1, 5),
           'dropout': (0, 0.5), 'lr': (0.0001, 0.01)}

# 定义待优化的函数,即神经网络的训练函数
def train_nn(input_dim, hidden_dim, hidden_layers, dropout, lr):
    # 导入需要的库
    import torch
    import torch.nn as nn
    import torch.optim as optim
    import numpy as np
    from sklearn.metrics import accuracy_score, roc_curve, auc

    # 定义神经网络模型
    class Net(nn.Module):
        def __init__(self, input_dim, hidden_dim, hidden_layers, dropout):
            super(Net, self).__init__()
            self.fc1 = nn.Linear(input_dim, hidden_dim)
            self.relu = nn.ReLU()
            self.dropout = nn.Dropout(dropout)
            self.hidden_layers = hidden_layers
            if hidden_layers >= 2:
                self.fc_hidden = nn.ModuleList([nn.Linear(hidden_dim, hidden_dim) for i in range(hidden_layers-1)])
            self.fc_out = nn.Linear(hidden_dim, 1)
            self.sigmoid = nn.Sigmoid()

        def forward(self, x):
            x = self.fc1(x)
            x = self.relu(x)
            x = self.dropout(x)
            for i in range(self.hidden_layers-1):
                x = self.fc_hidden[i](x)
                x = self.relu(x)
                x = self.dropout(x)
            x = self.fc_out(x)
            x = self.sigmoid(x)
            return x

    # 定义训练函数
    def train_model(model, X_train, y_train, lr):
        criterion = nn.BCELoss()
        optimizer = optim.Adam(model.parameters(), lr=lr)
        epochs = 100
        for epoch in range(epochs):
            model.train()
            optimizer.zero_grad()
            outputs = model(X_train)
            loss = criterion(outputs, y_train)
            loss.backward()
            optimizer.step()
        return model

    # 划分数据集
    from sklearn.model_selection import train_test_split
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

    # 将数据集转换为张量形式
    X_train = torch.tensor(X_train).float()
    y_train = torch.tensor(y_train).float().unsqueeze(1)
    X_test = torch.tensor(X_test).float()
    y_test = torch.tensor(y_test).float().unsqueeze(1)

    # 定义神经网络模型
    model = Net(input_dim, hidden_dim, hidden_layers, dropout)

    # 训练神经网络模型
    model = train_model(model, X_train, y_train, lr)

    # 预测概率并计算准确率和AUC值
    model.eval()
    y_pred = model(X_test).detach().numpy().flatten()
    y_pred_label = np.round(y_pred)
    acc = accuracy_score(y_test, y_pred_label)
    fpr, tpr, thresholds = roc_curve(y_test, y_pred)
    auc_value = auc(fpr, tpr)

    return auc_value

# 初始化贝叶斯优化对象
boptimizer = BayesianOptimization(f=train_nn, pbounds=pbounds, random_state=1)

# 进行贝叶斯优化
boptimizer.maximize(init_points=5, n_iter=10)

# 获取最优参数
best_params = boptimizer.max['params']

4. 模型定义与训练

  1. 模型为二分类,有三个隐藏层;加入注意力机制。
  2. 数据划分:数据全部作为训练集,没有测试集。即全部把数据拿去训练。
  3. 将每次训练的准确率和损失值两者进行输出。
# 定义神经网络模型
class Net(nn.Module):
    def __init__(self, input_dim, hidden_dim, hidden_layers, dropout):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.relu = nn.ReLU()
        self.dropout = nn.Dropout(dropout)
        self.hidden_layers = hidden_layers
        self.attention = nn.Linear(hidden_dim, 1)
        if hidden_layers >= 2:
            self.fc_hidden = nn.ModuleList([nn.Linear(hidden_dim, hidden_dim) for i in range(hidden_layers-1)])
        self.fc_out = nn.Linear(hidden_dim, 1)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        x = self.fc1(x)
        x = self.relu(x)
        x = self.dropout(x)
        for i in range(self.hidden_layers-1):
            x = self.fc_hidden[i](x)
            x = self.relu(x)
            x = self.dropout(x)
        attention = self.attention(x)
        attention = torch.softmax(attention, dim=0)
        x = x * attention
        x = self.fc_out(x)
        x = self.sigmoid(x)
        return x

# 定义训练函数
def train_model(model, X_train, y_train, lr):
    criterion = nn.BCELoss()
    optimizer = optim.Adam(model.parameters(), lr=lr)
    epochs = 100
    loss_list = []
    auc_list = []
    for epoch in range(epochs):
        model.train()
        optimizer.zero_grad()
        outputs = model(X_train)
        loss = criterion(outputs, y_train)
        loss.backward()
        optimizer.step()
        y_pred = model(X_train).detach().numpy().flatten()
        auc = roc_auc_score(y_train, y_pred)
        loss_list.append(loss.item())
        auc_list.append(auc)
        if epoch % 10 == 0:
            print('Epoch: {}, Loss: {:.4f}, AUC: {:.4f}'.format(epoch, loss.item(), auc))
    return model, loss_list, auc_list

# 划分数据集
X_train = torch.tensor(X).float()
y_train = torch.tensor(y).float().unsqueeze(1)

# 定义神经网络模型
model = Net(16, 256, 3, 0.2)

# 训练神经网络模型
model, loss_list, auc_list = train_model(model, X_train, y_train, 0.001)

5. 结果可视化

  1. 绘制最优参数的准确率变化的图。
  2. 绘制最优参数的损失变化的图。
  3. 绘制最优参数的模型的 ROC 图。
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc

# 绘制 AUC 曲线
plt.plot(auc_list)
plt.title('AUC Curve')
plt.xlabel('Epochs')
plt.ylabel('AUC')
plt.show()

# 绘制 Loss 曲线
plt.plot(loss_list)
plt.title('Loss Curve')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.show()

# 绘制 ROC 图
y_pred = model(X_train).detach().numpy().flatten()
fpr, tpr, thresholds = roc_curve(y_train, y_pred)
roc_auc = auc(fpr, tpr)

plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = {:.2f})'.format(roc_auc))
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc='lower right')
plt.show()

6. 总结

本项目使用 Python 编写 DNN 神经网络,根据基因表达量预测患者是否患病。使用贝叶斯优化对模型进行优化,并加入注意力机制。代码包含详细注释,使用 PyTorch 框架,绘制了准确率、损失和 ROC 图。

该项目是一个简单的示例,展示了如何使用 DNN 神经网络进行疾病预测。实际应用中,需要根据具体情况进行调整,例如使用更多的数据、更复杂的模型、更先进的优化算法等。

使用 Python 编写 DNN 神经网络根据基因表达量预测患者是否患病

原文地址: https://www.cveoy.top/t/topic/ndf3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录