逻辑回归
逻辑回归实质上是线性回归,把特征线性求和(一阶)之后再使用Sigmoid函数将结果映射到[0,1]区间,得到分类结果为1的概率大小。具体表达式如下:
h(w,x) =1/(1+exp(-(w*x+b)))
其中x为特征向量,可以表示为[x1,x2,…,xN],的取值范围为[0,1]表示分类结果为1的概率大小。通过公式可以看出,逻辑回归可以理解为单层的全连接网络加上sigmoid激活函数的神经网络结构,具体如下:
代码实现
定义数据
n_data = torch.ones(100, 2) # 数据的基本形态
x0 = torch.normal(2*n_data, 1) # 类型0 x data (tensor), shape=(100, 2)
y0 = torch.zeros(100) # 类型0 y data (tensor), shape=(100, 1)
x1 = torch.normal(-2*n_data, 1) # 类型1 x data (tensor), shape=(100, 1)
y1 = torch.ones(100) # 类型1 y data (tensor), shape=(100, 1)
# 注意 x, y 数据的数据形式是一定要像下面一样 (torch.cat 是在合并数据)
x = torch.cat((x0, x1), 0).type(torch.FloatTensor) # FloatTensor = 32-bit floating
y = torch.cat((y0, y1), 0).type(torch.FloatTensor) # LongTensor = 64-bit integer
定义Logistic回归模型
class LogisticRegression(nn.Module):
def __init__(self):
super(LogisticRegression, self).__init__()
self.lr = nn.Linear(2, 1)
self.sm = nn.Sigmoid()
def forward(self, x):
x = self.lr(x)
x = self.sm(x)
return x
logistic_model = LogisticRegression()
if torch.cuda.is_available():
logistic_model.cuda()
# 定义损失函数和优化器
criterion = nn.BCELoss()
optimizer = torch.optim.SGD(logistic_model.parameters(), lr=1e-3, momentum=0.9)
模型训练
# 开始训练
for epoch in range(10000):
if torch.cuda.is_available():
x_data = Variable(x).cuda()
y_data = Variable(y).cuda()
else:
x_data = Variable(x)
y_data = Variable(y)
out = logistic_model(x_data)
loss = criterion(out, y_data)
print_loss = loss.data.item()
mask = out.ge(0.5).float() # 以0.5为阈值进行分类
correct = (mask == y_data).sum() # 计算正确预测的样本个数
acc = correct.item() / x_data.size(0) # 计算精度
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 每隔20轮打印一下当前的误差和精度
if (epoch + 1) % 20 == 0:
print('*'*10)
print('epoch {}'.format(epoch+1)) # 训练轮数
print('loss is {:.4f}'.format(print_loss)) # 误差
print('acc is {:.4f}'.format(acc)) # 精度
参考:
[1]: https://blog.csdn.net/out_of_memory_error/article/details/81275651
[2]: https://cloud.tencent.com/developer/news/91332