import torch
import matplotlib.pyplot as plt
import numpy as np
xy = np.loadtxt('diabetes.csv',delimiter=',',dtype=np.float32)
x_data = torch.from_numpy(xy[:,:-1])
#print(x_data)
y_data =torch.from_numpy(xy[:,[-1]])
#print(y_data)
epoch_list = []
loss_list = []
class Model(torch.nn.Module):
def __init__(self):
super(Model,self).__init__()
# self,linear = torch.nn.Linear(8,1)#输入8维特征维,输出1维特征维
self.linear1 = torch.nn.Linear(8,6)
self.linear2 = torch.nn.Linear(6,4)
self.linear3 = torch.nn.Linear(4,1)
self.sigmod = torch.nn.Sigmoid()
self.activate = torch.nn.ReLU()
def forward(self,x):
x = self.activate(self.linear1(x))
x = self.activate(self.linear2(x))
x = self.sigmod(self.linear3(x))
return x
model = Model()
criterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(),lr=0.05)
for epoch in range(10000):
y_pred = model(x_data)
loss = criterion(y_pred,y_data)
print(f'epoch = {epoch} loss = {loss.data:.2f}')
optimizer.zero_grad()
loss.backward()
optimizer.step()
epoch_list.append(epoch)
loss_list.append(loss.item())
x_test = torch.tensor([[-0.294118,0.487437,0.180328,-0.292929,0,0.00149028,-0.53117,-0.0333333]])
print(x_test)
y_test =model(x_test)
print(y_test.item())
x_test2 =torch.tensor([[-0.176471,0.959799,0.147541,-0.333333,-0.65721,-0.251863,-0.927412,0.133333]])
print(model(x_test2).item())
plt.plot(epoch_list,loss_list)
plt.xlabel('Epoch')
plt.ylabel('loss')
plt.show()
import torch
import numpy as np
from torch.utils.data import Dataset,DataLoader
import matplotlib.pyplot as plt
class Datasets(Dataset):
def __init__(self,filepath):
xy = np.loadtxt(filepath,delimiter=',',dtype=np.float32)
self.len = xy.shape[0]
self.x_data = torch.from_numpy(xy[:,:-1])
self.y_data = torch.from_numpy(xy[:,[-1]])
def __getitem__(self, index):
return self.x_data[index],self.y_data[index]
def __len__(self):
return self.len
dataset = Datasets('diabetes.csv')
train_loader = DataLoader(dataset=dataset,batch_size=32,shuffle=True ,num_workers=3)
class Model(torch.nn.Module):
def __init__(self):
super(Model,self).__init__()
self.linear1 = torch.nn.Linear(8,6)
self.linear2 = torch.nn.Linear (6,4)
self.linear3 = torch.nn.Linear(4,1)
self.sigmod = torch.nn.Sigmoid()
self.relu = torch.nn.ReLU()
def forward(self,x):
x = self.sigmod(self.linear1(x))
x = self.sigmod(self.linear2(x))
x = self.sigmod(self.linear3(x))
return x
model = Model()
criterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)
epoch_list =[]
loss_list = []
num=0
if __name__ =='__main__':
for epoch in range(100):
for i ,data in enumerate(train_loader,0):
#print(data)
inputs,labels = data
y_pred = model(inputs)
loss = criterion(y_pred,labels)
print(epoch,i,loss.item())
loss_list.append(loss.item())
#print(loss_list)
optimizer.zero_grad()
loss.backward()
optimizer.step()
epoch_list.append(num)
num = num + 1
plt.plot(epoch_list,loss_list)
plt.xlabel('epoch')
plt.ylabel('loss')
plt.show()
|