思路:
1、准备数据
2、模型构造
3、损失和优化器
4、循环训练
5、投入模型数据,计算结果
课上示例
示例程序源代码+注释(根据个人理解)
import torch
import torch.nn.functional as F # 函数包
import numpy as np
import matplotlib.pyplot as plt
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0], [0], [1]]) # 分类数据
class LogisticRegressionModel(torch.nn.Module):
def __init__(self): # 构造函数与线性模型一样,无其他参数
super(LogisticRegressionModel, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
y_pred = F.sigmoid(self.linear(x)) # F.sigmoid()
return y_pred
model = LogisticRegressionModel()
criterion = torch.nn.BCELoss(size_average=False) # 用BCE损失函数:cross-entropy(交叉熵),不需要求均值
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, loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
x = np.linspace(0, 10, 200)
x_t = torch.Tensor(x).view((200, 1)) # .view() 转换成矩阵
y_t = model(x_t) # 将张量送到训练好的模型中,计算结果
y = y_t.data.numpy()
plt.plot(x, y)
plt.plot([0, 10], [0.5, 0.5], c='r') # 画出y=0.5时的分界线
plt.xlabel('Hours')
plt.ylabel('Probability of Pass')
plt.grid() # x和y轴的网格线
plt.show()
输出结果:
结论:
可以看到大约在2.5小时左右分为两类:
1、小于2.5小时时,结果为0,意为不通过;
2、大于2.5小时时,结果为1,意为通过考试。