Logistic Regression 这个名字叫做回归,做的是分类。
线性和logistic的模型:
使用的损失函数:二分类交叉熵
(这个也叫做BCELoss)
logistic要做的事:
代码:
import torch
# import torch.nn.functional as F
# prepare dataset
x_data = torch.Tensor([[1.0], [2.0], [3.0]]) #数据准备
y_data = torch.Tensor([[0], [0], [1]]) #第0类,第1类
# 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_pred = F.sigmoid(self.linear(x))
y_pred = torch.sigmoid(self.linear(x)) #先用linear做一下线性变换,再把sigmoid函数应用到计算出来的结果上面作为最后的输出。线性模型和logistic多了sigmoid这一步
return y_pred
model = LogisticRegressionModel()
# construct loss and optimizer
# 默认情况下,loss会基于element平均,如果size_average=False的话,loss会被累加。
criterion = torch.nn.BCELoss(size_average=False) #损失也用得不一样与线性模型(MSE)相比
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# training cycle forward, backward, update
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()
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.data)
关于上述的代码产生的结果进行可视化:
import numpy as np
import matplotlib. pyplot as plt
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()
练习:(关于BCELoss函数)
import math
import torch
pred = torch.tensor([[-0.2],[0.2],[0.8]])
target = torch.tensor([[0.0],[0.0],[1.0]])
sigmoid = torch.nn.Sigmoid()
pred_s = sigmoid(pred)
print(pred_s)
"""
pred_s 输出tensor([[0.4502],[0.5498],[0.6900]])
0*math.log(0.4502)+1*math.log(1-0.4502)
0*math.log(0.5498)+1*math.log(1-0.5498)
1*math.log(0.6900) + 0*log(1-0.6900)
"""
result = 0
i=0
for label in target:
if label.item() == 0:
result += math.log(1-pred_s[i].item())
else:
result += math.log(pred_s[i].item())
i+=1
result /= 3
print("bce:", -result)
loss = torch.nn.BCELoss()
print('BCELoss:',loss(pred_s,target).item())
处理多维特征的输入
数据集:文末分享。
模型:
损失和优化:(BCE)
代码:
import numpy as np
import torch
import matplotlib.pyplot as plt
# prepare dataset
xy = np.loadtxt('diabetes.csv', delimiter=',', dtype=np.float32) #“delimiter”分隔符
x_data = torch.from_numpy(xy[:, :-1]) # 第一个‘:’是指读取所有行,第二个‘:’是指从第一列开始,最后一列不要
y_data = torch.from_numpy(xy[:, [-1]]) # [-1] 最后得到的是个矩阵
# design model using class
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear1 = torch.nn.Linear(8, 6) # 输入数据x的特征是8维,x有8个特征;输出维度是6
self.linear2 = torch.nn.Linear(6, 4)
self.linear3 = torch.nn.Linear(4, 1) # 三个线性模型
self.sigmoid = torch.nn.Sigmoid() # 将其看作是网络的一层,而不是简单的函数使用。nn.Sigmoid()是一个模块,,继承自Module,没有参数;用它来做计算图
#激活函数可以更改,比如改为“torch.nn.ReLU()”
def forward(self, x):
x = self.sigmoid(self.linear1(x)) #如果前面的激活函数改为了ReLU,这里就需要改为“self.activate(self.linear1(x)) ”
x = self.sigmoid(self.linear2(x))
x = self.sigmoid(self.linear3(x)) # y hat
return x
model = Model()
# construct loss and optimizer
# criterion = torch.nn.BCELoss(size_average = True)
criterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
epoch_list = []
loss_list = []
# training cycle forward, backward, update
for epoch in range(100):
y_pred = model(x_data) #所有的数据加载进来
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
epoch_list.append(epoch)
loss_list.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step() #更新
plt.plot(epoch_list, loss_list)
plt.ylabel('loss')
plt.xlabel('epoch')
plt.show()
ok。
可以使用不同的激活函数去尝试,比如: