1. 算法思想
逻辑回归算法(Logistic Regression,LR)是一种二分类算法,决策函数由条件概率分布P(Y|X)表示。其将线性回归的运算结果通过Sigmoid函数进行非线性映射到[0,1]区间的值,即以概率的形式表示预测类别。所以,当线性函数运算的结果越大,则P越接近1;当线性运行的结果越小,则P越接近0。
当然,可将LR算法推广至多分类,一般称为多项逻辑回归或者softmax多分类。
2. 公式推导
1. 线性运算
2.非线性映射
3.似然函数
4.对数似然函数
5.损失函数
6.基于梯度下降法求解w
具体公式可参考此篇博客:https://blog.csdn.net/weixin_/article/details/
基于梯度下降算法获得训练权重W,然后利用决策函数进行类别的概率预测:

3. 多分类
方式一:(1 – vs – rest结构)
1. 建立当前类与其他类的分类参数,需学习获得K个分类参数;
2. 利用这K个分类参数分别预测测试样本,最终获得K个预测概率,则属于哪类的预测概率最大,则此样本属于哪类;
方式二:(Softmax函数)
加入指示函数,修改二项逻辑回归的损失函数为Softmax函数的损失函数,基于梯度下降算法训练获得权重参数W;
具体公式参考博客:https://blog.csdn.net/u0/article/details/
4. 代码实现
1. 代码实验使用数据集为鸢尾花数据集
2. 首先使用自编的LR进行测试;然后使用sklearn库中的LogisticRegression进行对比;
3. 代码实现的是二分类
# -*-coding:utf-8 -*- import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression def load_Iris_set(set_path): with open(set_path,'r',encoding='utf-8') as txt: lines = [line.strip().split('\t') for line in txt.readlines()] lines = [line[0].split(',') for line in lines] X = [] Y = [] for line in lines: data = line[:-1] label = line[-1] if label=="Iris-setosa": X.append([float(x) for x in data]) Y.extend([0]) elif label=="Iris-versicolor": X.append([float(x) for x in data]) Y.extend([1]) # else: # Y.extend([3]) return np.array(X),np.array(Y) class LR(): def __init__(self,alpha,epoch): self.alpha = alpha self.epoch = epoch self.w = None def sigmoid(self,x): return 1/(1+np.exp(-x)) def fit(self,X,Y): # n个样本,m个特征 n,m = X.shape # 权重初始化 # np.random.seed(1) self.w = np.random.normal(size=(m,1)) # 迭代训练 for i in range(self.epoch): # 计算预测概率 hw = self.sigmoid(np.dot(X,self.w)) # 计算错误率 err = Y[:,np.newaxis]-hw # 更新梯度 self.w = self.w + self.alpha*np.dot(X.T,err) return self def predict(self,X): P0 = self.sigmoid(np.squeeze(np.dot(X,self.w))).tolist() pred = [1 if i>0.5 else 0 for i in P0] return np.array(pred) def score(self,X,Y): pred = self.predict(X) count = 0 for i,j in zip(pred.tolist(),Y.tolist()): if i==j: count += 1 return count/pred.shape[0] if __name__=='__main__': set_path = "Iris.txt" X,Y = load_Iris_set(set_path) X_train, X_test, y_train, y_test = train_test_split(X,Y,test_size=0.2) # 自编LR # 给定学习率和迭代次数 # lr = LR(0.1,9) # lr.fit(X_train,y_train) # print("训练准确率: ",lr.score(X_train,y_train)) # print("测试准确率: ",lr.score(X_test,y_test)) # sklearn库中的LR LR = LogisticRegression() LR.fit(X_train,y_train) print("训练准确率: ", LR.score(X_train, y_train)) print("测试准确率: ", LR.score(X_test, y_test))
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/204787.html原文链接:https://javaforall.net
