第5讲 处理多维特征的输入 Multiple Dimension Input
pytorch学习视频——B站视频链接:《PyTorch深度学习实践》完结合集_哔哩哔哩_bilibili
以下是视频内容笔记以及小练习源码,笔记纯属个人理解,如有错误欢迎路过的大佬指出 。
1. 多维logistic 回归模型
2. 神经网络的形成
-
多层神经网络 将多个linear加上激活函数后,组合到一个网络中形成如图所示的多层网络: 注:一般来说,中间层数越多,网络对非线性映射的拟合程度越好,学习能力越强,但是学习能力太强可能会将输入的噪声也学习进去,所以网络学习能力太强也不好,学习应该具有泛化能力。 (插播一条心得:学习新知识,提高泛化能力——学会读文档+计算机系统基本架构理解)
3. 代码实现
问题描述:输入x是8个维度(8个feature/特征),输出是0或1。
应用场景描述:x是病人的各项指标,y是病人未来一年病情是否加重,1表示加重,0表示不会。
源码 multiple_dimension_linear.py
import torch
import numpy as np
xy = np.loadtxt('diabetes.csv.gz', delimiter=',', dtype=np.float32)
x_data = torch.from_numpy(xy[:, :-1])
y_data = torch.from_numpy(xy[:, [-1]])
print(x_data.shape)
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.relu(self.linear1(x))
x = self.relu(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()
- 替换其它的激活函数
for example: relu函数,在以下两处修改即可
self.relu = torch.nn.ReLU()
x = self.relu(self.linear1(x))
x = self.relu(self.linear2(x))
x = self.sigmoid(self.linear3(x))
如图所示: 源码 relu.py
import torch
import numpy as np
import matplotlib.pyplot as plt
xy = np.loadtxt('diabetes.csv.gz', delimiter=',', dtype=np.float32)
x_data = torch.from_numpy(xy[:, :-1])
y_data = torch.from_numpy(xy[:, [-1]])
print(x_data.shape)
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()
self.relu = torch.nn.ReLU()
def forward(self, x):
x = self.relu(self.linear1(x))
x = self.relu(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)
loss_list = []
for epoch in range(100):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
loss_list.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
plt.plot(range(100), loss_list)
plt.xlabel('epoch')
plt.ylabel('cost')
plt.show()
- 结果:
都不太收敛
|