B站刘二大人老师的《PyTorch深度学习实践》Lecture_07 重点回顾+代码复现
Lecture_07 处理多维特征的输入 Multiple Dimension Input
一、重点回顾
(一)Multiple Dimension Logistic Regression Model
1. 多维特征的逻辑回归模型
(每个样本有8个特征)
通过并行运算可以提高运算速度
2. 线性层
3. 神经网络
一个例子:
(二)激活函数
二、代码复现
# 读取数据
import torch
import numpy as np
xy = np.loadtxt('diabetes.csv.gz',delimiter=',',dtype=np.float32)
# delimiter分隔符
x_data = torch.from_numpy(xy[:,:-1])
# 不要最后一列
y_data = torch.from_numpy(xy[:,[-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.sigmoid = torch.nn.Sigmoid()
def forward(self,x):
x = self.sigmoid(self.linear1(x))
# O1
x = self.sigmoid(self.linear2(x))
# O2
x = self.sigmoid(self.linear3(x))
# Y_hat
return x
model = Model()
# 构造损失和优化器
criterion = torch.nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)
# 训练
loss_ = []
for epoch in range(100):
y_pred = model(x_data)
# 该项目并没有用mini-batch
loss = criterion(y_pred,y_data)
print(epoch,loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss_.append(loss.item())
# 结果输出
from matplotlib import pyplot as plt
x = np.linspace(0,len(loss_),len(loss_))
plt.plot(x, loss_,linewidth = 1.5)
plt.xlabel("epoch")
plt.ylabel("loss")
plt.show()