python实现逻辑回归

        这里是用的鸢尾花数据集进行的运算,然后大家可以修改一下路径

首先是得到参数的代码

import numpy as np
import pandas as pd

def sigmod(x: np.ndarray):
    return 1 / (1 + np.exp(-x))


class Net:
    def __init__(self, in_feature: int):
        self.weights = np.random.rand(in_feature)
        self.bias = np.random.rand(1)
        self.alpha = 0.05

    def forward(self, x: np.ndarray) -> np.ndarray:
        return sigmod(x.dot(self.weights) + self.bias)

    def grad_w(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:
        M, N = x.shape
        gw = np.array([sum((self.forward(x[i]) - y[i]) * x[i][j] for i in range(M)) / M for j in range(N)])

        return gw[:, 0]

    def grad_b(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:
        return (self.forward(x) - y).mean()

    def update(self, x: np.ndarray, y: np.ndarray):
        self.weights -= self.alpha * self.grad_w(x, y)
        self.bias -= self.alpha * self.grad_b(x, y)


if __name__ == '__main__':
    net = Net(4)
    epochs = 100
    data = pd.read_excel(r"C:/Users/wxc/PycharmProjects/pythonProject4/机器学习/回归/逻辑回归/train.xlsx")
    x = np.array(data.iloc[:, 1:5])
    y = np.array(data.iloc[:, 6])

    for epoch in range(epochs):
        net.update(x, y)

    weights = net.weights
    bias = net.bias

    print('权重', weights)
    print('偏置', bias)

得到参数之后可以在进行分类,这里我进行的二分类

import numpy as np
import pandas as pd


data = pd.read_excel(r"C:/Users/wxc/PycharmProjects/pythonProject4/机器学习/回归/逻辑回归/test.xlsx")
x = data.iloc[:, 1:5]


weights = [-0.4095052,  -0.70925044,  1.41457683,  0.29889677]
bias = [0.29006966]
z1 = np.dot(x, weights) + bias
sigmoid = 1 / (1 + np.exp(-z1))
for i in sigmoid:
    if i > 0.5:
        y = 1
    else:
        y = 0

    print(y)





就可以输出了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值