loss Funct


代码
import numpy as np
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
#1.Prepare dataset
x_data=torch.Tensor([[1.0],[2.0],[3.0]])
y_data=torch.Tensor([[0],[0],[1]])
#----------------------------------------------------#
#2.Design model using Class
class LogisticRegressionModel(torch.nn.Module):
def __init__(self):
super(LogisticRegressionModel,self).__init__()
self.Linear=torch.nn.Linear(1,1)
def forward(self,x):
y_predict=torch.sigmoid(self.Linear(x))
return y_predict
model=LogisticRegressionModel()
#----------------------------------------------------#
#3.Construct loss and optimizer
creterion=torch.nn.BCELoss(size_average=False)
optimizer=torch.optim.SGD(model.parameters(),lr=0.01)
#----------------------------------------------------#
#4.Training cycle:forward, backward, update
for epoch in range(1000):
y_predict=model(x_data)
loss=creterion(y_predict,y_data)
print(epoch,loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
#----------------------------------------------------#
#test
x=np.linspace(0,10,200)
x_t=torch.Tensor(x).view(200,1)#相当于reshape
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()

该博客通过PyTorch构建了一个简单的逻辑回归模型,用于预测学生是否通过考试。数据集包含三个小时的学习时间,模型训练了1000个周期,并在0到10小时的时间范围内进行了预测。训练过程中使用了二元交叉熵损失函数和随机梯度下降优化器。最终,模型的预测概率被绘制出来,与及格概率线进行对比。
354

被折叠的 条评论
为什么被折叠?



