利用BP神经网络实现糖尿病患者分类具体实现python以及解析
时间: 2023-07-17 09:02:19 浏览: 122
下面是使用BP神经网络实现糖尿病患者分类的Python代码示例:
```python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import torch
import torch.nn as nn
import torch.optim as optim
# 读取数据
data = pd.read_csv('diabetes.csv')
# 划分特征和标签
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
# 数据归一化
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 转换为张量
X_train = torch.Tensor(X_train)
X_test = torch.Tensor(X_test)
y_train = torch.Tensor(y_train)
y_test = torch.Tensor(y_test)
# 定义模型
class DiabetesClassifier(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(DiabetesClassifier, self).__init__()
self.layer1 = nn.Linear(input_dim, hidden_dim)
self.layer2 = nn.Linear(hidden_dim, output_dim)
self.relu = nn.ReLU()
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.relu(self.layer1(x))
x = self.sigmoid(self.layer2(x))
return x
input_dim = X_train.shape[1]
hidden_dim = 8
output_dim = 1
model = DiabetesClassifier(input_dim, hidden_dim, output_dim)
# 定义损失函数和优化器
criterion = nn.BCELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 训练模型
num_epochs = 1000
for epoch in range(num_epochs):
# 前向传播
output = model(X_train)
loss = criterion(output, y_train.view(-1, 1))
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 测试模型
with torch.no_grad():
predicted = model(X_test)
predicted = predicted.round()
accuracy = (predicted == y_test.view(-1, 1)).sum().item() / len(y_test)
print('Test Accuracy: {:.2f}%'.format(accuracy * 100))
```
上述代码假设数据存储在名为"diabetes.csv"的CSV文件中,文件中的最后一列是标签列。代码首先导入必要的库,然后读取数据并进行归一化处理。接下来,将数据划分为训练集和测试集,并将其转换为PyTorch张量。然后,定义一个BP神经网络模型,并指定输入维度、隐藏层维度和输出维度。定义损失函数和优化器后,使用训练集进行模型训练。最后,使用测试集评估模型的准确率。
请注意,以上代码仅为示例,实际应用中可能需要根据具体情况进行调整和优化。
阅读全文