(六)PyTorch深度学习:Logistic回归(多层多维特征输入)

PyTorch:Logistic回归(多维特征输入)

1、多维特征输入:(多个输入参数Xn,对Y = 0 or 1 的影响)

在这里插入图片描述

2、之前我们用的是单特征输入,模型函数为:

在这里插入图片描述

而面对多维特征输入,模型函数就需要改变:

在这里插入图片描述

式中多维特征 x 与权重 w 相乘是等于一个标量的,所以:

在这里插入图片描述

简化:

在这里插入图片描述

表达式中的符号,实际上表示是Logistic函数在这里插入图片描述

在这里插入图片描述

3、将多维特征输入函数表达式:

因为

在这里插入图片描述

则:

在这里插入图片描述

4、程序表达:

class Model(torch.nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear = torch.nn.Linear(8, 1)
        self.sigmoid = torch.nn.Sigmoid()
        
    def forward(self, x):
        x = self.sigmoid(self.linear(x))
        return x
    
model = Model()

5、多层多参数代码:

import torch
import numpy as np

xy = np.loadtxt('diabetes.csv.gz', delimiter=',', dtype=np.float32)  # np里面的数据集,可打印查看
x_data = torch.from_numpy(xy[ : , : -1])   # 所有行,除最后一列的所有列
y_data = torch.from_numpy(xy[ : , [-1]])   # 最后一列的所有行

class Model(torch.nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear1 = torch.nn.Linear(8, 6)
        self.linear2 = torch.nn.linear(6, 4)
        self.linear3 = torch.nn.linear(4, 1)
        self.sigmoid = torch.nn.Sigmoid()   # Sigmoid 激活函数

    def forward(self, x):
        x = self.sigmoid(self.linear1(x))
        x = self.sigmoid(self.linear2(x))
        x = self.sigmoid(self.linear3(x))
        return x

# 想使用模型,就实例化即可,可以直接调用
model = Model()

# 构建损失函数、优化器
criterion = torch.nn.BCELoss(size_average=False)          # BCE损失
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)   # 参数优化

for epoch in range(100):
    # forward
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    print(epoch, loss.item())

    # backward
    optimizer.zero_grad()
    loss.backward()

    # Update
    optimizer.step()

猜你喜欢

转载自blog.csdn.net/K_AAbb/article/details/125807830