一.引入模块,读取数据集
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import math
from torch.autograd import Variable
#读取数据
data = pd.read_csv('diabetes.csv',delimiter=',',dtype=np.float32)
print(data.head())
data = np.array(data)
x = data[:,0:-1]
y = data[:,-1].reshape(-1,1)

x = torch.Tensor(torch.from_numpy(x))
y = torch.Tensor(torch.from_numpy(y))
#查看数据维度
print(x.data.shape)
print(y.data.shape)

二.搭建神经网络
#构建模型
class Model(nn.Module):
def __init__(self):
super(Model,self).__init__()
#定义多层神经网络
self.fc1 = torch.nn.Linear(8,6)
self.fc2 = torch.nn.Linear(6,4)
self.fc3 = torch.nn.Linear(4,1)
def forward(self,x):
x = F.relu(self.fc1(x)) #第一层
x = F.dropout(x,p=0.5)
x = F.relu(self.fc2(x)) #第二层
x = F.dropout(x,p=0.5)
y_pred = torch.sigmoid(self.fc3(x))
return y_pred
def weight_init(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
m.weight.data = torch.randn(m.weight.data.size()[0],m.weight.data.size()[1])
m.bias.data = torch.randn(m.bias.data.size()[0])
model = Model()
model.apply(weight_init)
#定义损失函数和优化器
criterion = torch.nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)
Loss = []
for epoch in range(200):
y_pred = model(x)
loss = criterion(y_pred,y)
if epoch % 50 == 0:
print('epoch=',epoch,'loss=',loss.item())
#梯度清零
optimizer.zero_grad()
#反向传播
loss.backward()
#更新梯度
optimizer.step()
for i in range(len(y_pred)):
if(y_pred[i]>0.5):
y_pred[i] = 1.0
else:
y_pred[i] = 0.0
type(y_pred)

三.预测准确率
#求准确率
(y_pred == y).sum().item()/len(y)
