上课代码
import torch标签:__,torch,nn,self,DataLoader,Dataset,PyTorch,data,def From: https://blog.51cto.com/u_15698454/5963005
import numpy as np
from torch.utils.data import Dataset #Data是一个抽先类
from torch.utils.data import DataLoader
class DiabetesDataset(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 = DiabetesDataset('diabetes.csv.gz') #实例化
train_loader = DataLoader(dataset = dataset,batch_size = 32,shuffle = True,num_workers = 2)
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.sigmoid = torch.nn.Sigmoid() #改变激活函数
def forward(self,x):
x = self.sigmoid(self.linear1(x)) #加入逻辑变换
x = self.sigmoid(self.linear2(x))
x = self.sigmoid(self.linear3(x))
return x #全程只用一个x
model = Model() #模型实例化
criterion = torch.nn.BCELoss(size_average = False) #将原来MSE变为BCE
optimizer = torch.optim.SGD(model.parameters(),lr = 0.01) #优化器
if __name__ == '__main__':
for epoch in range(100):
for i,data in enumerate(train_loader,0):
#prepare data
inputs,labels = data
#forward
y_pred =model(inputs)
loss = criterion(y_pred,labels)
print(epoch,i,loss.item())
#backward
optimizer.zero_grad()
loss.backward()
#update
optimizer.step()