Logistic Regression代码实现
Logistic Regression
步骤
引入库
import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
Prepare dataset
#准备数据将数据分为第0类和第1类
x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[0],[0],[1]])
Design model using Class
#将逻辑回归模型分类,模型继承于Module
class LogisticRegressionModel(torch.nn.Module):
#初始化自身对象
def __init__(self):
#super调用父类初始化器
super(LogisticRegressionModel, self).__init__()
#构造一个线性函数,输入维度为1,输出维度为1
self.linear = torch.nn.Linear(1,1)
#定义前馈过程中的计算
def forward(self, x):
#调用逻辑回归和线性函数
y_pred = F.sigmoid(self.linear(x))
#返回预测值
return y_pred
#实例化模型
model = LogisticRegressionModel()
Construct loss and optimizer
#构造二分类交叉熵求损失,设置降维求和
criterion = torch.nn.BCELoss(reduction='sum')
#优化模块中的SGD优化模型中的所有参数,学习率为0.01
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
Training cycle
#循环1000次
for epoch in range(1000):
#将x代入模型求y的预测值
y_pred = model(x_data)
#将y的预测值和真实值代入损失函数中,求损失值
loss = criterion(y_pred,y_data)
#输出循环次数,和损失值,用item设置损失值为标量
print(epoch,loss.item())
#梯度归零
optimizer.zero_grad()
#损失反向传播
loss.backward()
#step更新权重
optimizer.step()
#在线性空间中以均匀步长生成数字序列(在0-10之间取200个点,包括0和10)
x = np.linspace(0, 10, 200)
#torch.Tensor将x变成张量,view将这个张量变成200行,1列的矩阵
x_t = torch.Tensor(x).view((200, 1))
#将x代入模型求出y
y_t = model(x_t)
#将y里面的数据用numpy提取出来一个数组
y = y_t.data.numpy()
#绘图,设置x,y
plt.plot(x, y)
#设置x轴,y轴的范围,图形颜色
plt.plot([0, 10],[0.5, 0.5], c='r')
#设置横坐标
plt.xlabel('Hours')
#设置纵坐标
plt.ylabel('Probability of Pass')
#显示网格
plt.grid()
#展示图形
plt.show()