-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogistic_regression.py
More file actions
35 lines (27 loc) · 1.11 KB
/
Copy pathlogistic_regression.py
File metadata and controls
35 lines (27 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# -*- coding: utf-8 -*-
# @Date : 2020/5/21
# @Author: Luokun
# @Email : olooook@outlook.com
import numpy as np
class LogisticRegression:
"""
Logistic regression classifier(逻辑斯蒂回归分类器)
"""
def __init__(self, input_dim: int, lr: float):
self.weights = np.random.randn(input_dim + 1) # 随机初始化参数
self.lr = lr # 学习率
def fit(self, X: np.ndarray, Y: np.ndarray):
x_pad = self._pad(X) # 为X填充1作为偏置
pred = self._sigmoid(x_pad @ self.weights) # 计算预测值
grad = x_pad.T @ (pred - Y) / len(pred) # 计算梯度
self.weights -= self.lr * grad # 沿负梯度更新参数
def predict(self, X: np.ndarray):
x_pad = self._pad(X) # 为X填充1作为偏置
pred = self._sigmoid(x_pad @ self.weights) # 计算预测值
return np.where(pred > 0.5, 1, 0) # 将(0, 1)之间分布的概率转化为{0, 1}标签
@staticmethod
def _pad(x):
return np.concatenate([x, np.ones([len(x), 1])], axis=1)
@staticmethod
def _sigmoid(x):
return 1 / (1 + np.exp(-x))