当前位置:   article > 正文

机器学习——5.模型训练案例: 乳腺癌预测_机器学习 肿瘤预测数据

机器学习 肿瘤预测数据

案例目的

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

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

代码逻辑步骤

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

代码实现

  1. import torch
  2. import numpy as np
  3. import pandas as pd
  4. from sklearn.model_selection import train_test_split
  5. from sklearn.preprocessing import StandardScaler
  6. df = pd.read_csv('/Volumes/Sophia/机器学习/day03/code/breast_cancer.csv')
  7. X = df[df.columns[0:-1]].values
  8. Y = df[df.columns[-1]].values
  9. # 数据集拆分
  10. X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state=5)
  11. # 数据标准化
  12. sc = StandardScaler()
  13. X_train = sc.fit_transform(X_train)
  14. X_test = sc.fit_transform(X_test)
  15. # 转化为张量
  16. X_train = torch.from_numpy(X_train.astype(np.float32))
  17. X_test = torch.from_numpy(X_test.astype(np.float32))
  18. Y_train = torch.from_numpy(Y_train.astype(np.float32))
  19. Y_test = torch.from_numpy(Y_test.astype(np.float32))
  20. # 标签转化为二维数据
  21. # print(Y_train.shape)
  22. Y_train = Y_train.view(Y_train.shape[0],-1)
  23. Y_test = Y_test.view(Y_test.shape[0],-1)
  24. # 定义模型
  25. class Model(torch.nn.Module):
  26. def __init__(self,n_input_features):
  27. super(Model,self).__init__()
  28. self.linear = torch.nn.Linear(n_input_features,1)
  29. def forward(self,x):
  30. y = torch.sigmoid(self.linear(x))
  31. return y
  32. n_features = X_train.shape[1]
  33. # 定义损失函数
  34. model = Model(n_features)
  35. loss = torch.nn.BCELoss()
  36. # 定义优化器
  37. # 学习率
  38. learning_rate = 0.001
  39. optimzier = torch.optim.SGD(model.parameters(),lr=learning_rate)
  40. # 定义梯度下降函数
  41. def gradient_descent():
  42. pre_y = model(X_train)
  43. l = loss(pre_y,Y_train)
  44. l.backward()
  45. optimzier.step()
  46. optimzier.zero_grad()
  47. return l,list(model.parameters())
  48. # 模型训练
  49. for i in range(500):
  50. l,pa = gradient_descent()
  51. if i % 50 == 0:
  52. print(l,pa)
  53. # 模型测试
  54. index = np.random.randint(0,X_test.shape[0])
  55. pre = model(X_test[index])
  56. print(pre,Y_test[index])
  57. # 计算模型准确率
  58. pres_y = model(X_test).round()
  59. result = np.where(pres_y==Y_test,1,0)
  60. ac = np.sum(result)/result.size
  61. print(ac)
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/776201
推荐阅读
相关标签
  

闽ICP备14008679号