赞
踩
逻辑回归(Logistic Regression)是一种用于二元分类问题的机器学习算法。逻辑回归的目的是基于输入特征预测一个样本属于某个特定的类别的概率。
逻辑回归的核心思想是将线性回归的结果经过一个逻辑函数(Logistic Function)转化为一个在0和1之间的概率值,从而进行分类。逻辑函数通常采用Sigmoid函数,它的输入是线性回归的结果,输出值在0到1之间。当输出值大于0.5时,我们将样本预测为正类,否则预测为负类。
在逻辑回归中,我们使用最大似然估计(Maximum Likelihood Estimation)来求解模型参数。具体地,我们需要最大化对数似然函数,以获得最优的模型参数。我们可以使用梯度下降等优化算法来最大化对数似然函数。
逻辑回归具有简单、快速、易于实现等优点,因此在许多实际问题中得到了广泛应用,例如医学诊断、金融风险评估、自然语言处理等。
metrics.py
import numpy as np from math import sqrt # 分类准确度 def accuracy_score(y_true, y_predict): """计算y_true(y_test)和y_predict之间的准确率""" assert y_true.shape[0] == y_predict.shape[0], \ "the size of y_true must be equal to the size of y_predict" return np.sum(y_true == y_predict) / len(y_true) # 下面三个是对线性回归模型大的评测指标 def mean_squared_error(y_true, y_predict): """计算y_true和y_predict之间的mse""" assert len(y_true) == len(y_predict), \ "the size of y_true must be equal to the size of y_predict" return np.sum((y_true - y_predict) ** 2) / len(y_true) def root_mean_squared_error(y_true, y_predict): """计算y_true和y_predict之间的RMSE""" return sqrt(mean_squared_error(y_true, y_predict)) def mean_absolute_error(y_true, y_predict): """计算y_true和y_predict之间的RMSE""" assert len(y_true) == len(y_predict), \ "the size of y_true must be equal to the size of y_predict" return np.sum(np.absolute(y_true - y_predict)) / len(y_true) def r2_score(y_true, y_predict): """计算y_true和y_predict之间的R Square""" return 1 - mean_squared_error(y_true, y_predict) / np.var(y_true) # 评价分类的指标 def TN(y_true, y_predict): assert len(y_true) == len(y_predict) return np.sum((y_true == 0) & (y_predict == 0)) def FP(y_true, y_predict): assert len(y_true) == len(y_predict) return np.sum((y_true == 0) & (y_predict == 1)) def FN(y_true, y_predict): assert len(y_true) == len(y_predict) return np.sum((y_true == 1) & (y_predict == 0)) def TP(y_true, y_predict): assert len(y_true) == len(y_predict) return np.sum((y_true == 1) & (y_predict == 1)) def confusion_matrix(y_true, y_predict): return np.array([ [TN(y_true, y_predict), FP(y_true, y_predict)], [FN(y_true, y_predict), TP(y_true, y_predict)] ]) def precision_score(y_true, y_predict): tp = TP(y_true, y_predict) fp = FP(y_true, y_predict) try: return tp / (tp + fp) except: return 0.0 def recall_score(y_true, y_predict): tp = TP(y_true, y_predict) fn = FN(y_true, y_predict) try: return tp / (tp + fn) except: return 0.0 def f1_score(y_true, y_predict): precision = precision_score(y_true, y_predict) recall = recall_score(y_true, y_predict) try: return 2 * precision * recall / (precision + recall) except: return 0.0 def TPR(y_true, y_predict): tp = TP(y_true, y_predict) fn = FN(y_true, y_predict) try: return tp / (tp + fn) except: return 0.0 def FPR(y_true, y_predict): fp = FP(y_true, y_predict) tn = TN(y_true, y_predict) try: return fp / (fp + tn) except: return 0.0
上面的代码是一些评估机器学习模型表现的函数,包括回归模型和分类模型的指标。下面是每个函数的具体功能描述:
accuracy_score(y_true, y_predict):计算分类模型的准确率。
mean_squared_error(y_true, y_predict):计算回归模型的均方误差。
root_mean_squared_error(y_true, y_predict):计算回归模型的均方根误差。
mean_absolute_error(y_true, y_predict):计算回归模型的平均绝对误差。
r2_score(y_true,y_predict):计算回归模型的R²分数。
TN(y_true, y_predict):计算二分类模型中真负类数。
FP(y_true,y_predict):计算二分类模型中假正类数。
FN(y_true, y_predict):计算二分类模型中假负类数。
TP(y_true, y_predict):计算二分类模型中真正类数。
confusion_matrix(y_true,y_predict):计算二分类模型中的混淆矩阵。
precision_score(y_true,y_predict):计算二分类模型中的精确率。
recall_score(y_true, y_predict):计算二分类模型中的召回率。
f1_score(y_true, y_predict):计算二分类模型中的F1分数。
TPR(y_true,y_predict):计算二分类模型中的真正类率。
FPR(y_true, y_predict):计算二分类模型中的假正类率。
LogisticRegression.py
import numpy as np from .metrics import accuracy_score # 逻辑回归是处理分类任务的,使用分类准确度衡量模型 # 逻辑回归模型 class LogisticRegression: def __init__(self): """初始化Logistic Regression模型""" self.coef_ = None # 系数 self.interception_ = None # 截距 self._theta = None # 自定义sigmoid函数,为私有方法 def _sigmoid(self, t): return 1. / (1. + np.exp(-t)) # 使用批量梯度下降法 def fit(self, X_train, y_train, eta=0.01, n_iters=1e4): """根据训练数据集X_train, y_train,使用梯度下降法训练Logistic Regression模型""" assert X_train.shape[0] == y_train.shape[0], \ "the size of X_train must be equal to the size of y_train" def J(theta, X_b, y): """求出对应theta的损失函数""" y_hat = self._sigmoid(X_b.dot(theta)) try: return -np.sum(y*np.log(y_hat) + (1-y)*np.log(1-y_hat)) / len(y) except: return float('inf') def dJ(theta, X_b, y): """求出损失函数的对应theta梯度""" # 使用下面向量化运算求梯度 return X_b.T.dot(self._sigmoid(X_b.dot(theta)) - y) / len(y) def gradient_descent(X_b, y, initial_theta, eta, n_iters=1e4, epsilon=1e-8): """使用梯度下降算法训练模型""" theta = initial_theta cur_iter = 0 while cur_iter < n_iters: gradient = dJ(theta, X_b, y) last_theta = theta theta = theta - eta * gradient if abs(J(theta, X_b, y) - J(last_theta, X_b, y)) < epsilon: break cur_iter += 1 return theta X_b = np.hstack([np.ones((len(X_train), 1)), X_train]) initial_theta = np.zeros(X_b.shape[1]) self._theta = gradient_descent(X_b, y_train, initial_theta, eta, n_iters) self.interception_ = self._theta[0] self.coef_ = self._theta[1:] return self def predict_proba(self, X_predict): """给定待预测数据集X_predict,返回表示X_predict结果的概率向量""" assert self.coef_ is not None and self.interception_ is not None, \ "must fit before predict!" assert X_predict.shape[1] == len(self.coef_), \ "the feature number of X_predict must be equal to X_train" X_b = np.hstack([np.ones((X_predict.shape[0], 1)), X_predict]) return self._sigmoid(X_b.dot(self._theta)) def predict(self, X_predict): """给定待预测数据集X_predict,返回表示X_predict""" assert self.coef_ is not None and self.interception_ is not None, \ "must fit before predict!" assert X_predict.shape[1] == len(self.coef_), \ "the feature number of X_predict must be equal to X_train" proba = self.predict_proba(X_predict) return np.array(proba >= 0.5, dtype='int') def score(self, X_test, y_test): """根据测试数据集X_test和y_test确定当前模型的准确度""" y_predict = self.predict(X_test) return accuracy_score(y_test, y_predict) def __repr__(self): return "LogisticRegression()"
这段代码实现了逻辑回归模型,包含了模型训练和预测等基本功能。具体来说,实现了以下方法:
- 初始化模型;
- 自定义sigmoid函数;
- 使用批量梯度下降法训练模型;
- 给定待预测数据集X_predict,返回表示X_predict结果的概率向量;
- 给定待预测数据集X_predict,返回表示X_predict的预测结果;
- 根据测试数据集X_test和y_test确定当前模型的准确度;
*输出模型的字符串表示。
Time:2023.3.27
如果上面代码对您有帮助,欢迎点个赞!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。