机器学习——5.案例: 乳腺癌预测

案例目的

通过已标注的数据,训练出模型来预测患者是否有患乳腺癌。

该问题属于二分类问题,所以可以使用Sigmoid激活函数,损失用BCE函数

代码逻辑步骤

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

代码实现

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


df = pd.read_csv('/Volumes/Sophia/机器学习/day03/code/breast_cancer.csv')
X = df[df.columns[0:-1]].values
Y = df[df.columns[-1]].values
# 数据集拆分
X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state=5)

# 数据标准化
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))
# 标签转化为二维数据
# print(Y_train.shape)
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):
        y = torch.sigmoid(self.linear(x))
        return y

n_features = X_train.shape[1]    
# 定义损失函数
model = Model(n_features)
loss = torch.nn.BCELoss()
# 定义优化器
# 学习率
learning_rate = 0.001
optimzier = torch.optim.SGD(model.parameters(),lr=learning_rate)
# 定义梯度下降函数
def gradient_descent():
    pre_y = model(X_train)
    l = loss(pre_y,Y_train)
    l.backward()
    optimzier.step()
    optimzier.zero_grad()
    return l,list(model.parameters())

# 模型训练
for i in range(500):
    l,pa = gradient_descent()
    if i % 50 == 0:
        print(l,pa)

# 模型测试
index = np.random.randint(0,X_test.shape[0])
pre = model(X_test[index])
print(pre,Y_test[index])

# 计算模型准确率
pres_y = model(X_test).round()
result = np.where(pres_y==Y_test,1,0)
ac = np.sum(result)/result.size
print(ac)
相关推荐
ryrhhhh1 分钟前
矩阵跃动自研技术:小陌GEO动态监测算法,30分钟快速适配大模型更新
人工智能·算法·矩阵
const_qiu1 分钟前
P0+P1+P2 分层测试策略方法论
人工智能
guoji77884 分钟前
Gemini 3.1 Pro 评估科学:超越基准测试的硬核能力测评方法论
大数据·人工智能
zzh940774 分钟前
Gemini 3.1 Pro 工程化部署优势解析:架构革新如何成就国内高可用访问
人工智能
AustinCyy7 分钟前
【论文笔记】Guiding Generative Storytelling with Knowledge Graphs
论文阅读·人工智能·知识图谱
柯儿的天空10 分钟前
【OpenClaw 全面解析:从零到精通】第 014 篇:OpenClaw 云端部署实战——阿里云、腾讯云与 Docker 部署全指南
人工智能·阿里云·docker·云计算·aigc·腾讯云·ai写作
AC赳赳老秦11 分钟前
使用OpenClaw tavily-search技能高效撰写工作报告:以人工智能在医疗行业的应用为例
运维·人工智能·python·flask·自动化·deepseek·openclaw
2301_7665586513 分钟前
国产自研AI搜索优化引擎:小陌GEO+龙虾机器人,全域大模型占位实战解析
人工智能·机器人
智算菩萨14 分钟前
【Generative AI For Autonomous Driving】5 生成式AI在自动驾驶中的六大应用场景:从数据合成到智慧交通
论文阅读·人工智能·机器学习·ai·自动驾驶·感知
2501_9431240514 分钟前
7×24小时自动运营:矩阵跃动龙虾机器人,AI流量闭环效率拉满
人工智能·矩阵·机器人