import torch
import numpy as np
import matplotlib.pyplot as plt
xy = np.loadtxt("diabetes.csv.gz", dtype=np.float32, delimiter=",")
x = torch.from_numpy(xy[:, :-1])
y = torch.from_numpy(xy[:, [-1]]) # 这里[-1]是为了返回nx1的矩阵,如果只是一个-1的话,是没有维度的
class MyModel(torch.nn.Module):
def __init__(self):
super(MyModel, 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()#这里Sigmoid也是继承自Module的模块,只是其没有参数。其也是一个callable的东西
def forward(self,x):
x=self.Sigmoid(self.linear1(x))
x=self.Sigmoid(self.linear3(x))
x=self.Sigmoid(self.linear3(x))
return x #这里最好都只使用这一个变量x。便于调试
# return self.Sigmoid(self.linear2(self.Sigmoid(self.linear1(x))))
model=MyModel()
criterion=torch.nn.BCELoss()
optimizer=torch.optim.SGD(model.parameters(),lr=0.1)
for epoch in range(1100):
y_pred=model(x)
loss=criterion(y_pred,y)
print("Epoch{}, loss={}".format(epoch, loss.item()))
optimizer.zero_grad()
loss.backward()
optimizer.step()
07.Mutipule
最新推荐文章于 2022-06-03 10:21:06 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)