- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊 | 接辅导、项目定制
一、我的环境
1.语言环境:Python 3.9
2.编译器:Pycharm
3.深度学习环境:TensorFlow 2.10.0
二、GPU设置
import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")if gpus:gpu0 = gpus[0] #如果有多个GPU,仅使用第0个GPUtf.config.experimental.set_memory_growth(gpu0, True) #设置GPU显存用量按需使用tf.config.set_visible_devices([gpu0],"GPU")
三、数据导入
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
import torch.nn as nn
from sklearn.model_selection import train_test_splitimport warningsplt.rcParams['savefig.dpi'] = 100 # 图片像素
plt.rcParams['figure.dpi'] = 100 # 分辨率
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
warnings.filterwarnings("ignore")
# 设置硬件设备,如果有GPU则使用,没有则使用cpu
DataFrame = pd.read_excel('data/dia.xlsx')print(DataFrame.head())
卡号 性别 年龄 高密度脂蛋白胆固醇 低密度脂蛋白胆固醇 ... 尿素氮 尿酸 肌酐 体重检查结果 是否糖尿病
0 18054421 0 38 1.25 2.99 ... 4.99 243.3 50 1 0
1 18054422 0 31 1.15 1.99 ... 4.72 391.0 47 1 0
2 18054423 0 27 1.29 2.21 ... 5.87 325.7 51 1 0
3 18054424 0 33 0.93 2.01 ... 2.40 203.2 40 2 0
4 18054425 0 36 1.17 2.83 ... 4.09 236.8 43 0 0[5 rows x 16 columns]
四、数据检查
# 查看数据是否有缺失值
print('数据缺失值---------------------------------')
print(DataFrame.isnull().sum())
数据缺失值---------------------------------
卡号 0
性别 0
年龄 0
高密度脂蛋白胆固醇 0
低密度脂蛋白胆固醇 0
极低密度脂蛋白胆固醇 0
甘油三酯 0
总胆固醇 0
脉搏 0
舒张压 0
高血压史 0
尿素氮 0
尿酸 0
肌酐 0
体重检查结果 0
是否糖尿病 0
dtype: int64
# 查看数据是否有重复值
print('数据重复值---------------------------------')
print('数据集的重复值为:'f'{DataFrame.duplicated().sum()}')
#数据重复值---------------------------------
#数据集的重复值为:0
五、数据分布分析
feature_map = {'年龄': '年龄','高密度脂蛋白胆固醇': '高密度脂蛋白胆固醇','低密度脂蛋白胆固醇': '低密度脂蛋白胆固醇','极低密度脂蛋白胆固醇': '极低密度脂蛋白胆固醇','甘油三酯': '甘油三酯','总胆固醇': '总胆固醇','脉搏': '脉搏','舒张压': '舒张压','高血压史': '高血压史','尿素氮': '尿素氮','尿酸': '尿酸','肌酐': '肌酐','体重检查结果': '体重检查结果'
}
plt.rcParams.update({'axes.titlesize': 8, # 图标题'axes.labelsize': 8, # 轴标签'xtick.labelsize': 8, # x轴刻度标签'ytick.labelsize': 8, # y轴刻度标签'legend.fontsize': 8, # 图例字体'figure.titlesize': 8 # 图形标题
})
plt.figure(figsize=(15, 10))
for i, (col, col_name) in enumerate(feature_map.items(), 1):plt.subplot(3, 5, i)sns.boxplot(x=DataFrame['是否糖尿病'], y=DataFrame[col])plt.title(f'{col_name}的箱线图', fontsize=8)plt.ylabel('数值', fontsize=8)# plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()
六、LSTM模型
数据集构建
# '高密度脂蛋白胆固醇'字段与糖尿病负相关,故而在 X 中去掉该字段
X = DataFrame.drop(['卡号', '是否糖尿病', '高密度脂蛋白胆固醇'], axis=1)
y = DataFrame['是否糖尿病']
# sc_X = StandardScaler()
# X = sc_X.fit_transform(X)
X = torch.tensor(np.array(X), dtype=torch.float32)
y = torch.tensor(np.array(y), dtype=torch.int64)
train_X, test_X, train_y, test_y = train_test_split(X, y,test_size=0.2,random_state=1)
print(train_X.shape, train_y.shape)
输出
(torch.Size([804,13]),torch.Size([804]))
from torch.utils.data import TensorDataset, DataLoadertrain_dl = DataLoader(TensorDataset(train_X, train_y),batch_size=64,shuffle=False)
test_dl = DataLoader(TensorDataset(test_X, test_y),batch_size=64,shuffle=False)
定义模型
class model_lstm(nn.Module):def __init__(self):super(model_lstm, self).__init__()self.lstm0 = nn.LSTM(input_size=13, hidden_size=200,num_layers=1, batch_first=True)self.lstm1 = nn.LSTM(input_size=200, hidden_size=200,num_layers=1, batch_first=True)self.fc0 = nn.Linear(200, 2)def forward(self, x):out, hidden1 = self.lstm0(x)out, _ = self.lstm1(out, hidden1)out = self.fc0(out)return outmodel = model_lstm().to(device)
print(model)
输出
model_lstm((lstm0): LSTM(13, 200, batch_first=True)(lstm1): LSTM(200, 200, batch_first=True)(fc0): Linear(in_features=200, out_features=2, bias=True)
)
七、训练模型
训练集
# 训练循环
def train(dataloader, model, loss_fn, optimizer):size = len(dataloader.dataset) # 训练集的大小num_batches = len(dataloader) # 批次数目, (size/batch_size,向上取整)train_loss, train_acc = 0, 0 # 初始化训练损失和正确率for X, y in dataloader: # 获取图片及其标签X, y = X.to(device), y.to(device)# 计算预测误差pred = model(X) # 网络输出loss = loss_fn(pred, y) # 计算网络输出和真实值之间的差距,targets为真实值# 反向传播optimizer.zero_grad() # grad属性归零loss.backward() # 反向传播optimizer.step() # 每一步自动更新# 记录acc与losstrain_acc += (pred.argmax(1) == y).type(torch.float).sum().item()train_loss += loss.item()train_acc /= sizetrain_loss /= num_batchesreturn train_acc, train_loss
测试集
def test(dataloader, model, loss_fn):size = len(dataloader.dataset) # 测试集的大小num_batches = len(dataloader) # 批次数目, (size/batch_size,向上取test_loss, test_acc = 0, 0# 当不进行训练时,停止梯度更新,节省计算内存消耗with torch.no_grad():for imgs, target in dataloader:imgs, target = imgs.to(device), target.to(device)# 计算losstarget_pred = model(imgs)loss = loss_fn(target_pred, target)test_loss += loss.item()test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()test_acc /= sizetest_loss /= num_batchesreturn test_acc, test_loss
模型训练
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-4 # 学习率
opt = torch.optim.Adam(model.parameters(), lr=learn_rate)
epochs = 30
train_loss = []
train_acc = []
test_loss = []
test_acc = []
for epoch in range(epochs):model.train()epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, opt)model.eval()epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)train_acc.append(epoch_train_acc)train_loss.append(epoch_train_loss)test_acc.append(epoch_test_acc)test_loss.append(epoch_test_loss)# 获取当前的学习率lr = opt.state_dict()['param_groups'][0]['lr']template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f},Lr:{:.2E}')print(template.format(epoch + 1, epoch_train_acc * 100, epoch_train_loss, epoch_test_acc * 100, epoch_test_loss, lr))print("=" * 20, 'Done', "=" * 20)
#结果
Epoch: 1, Train_acc:49.4%, Train_loss:0.699, Test_acc:57.4%, Test_loss:0.698,Lr:1.00E-04
==================== Done ====================
Epoch: 2, Train_acc:55.6%, Train_loss:0.688, Test_acc:54.5%, Test_loss:0.709,Lr:1.00E-04
==================== Done ====================
Epoch: 3, Train_acc:56.5%, Train_loss:0.683, Test_acc:53.0%, Test_loss:0.712,Lr:1.00E-04
==================== Done ====================
Epoch: 4, Train_acc:56.2%, Train_loss:0.680, Test_acc:53.0%, Test_loss:0.715,Lr:1.00E-04
==================== Done ====================
Epoch: 5, Train_acc:56.2%, Train_loss:0.678, Test_acc:53.0%, Test_loss:0.717,Lr:1.00E-04
==================== Done ====================
Epoch: 6, Train_acc:56.2%, Train_loss:0.675, Test_acc:53.0%, Test_loss:0.716,Lr:1.00E-04
==================== Done ====================
Epoch: 7, Train_acc:56.2%, Train_loss:0.673, Test_acc:53.0%, Test_loss:0.714,Lr:1.00E-04
==================== Done ====================
Epoch: 8, Train_acc:56.3%, Train_loss:0.670, Test_acc:53.0%, Test_loss:0.712,Lr:1.00E-04
==================== Done ====================
Epoch: 9, Train_acc:56.5%, Train_loss:0.666, Test_acc:52.5%, Test_loss:0.710,Lr:1.00E-04
==================== Done ====================
Epoch:10, Train_acc:56.8%, Train_loss:0.662, Test_acc:52.5%, Test_loss:0.707,Lr:1.00E-04
==================== Done ====================
Epoch:11, Train_acc:57.7%, Train_loss:0.656, Test_acc:52.0%, Test_loss:0.703,Lr:1.00E-04
==================== Done ====================
Epoch:12, Train_acc:58.6%, Train_loss:0.650, Test_acc:53.5%, Test_loss:0.699,Lr:1.00E-04
==================== Done ====================
Epoch:13, Train_acc:61.2%, Train_loss:0.643, Test_acc:55.9%, Test_loss:0.695,Lr:1.00E-04
==================== Done ====================
Epoch:14, Train_acc:63.4%, Train_loss:0.635, Test_acc:56.9%, Test_loss:0.689,Lr:1.00E-04
==================== Done ====================
Epoch:15, Train_acc:63.6%, Train_loss:0.626, Test_acc:58.9%, Test_loss:0.683,Lr:1.00E-04
==================== Done ====================
Epoch:16, Train_acc:65.3%, Train_loss:0.616, Test_acc:63.4%, Test_loss:0.676,Lr:1.00E-04
==================== Done ====================
Epoch:17, Train_acc:66.3%, Train_loss:0.605, Test_acc:62.9%, Test_loss:0.668,Lr:1.00E-04
==================== Done ====================
Epoch:18, Train_acc:68.8%, Train_loss:0.593, Test_acc:62.9%, Test_loss:0.662,Lr:1.00E-04
==================== Done ====================
Epoch:19, Train_acc:70.1%, Train_loss:0.583, Test_acc:62.9%, Test_loss:0.654,Lr:1.00E-04
==================== Done ====================
Epoch:20, Train_acc:70.5%, Train_loss:0.572, Test_acc:62.9%, Test_loss:0.649,Lr:1.00E-04
==================== Done ====================
Epoch:21, Train_acc:70.3%, Train_loss:0.562, Test_acc:61.9%, Test_loss:0.646,Lr:1.00E-04
==================== Done ====================
Epoch:22, Train_acc:71.3%, Train_loss:0.552, Test_acc:62.4%, Test_loss:0.644,Lr:1.00E-04
==================== Done ====================
Epoch:23, Train_acc:72.8%, Train_loss:0.543, Test_acc:61.9%, Test_loss:0.644,Lr:1.00E-04
==================== Done ====================
Epoch:24, Train_acc:73.3%, Train_loss:0.530, Test_acc:63.4%, Test_loss:0.640,Lr:1.00E-04
==================== Done ====================
Epoch:25, Train_acc:74.4%, Train_loss:0.522, Test_acc:63.9%, Test_loss:0.636,Lr:1.00E-04
==================== Done ====================
Epoch:26, Train_acc:74.8%, Train_loss:0.512, Test_acc:63.9%, Test_loss:0.635,Lr:1.00E-04
==================== Done ====================
Epoch:27, Train_acc:76.0%, Train_loss:0.501, Test_acc:64.4%, Test_loss:0.631,Lr:1.00E-04
==================== Done ====================
Epoch:28, Train_acc:76.9%, Train_loss:0.492, Test_acc:64.4%, Test_loss:0.629,Lr:1.00E-04
==================== Done ====================
Epoch:29, Train_acc:78.2%, Train_loss:0.484, Test_acc:64.9%, Test_loss:0.634,Lr:1.00E-04
==================== Done ====================
Epoch:30, Train_acc:78.1%, Train_loss:0.472, Test_acc:66.3%, Test_loss:0.634,Lr:1.00E-04
==================== Done ====================
八、总结
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.rcParams['figure.dpi'] = 100 # 分辨率
epochs_range = range(epochs)
plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
九、总结
这周学习LSTM实现糖尿病探索与预测:
LSTM原理:
长短时记忆网络(LSTM)是一种特殊的循环神经网络(RNN),能够学习长序列数据中的依赖关系。LSTM通过引入门控机制解决了传统RNN在处理长序列时梯度消失和梯度爆炸的问题。
LSTM包含三个门:输入门、遗忘门和输出门。输入门决定输入的信息是否被加入到记忆细胞中,遗忘门决定记忆细胞中的过去信息是否被保留,输出门决定最终的输出值。
展示了数据样例、数据加载、模型构建、训练与预测的过程,证明了LSTM模型在糖尿病预测中的有效性。