Logistic回归简介及python代码实现
来源:互联网 发布:网络小贷 编辑:程序博客网 时间:2024/05/16 19:48
1、Sigmoid 函数:
设
2、二项 Logistic 回归模型:
二项分布 Logistic 回归模型是满足如下的条件概率分布:
我们可以写为如下的形式:
这里,
3、损失函数
似然函数是:
对似然函数取对数:
对对数似然求极大值:
=
=
=
=
取损失函数
使用随机梯度下降算法:这里和线性回归的形式有些不同。线性回归中,似然函数取最大值时,损失函数(均方误差)需要取最小值才满足要求,使用随机梯度下降法。而在 Logistic 回归中,损失函数是似然函数的相反数,使用随机梯度上升法,更新公式中是加号。
参数优化公式:
#-*- coding:utf-8 -*-from numpy import *import numpy as npimport pandas as pdimport matplotlib as mplimport matplotlib.pyplot as pltfrom math import *def calSigmod(theta,inX): return 1.0/(1+exp(-1*(theta*inX)))if __name__=="__main__": print "hello world" data = pd.read_csv("testSet.txt",delimiter='\t',header=None) m, n = shape(data) # data 的数据类型是:pandas.core.frame.DataFrame,按data[j] 是按列输出; data[i][j] 按照元素输出 print m,n x = mat(ones((n,m))) # x 是 m 行 n 列的矩阵,按行输出为 x[j], 按列输出为 x[:,j],按照单个元素输出为 x[i,j] x[1] = data[0] x[2] = data[1] y = data[[2]] y = mat(y) theta = mat(zeros((1,n))) a = 0.001 # 步长,学习率 # 使用随机梯度下降优化参数 for i in range(1000): for j in range(m): hx = calSigmod(theta,x[:,j]) - y[j] theta = theta - a*hx*x[:,j].T # theta[0,0] = theta[0,0] + a*hx*x[0,j] # theta[0,1] = theta[0,1] + a*hx*x[1,j] # theta[0,2] = theta[0,2] + a*hx*x[2,j] print theta # 根据求到的参数theta,计算分界面 x1 = arange(-5,5,0.1) x2 = (-1*theta[0,0] - theta[0,1]*x1)/theta[0,2] # 根据标签,对样本点做标记,便于观察 x1_record = []; y1_record =[] x2_record = []; y2_record =[] for i in range(m): if y[i]==1: x1_record.append(x[1,i]) y1_record.append(x[2,i]) else: x2_record.append(x[1,i]) y2_record.append(x[2,i]) # 画图 mpl.rcParams['font.sans-serif'] = [u'simHei'] mpl.rcParams['axes.unicode_minus'] = False # 在图中加入汉字需要 fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(x1_record,y1_record,s=20,c='red') ax.scatter(x2_record,y2_record,s=30,c='green') ax.plot(x1,x2,'b-') plt.xlabel(u'特征1',fontsize=15) plt.ylabel(u'特征2',fontsize=15) plt.show()
一个事件的几率(odds): 指该事件发生的概率(P)和该事件不发生的概率(1-P)的比值。即:
事件的对数几率(log odds)或者logit 是:
对 Logistic 回归,
也就是说,在 Logistic回归模型中,输出
对图2,
当
当
参考:
《统计学习方法》 李航
《机器学习实战》
- Logistic回归简介及python代码实现
- 线性回归简介及python代码实现
- SoftMax回归简介及python代码实现
- 【Logistic回归】原理及Python代码示例
- logistic回归算法原理及python实现
- Logistic回归python代码
- Logistic回归 Python实现
- Logistic回归简介和相关的PYTHON实现
- 逻辑回归(Logistic Regression)简介及C++实现
- Logistic Regression 逻辑回归算法例子,python代码实现
- logistic回归算法详细分析与Python代码实现注释
- c++实现logistic回归代码
- Logistic回归模型的Python及C++实现
- logistic回归与python实现
- Python实现Logistic 回归实例
- logistic回归和Python实现
- Logistic回归(Python实现)
- Logistic回归模型(C++代码实现)
- 排序算法之选择和插入排序的简单优化
- <基础原理进阶>机器学习算法python实现【3】--文本分析之朴素贝叶斯分类器
- 玄学的浮点型的整数型输出
- Elasticsearch常用插件集合
- 第三章遇到的问题&搜到的解释2
- Logistic回归简介及python代码实现
- opencv 矩阵运算(与python的numpy库略有差异)
- Elasticsearch 5.0下Java API使用指南
- MATLAB图像取点操作
- GROMACS运行参数之em_real.mdp文件详解
- Java数据结构详解(七)-TreeSet
- 2015-2016 Northwestern European Regional Contest (NWERC 2015) E
- 【笔记】2、初学python3网络爬虫——爬虫的基本原理
- 如何绑定阿里云域名