import torch
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.l1 = nn.Linear(8, 6)
self.l2 = nn.Linear(6, 4)
self.l3 = nn.Linear(4, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
''':arg x 数据输入变量
在前向函数中,我们接受输入数据的变量,我们必须返回
输出数据的变量。 我们可以使用构造函数中定义的模块作为
以及变量上的任意运算符。
'''
out1 = self.sigmoid(self.l1(x))
out2 = self.sigmoid(self.l2(out1))
y_pred = self.sigmoid(self.l3(out2))
return y_pred
def run(self):
model = Model()
criterion = nn.BCELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
for epoch in range(100):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
criterion.zero_grad()
loss.backward()
optimizer.step()
if __name__ == "__main__":
print("Life is short, You need Python!")
xy = np.loadtxt('.//data/diabetes.csv.gz', delimiter=',', dtype=np.float32)
x_data = Variable(torch.from_numpy(xy[:, 0:-1]))
y_data = Variable(torch.from_numpy(xy[:, [-1]]))
print(x_data.data.shape)
print(y_data.data.shape)
来源:CSDN
作者:_Zephyrus_
链接:https://blog.csdn.net/wangxw1803/article/details/104607417