- 🍨 本文为🔗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个GPU
tf.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_split
import warnings
plt.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()
相关性分析
import plotly.express as px
# 删除列“卡号”
DataFrame.drop(columns=['卡号'], inplace=True)
# 计算各列之间的相关系数
df_corr = DataFrame.corr()
# 相关矩阵生成函数
def corr_generate(df):
fig = px.imshow(df, text_auto=True, aspect="auto", color_continuous_scale='RdBu_r')
fig.show()
corr_generate(df_corr)
六、LSTM模型
数据集构建
from sklearn.preprocessing import StandardScaler
# '高密度脂蛋白胆固醇'字段与糖尿病负相关,故而在 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, DataLoader
train_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 out
model = 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与loss
train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
train_loss += loss.item()
train_acc /= size
train_loss /= num_batches
return 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)
# 计算loss
target_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 /= size
test_loss /= num_batches
return 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:56.2%, Train_loss:0.690, Test_acc:53.0%, Test_loss:0.694,Lr:1.00E-04
==================== Done ====================
Epoch: 2, Train_acc:56.2%, Train_loss:0.685, Test_acc:53.0%, Test_loss:0.694,Lr:1.00E-04
==================== Done ====================
Epoch: 3, Train_acc:56.2%, Train_loss:0.681, Test_acc:53.0%, Test_loss:0.693,Lr:1.00E-04
==================== Done ====================
Epoch: 4, Train_acc:56.2%, Train_loss:0.677, Test_acc:53.0%, Test_loss:0.692,Lr:1.00E-04
==================== Done ====================
Epoch: 5, Train_acc:56.6%, Train_loss:0.673, Test_acc:53.0%, Test_loss:0.690,Lr:1.00E-04
==================== Done ====================
Epoch: 6, Train_acc:57.1%, Train_loss:0.668, Test_acc:54.0%, Test_loss:0.685,Lr:1.00E-04
==================== Done ====================
Epoch: 7, Train_acc:58.1%, Train_loss:0.662, Test_acc:55.4%, Test_loss:0.680,Lr:1.00E-04
==================== Done ====================
Epoch: 8, Train_acc:60.2%, Train_loss:0.655, Test_acc:57.9%, Test_loss:0.672,Lr:1.00E-04
==================== Done ====================
Epoch: 9, Train_acc:62.7%, Train_loss:0.645, Test_acc:62.9%, Test_loss:0.662,Lr:1.00E-04
==================== Done ====================
Epoch:10, Train_acc:65.4%, Train_loss:0.631, Test_acc:62.9%, Test_loss:0.649,Lr:1.00E-04
==================== Done ====================
Epoch:11, Train_acc:69.2%, Train_loss:0.609, Test_acc:65.3%, Test_loss:0.626,Lr:1.00E-04
==================== Done ====================
Epoch:12, Train_acc:72.0%, Train_loss:0.563, Test_acc:70.8%, Test_loss:0.586,Lr:1.00E-04
==================== Done ====================
Epoch:13, Train_acc:73.5%, Train_loss:0.519, Test_acc:71.8%, Test_loss:0.562,Lr:1.00E-04
==================== Done ====================
Epoch:14, Train_acc:74.9%, Train_loss:0.493, Test_acc:72.3%, Test_loss:0.549,Lr:1.00E-04
==================== Done ====================
Epoch:15, Train_acc:75.5%, Train_loss:0.479, Test_acc:72.8%, Test_loss:0.540,Lr:1.00E-04
==================== Done ====================
Epoch:16, Train_acc:76.1%, Train_loss:0.468, Test_acc:72.8%, Test_loss:0.533,Lr:1.00E-04
==================== Done ====================
Epoch:17, Train_acc:76.7%, Train_loss:0.459, Test_acc:72.8%, Test_loss:0.527,Lr:1.00E-04
==================== Done ====================
Epoch:18, Train_acc:76.6%, Train_loss:0.452, Test_acc:72.3%, Test_loss:0.522,Lr:1.00E-04
==================== Done ====================
Epoch:19, Train_acc:77.1%, Train_loss:0.446, Test_acc:72.8%, Test_loss:0.518,Lr:1.00E-04
==================== Done ====================
Epoch:20, Train_acc:77.9%, Train_loss:0.441, Test_acc:72.8%, Test_loss:0.515,Lr:1.00E-04
==================== Done ====================
Epoch:21, Train_acc:78.0%, Train_loss:0.436, Test_acc:72.3%, Test_loss:0.513,Lr:1.00E-04
==================== Done ====================
Epoch:22, Train_acc:78.7%, Train_loss:0.432, Test_acc:72.8%, Test_loss:0.511,Lr:1.00E-04
==================== Done ====================
Epoch:23, Train_acc:79.0%, Train_loss:0.428, Test_acc:73.3%, Test_loss:0.510,Lr:1.00E-04
==================== Done ====================
Epoch:24, Train_acc:79.2%, Train_loss:0.424, Test_acc:73.3%, Test_loss:0.508,Lr:1.00E-04
==================== Done ====================
Epoch:25, Train_acc:79.6%, Train_loss:0.421, Test_acc:73.3%, Test_loss:0.508,Lr:1.00E-04
==================== Done ====================
Epoch:26, Train_acc:80.0%, Train_loss:0.418, Test_acc:72.8%, Test_loss:0.507,Lr:1.00E-04
==================== Done ====================
Epoch:27, Train_acc:79.7%, Train_loss:0.415, Test_acc:72.8%, Test_loss:0.507,Lr:1.00E-04
==================== Done ====================
Epoch:28, Train_acc:79.9%, Train_loss:0.412, Test_acc:73.3%, Test_loss:0.506,Lr:1.00E-04
==================== Done ====================
Epoch:29, Train_acc:79.9%, Train_loss:0.409, Test_acc:72.3%, Test_loss:0.506,Lr:1.00E-04
==================== Done ====================
Epoch:30, Train_acc:79.7%, Train_loss:0.406, Test_acc:71.8%, Test_loss:0.506,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 能够有效地解决传统 RNN 中的梯度消失问题,从而可以学习到序列数据中长距离的依赖关系。这使得它在处理诸如长文本、长时间序列等数据时表现出色,能够捕捉到数据中深层次的语义、趋势和模式。
灵活性与适应性:LSTM 可以应用于多种不同类型的序列数据处理任务,无论是自然语言、时间序列还是语音信号等。它的门控机制使得模型能够根据不同的数据特点和任务需求,灵活地调整细胞状态中的信息保留与更新,具有较强的适应性。
局限
计算复杂度较高:由于 LSTM 的细胞结构和门控机制相对复杂,相比于简单的神经网络模型,其计算复杂度较高。在处理大规模数据或构建深度 LSTM 网络时,训练时间和计算资源的需求可能会成为瓶颈,需要强大的计算硬件支持。
可能存在过拟合:在数据量较小或模型参数过多的情况下,LSTM 模型也可能出现过拟合现象,即模型过于适应训练数据,而对新的数据泛化能力较差。需要采用一些正则化技术,如 L1/L2 正则化、Dropout 等,来缓解过拟合问题。
尝试减少参数,拟合效果会更好,剔除掉相关性较弱的数据。