pytorch使用逻辑回归进行二分类并打印出模型参数

数据格式如下,第一列为标签,分别有0和1两个值;第2到4行分别为输入x的特征,也就是x有三个特征。
在这里插入图片描述

代码如下:

import torch # torch 是一种科学计算框架
import torch.nn as nn # torch.nn 神经网络的接口
import numpy as np # numpy 科学计算的软件包


data = np.loadtxt("train.txt")
n, l = data.shape
for j in range(1,l):
    meanVal = np.mean(data[:,j])
    stdVal = np.std(data[:,j])
    data[:,j] = (data[:,j]-meanVal) / stdVal

np.random.shuffle(data)

train_num = int(n*0.9)
train_data = data[:train_num, 1: ] #训练数据
train_lab = data[:train_num, 0 ] #训练标签
test_data = data[train_num: , 1: ] #测试数据
test_lab = data[train_num: , 0] #测试标签

class LR(nn.Module):
    def __init__(self):  #构造函数
        super(LR, self).__init__()
        self.fc = nn.Linear(3,2)

    #定义前向传播函数
    def forward(self,x):
        out = self.fc(x)
        out = torch.sigmoid(out)
        return out

def test(pred,lab):
    t = pred.max(-1)[1] == lab
    return torch.mean(t.float())

net = LR()
criterion = nn.CrossEntropyLoss()
optm = torch.optim.Adam(net.parameters())
epochs = 1000

for i in range(epochs):
    net.train()
    x = torch.from_numpy(train_data).float()
    y = torch.from_numpy(train_lab).long()
    y_hat = net(x)
    loss = criterion(y_hat,y)
    optm.zero_grad()
    loss.backward()
    optm.step()
    if (i + 1) % 200 == 0:
        #指定模型为测试模式
        net.eval()
        test_in = torch.from_numpy(test_data).float()
        test_l = torch.from_numpy(test_lab).float()
        test_out = net(test_in)
        # 使用我们的测试函数计算准确率
        accu = test(test_out, test_l)
        print("Epoch:{},Loss:{:.4f},Accuracy:{:.2f}".format(i+1,loss.item(),accu))

params = list(net.fc.named_parameters())
print(params.__len__())
print(params[0])
print(params[1])

结果如下:

ssh://root@192.168.206.100:60060/usr/bin/python3.6 -u /home/zhuhualong/pycharm_proj/zhuyuan_logistic/zhuyuan_logistic_1.py
Epoch:200,Loss:0.6909,Accuracy:0.50
Epoch:400,Loss:0.6571,Accuracy:0.72
Epoch:600,Loss:0.6337,Accuracy:0.71
Epoch:800,Loss:0.6189,Accuracy:0.71
Epoch:1000,Loss:0.6091,Accuracy:0.71
2
('weight', Parameter containing:
tensor([[-0.2694,  0.0243, -1.0125],
        [ 0.3076,  0.3333,  0.3903]], requires_grad=True))
('bias', Parameter containing:
tensor([ 1.0839, -0.4223], requires_grad=True))

Process finished with exit code 0

结果解释如下:
最终1000个epoch准确率为71%,weight中的第一行代表类别为0的权重,第二行代表类别为1的权重;bias中的第一个值与weight第一行对应,第二个值与weight第二行对应。x的三个特征(年龄,去年门诊数,去年住院次数)分别与weight中对应的三个权重相乘后再加上对应的偏置项bia求得最终的和。对于一个输入x,可以分别得到类别为0和类别为1的和,前者一般为负数,后者一般为正数,比较两个数的绝对值大小,最终x属于的类别就是绝对值大的那个对应的类别。
当然,由于我的原始数据集的数据特征并不具备很好的规律性,或者仅仅使用一层fc和sigmoid不足以提取出数据集的规律,所以结果不是很好。

详细的请参考以下博客:
Pytorch实战-logistic 回归二元分类代码详细注释

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值