目录
3.Logistic Fuction,sigmoid(激活)函数
1.实际是处理分类
虽然逻辑斯蒂名字是回归,但其实它做的是分类的问题,例如一些手写数字1,2,3.....的图片将他们识别到1,2,3....的数字类别。
2.torchvision
提供流行的数据集,比如MNIST,The CIFAR-10 dataset,train表示要训练集还是测试集,download,如果需要从网上下载,就设置download为True。
import torchvision
train_set =torchvision.datasets.MNIST(root = '../dataset/mnist',train = True,download= True)
test_set =torchvision.datasets.MNIST(root = '../dataset/mnist',train = False,download= True)
3.Logistic Fuction,sigmoid(激活)函数
4.loss函数
对于线性回归模型:
对于二分类问题:
=P(class = 1) = P(class = 0)
y = 0表示class = 0的概率是1,1-y表示class = 1的概率是0
criterion = torch.nn.BCELoss(size_average = False)#用的交叉熵
5.代码
import torch.nn.functional as F
import torch
x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[0],[0],[1]])
class LogisticRegressionModel(torch.nn.Module):#继承自Module,torch.nn.Module是PyTorch中所有神经网络模型的基类
def __init__(self):#构造函数
super(LogisticRegressionModel,self).__init__()#super函数来调用父类Module的构造函数,第一个参数是目前类的名称,第二个参数是self
self.linear =torch.nn.Linear(1,1)
#定义了一个线性层,该线性层是torch.nn.Linear类的实例,它接受一个输入和一个输出,这里输入和输出都设为1。
# Linear层是神经网络中的一个基本组件,它将输入数据与权重相乘,然后添加一个偏差 bias = True就是需要偏置差,为False就是不需要偏置差
def forward(self,x):
y_pred = F.sigmoid(self.linear(x))
return y_pred
model = LogisticRegressionModel()
#这两部分通常是在训练神经网络模型时必不可少的部分,其中损失函数是用来衡量模型的预测结果与真实结果之间的差距,
# 而优化器则是用来根据这个损失来调整模型的参数,以使得损失最小化。
criterion = torch.nn.BCELoss(size_average=True)#二分类交叉熵损失
#参数size_average设置为False意味着在计算损失时不是对每一个样本的损失进行平均,而是对每一个样本的损失进行求和
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
#创建了一个随机梯度下降(SGD)优化器。这个优化器是用于更新模型的参数。这里,我们传入了模型的参数以及学习率(learning rate)为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()#optimizer的step方法根据计算出的梯度来更新模型参数。
print('w = ',model.linear.weight.item())
print('b = ',model.linear.bias.item())
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ',y_test.item())
6.小练习
import numpy as np import matplotlib.pyplot as plt import torch from test6 import model x = np.linspace(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()
此笔记参考B站刘二大人pytorch学习视频
https://www.bilibili.com/video/BV1Y7411d7Ys?p=6&vd_source=d3c46650a910b1ad85cf3b75557e13df