全部代码在最后面。
X与Y表示:
x * w (多维情况下)转变为:
多个样本,尽量不用循坏(吴恩达),转为矩阵,便于计算
修改模型里面的参数:
多层:层数越多,非线性能力增强,但是学习能力不能太好,学到噪声,以至于过拟合,需要把握好泛化能力与过拟合的平衡点。
模型里面都用x,而不是用o1,o2,y_pred(惯例)
不同的激活函数:
code:
'''处理多维特征的输入'''
import numpy as np
import torch
xy = np.loadtxt('diabetes.csv', delimiter=',', dtype=np.float32)
x_data = torch.from_numpy(xy[:,:-1]) # 取所有行,加所有列(除了最后一列:y)
y_data = torch.from_numpy(xy[:,[-1]]) # 取所有行,加最后一列,为什么要用[-1]:因为要取出的格式为矩阵,而不是向量
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.activate = torch.nn.ReLU()
self.sigmoid = torch.nn.Sigmoid()
def forward(self, x):
x = self.activate(self.linear1(x))
x = self.activate(self.linear2(x))
x = self.sigmoid(self.linear3(x))
return x
model = Model()
criterion = torch.nn.BCELoss(size_average=True)
optimizer = torch.optim.SGD(model.parameters(), lr = 0.1)
for epoch in range(100):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
效果: