深度学习基础6:Logistic Regression.py
·
import torch
import torch.nn.functional as F
x_data = torch.tensor([[1.0], [2.0], [3.0]]) # 输入特征:学习时间(小时)
y_data = torch.tensor([[0.0], [0.0], [1.0]]) # 输出标签:是否通过考试(0=未通过,1=通过)
class LogisticRegressionModel(torch.nn.Module):
def __init__(self):
super().__init__() # (新版)
# super(LogisticRegressionModel, self).__init__() # 必须调用父类初始化(旧版)
self.linear = torch.nn.Linear(1, 1) # 创建线性层:输入1维,输出1维
def forward(self, x):
y_pred = F.sigmoid(self.linear(x)) # 前向传播:y=wx+b,并应用sigmoid函数将输出映射到[0,1]
return y_pred
model = LogisticRegressionModel() # 实例化模型
# criterion = torch.nn.BCELoss(size_average=False) # 二元交叉熵损失(已弃用)
criterion = torch.nn.BCELoss(reduction='sum') # 二元交叉熵损失函数(总和,非平均)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # 优化器:随机梯度下降
for epoch in range(1000):
y_pred = model(x_data) # 前向传播
loss = criterion(y_pred, y_data) # 计算损失
print("epoch:", epoch, "loss:", loss.item())
optimizer.zero_grad() # ☆梯度清零
loss.backward() # 反向传播(自动计算梯度)
optimizer.step() # 参数更新(自动使用梯度更新所有参数)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 200) # 生成0-10小时的200个点
x_t = torch.Tensor(x).view((200, 1))
y_t = model(x_t) # 预测每个时间点的通过概率
y = y_t.data.numpy()
plt.plot(x, y)
plt.plot([0, 10], [0.5, 0.5], c='r')
plt.xlabel('hours')
plt.ylabel('Probability of Pass')
plt.grid()
plt.show()
更多推荐
所有评论(0)