机器学习——6.模型训练案例: 预测儿童神经缺陷分类TD/ADHD

案例目的

有一份EXCEL标注数据,如下,训练出合适的模型来预测儿童神经缺陷分类。

参考文章:机器学习------5.案例: 乳腺癌预测-CSDN博客

代码逻辑步骤

  1. 读取数据
  2. 训练集与测试集拆分
  3. 数据标准化
  4. 数据转化为Pytorch张量
  5. label维度转换
  6. 定义模型
  7. 定义损失计算函数
  8. 定义优化器
  9. 定义梯度下降函数
  10. 模型训练(正向传播、计算损失、反向传播、梯度清空)
  11. 模型测试
  12. 精度计算

代码实现

python 复制代码
import numpy as np
import pandas as pd
import torch
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler


df = pd.read_excel('/Users/guojun/Desktop/Learning/machine_learning/Preprocess_Without_WDE_Channels_Data.xlsx')

X = df[df.columns[0:8]].values
mapping = {"TD":0,"ADHD":1}
Y = df["Class"].replace(mapping)

# 数据集拆分
X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state=5)
Y_train = Y_train.to_numpy()
Y_test = Y_test.to_numpy()

# 数据标准化
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.fit_transform(X_test)


# 转化为张量
X_train = torch.from_numpy(X_train.astype(np.float32))
X_test = torch.from_numpy(X_test.astype(np.float32))
Y_train = torch.from_numpy(Y_train.astype(np.float32))
Y_test = torch.from_numpy(Y_test.astype(np.float32))

# 真值转为为二维数据
Y_train = Y_train.view(Y_train.shape[0],-1)
Y_test = Y_test.view(Y_test.shape[0],-1)

# 定义模型
class Model(torch.nn.Module):
    def __init__(self,n_input_features):
        super(Model,self).__init__()
        self.linear = torch.nn.Linear(n_input_features,1)
        
    def forward(self,x):
        return torch.sigmoid(self.linear(x))

model = Model(X_train.shape[1])
# 定义损失函数
loss = torch.nn.BCELoss()
# 定义优化器
learning_rate = 0.001
optimizer = torch.optim.Adam(model.parameters(),lr=learning_rate)

# 梯度下降函数
def gradient_descent():
    # 预测Y值
    pre_y = model(X_train)
    # 计算损失
    l = loss(pre_y,Y_train)
    # 反向传播
    l.backward()
    # 梯度更新
    optimizer.step()
    # 梯度清空
    optimizer.zero_grad()
    return l,list(model.parameters())

# 模型训练
for i in range(10000):
    l,p = gradient_descent()
    print(l,p)

# 模型测试
mapping = {0:"TD",1:"ADHD"}
index = np.random.randint(0,X_test.shape[0])
pre_y = model(X_test[index])
pre_y = mapping[int(pre_y.round().item())]
gt_y = mapping[int(Y_test[index].item())]
print(pre_y,gt_y)


# 计算模型准确率
pres_y = model(X_test).round()
result = np.where(pres_y==Y_test,1,0)
ac = np.sum(result)/result.size
print(ac)

即使调整参数后,损失在0.68左右就不会再下降了。

最终的准确率只有54%-60%,我会在后面的笔记中使用深度神经网络来重新训练,提升模型精度。

相关推荐
金融小师妹6 分钟前
多因子量化模型预警:美元强势因子压制金价失守4000关口,ADP数据能否重构黄金趋势?
人工智能·深度学习·1024程序员节
BJ_Bonree11 分钟前
圆桌论坛精华实录 | AI是重构运维逻辑的颠覆性革命?博睿数据与行业大咖亲授“AI+可观测性”的破局之道
运维·人工智能·重构
终端域名13 分钟前
从 Grok 4 多智能体协同到 RAG 范式革命:2025 年 AI 工作流的技术重构生成
人工智能·重构
Dfreedom.19 分钟前
卷积神经网络(CNN)全面解析
人工智能·神经网络·cnn·卷积神经网络
zl_vslam1 小时前
SLAM中的非线性优-3D图优化之轴角在Opencv-PNP中的应用(一)
前端·人工智能·算法·计算机视觉·slam se2 非线性优化
koo3641 小时前
李宏毅机器学习笔记43
人工智能·笔记·机器学习
lzjava20241 小时前
Spring AI使用知识库增强对话功能
人工智能·python·spring
B站_计算机毕业设计之家2 小时前
深度血虚:Django水果检测识别系统 CNN卷积神经网络算法 python语言 计算机 大数据✅
python·深度学习·计算机视觉·信息可视化·分类·cnn·django
Francek Chen2 小时前
【自然语言处理】预训练05:全局向量的词嵌入(GloVe)
人工智能·pytorch·深度学习·自然语言处理·glove
这张生成的图像能检测吗2 小时前
(论文速读)LyT-Net:基于YUV变压器的轻量级微光图像增强网络
图像处理·人工智能·计算机视觉·低照度