文章目录

  • 1.形式化定义
  • 2.逻辑回归求解
    • 举例说明
  • 3.逻辑回归代码实现
  • 4.逻辑回归的正则化
    • 1)理论部分
    • 2)代码实现
  • 5.逻辑回归实现多分类
    • 1)原理
  • 6.sklearn实现逻辑回归
  • 7.案例:鸢尾花分类
  • 8.案例:手写数字识别

1.形式化定义

解决的是分类问题,类别分别是0和1

2.逻辑回归求解

举例说明

3.逻辑回归代码实现

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import accuracy_score# 定义加载数据的函数
def loaddata():data = np.loadtxt('data2.txt', delimiter=',')# 特征数n = data.shape[1] - 1X = data[:, 0:n]y = data[:, -1].reshape(-1, 1)return X, y# 定义散点图函数
def scatter(X, y):# 分别寻找y==1和y==0时,索引值的位置pos = np.where(y == 1)neg = np.where(y == 0)plt.scatter(X[pos[0], 0], X[pos[0], 1], marker='x')plt.scatter(X[neg[0], 0], X[neg[0], 1], marker='o')plt.xlabel('Exam 1 score')plt.xlabel('Exam 2 score')plt.show()# 实现sigmoid函数
def sigmoid(z):r = 1 / (1 + np.exp(-z))return r# 实现假设函数
def hypothesis(X, theta):z = np.dot(X, theta)return sigmoid(z)# 实现代价函数,先实现损失
def computeCost(X, y, theta):m = X.shape[0]l = -y * np.log(hypothesis(X, theta)) - (1 - y) * np.log(1 - hypothesis(X, theta))return np.sum(l) / m# 梯度下降法求解
def gradientDescent(X, y, theta, iterations, alpha):# 数据量m = X.shape[0]# 在x最前面插入全为1的列# np.vstack():在竖直方向上堆叠# np.hstack表示在水平方向上平铺X = np.hstack((np.ones((m, 1)), X))for i in range(iterations):for j in range(len(theta)):theta[j] = theta[j] - (alpha / m) * np.sum((hypothesis(X, theta) - y) * X[:, j].reshape(-1, 1))if (i % 10000 == 0):# 每迭代10000次,输出一次损失值print('第', i, '次迭代,当前损失为:', computeCost(X, y, theta), 'theta =', theta)return theta# 画决策边界
def plotDescionBoundary(X, y, theta):# 样本点颜色cm_dark = mpl.colors.ListedColormap(['g', 'r'])plt.xlabel('Exam 1 score')plt.ylabel('Exam 2 score')# 根据y的结果自动的在cmap中选择颜色,c参数代表颜色plt.scatter(X[:, 0], X[:, 1], c=np.array(y).squeeze(), cmap=cm_dark, s=30)# 画分类决策面x1 = np.arange(min(X[:, 0]), max(X[:, 0]), 0.1)x2 = -(theta[0] + theta[1] * x1) / theta[2]plt.plot(x1, x2)plt.show()# 定义预测函数
def predict(X):m = X.shape[0]# 在x最前面插入全为1的列X = np.hstack((np.ones((m, 1)), X))# 求解假设函数的值(预测值)h = hypothesis(X, theta)# 根据概率值决定最终的分类,>=0.5为1类,<0.5为0类h[h >= 0.5] = 1h[h < 0.5] = 0return hif __name__ == '__main__':X, y = loaddata()scatter(X, y)# 特征数n = X.shape[1]# theta是列向量,+1是因为求梯度时X前会增加一个全1列theta = np.zeros(n + 1).reshape(n + 1, 1)iterations = 250000alpha = 0.08theta = gradientDescent(X, y, theta, iterations, alpha)print('theta=\n', theta)# 画决策面plotDescionBoundary(X, y, theta)# 预测p = predict(X)print('准确度 =', np.mean(y == p))print('准确度 =', accuracy_score(y, p))
第 0 次迭代,当前损失为: 35.99966432903636 theta = [[ 0.008     ][ 0.9502343 ][-1.74785255]]
第 10000 次迭代,当前损失为: nan theta = [[-59.02504686][  1.14700554][  1.84509124]]
第 20000 次迭代,当前损失为: nan theta = [[-1.05585422e+02][ 4.68578082e-02][ 1.62067270e+00]]
第 30000 次迭代,当前损失为: nan theta = [[-148.80611341][   3.99030508][  -0.81613523]]
第 40000 次迭代,当前损失为: nan theta = [[-180.59920695][   2.5770718 ][   1.10286811]]
第 50000 次迭代,当前损失为: nan theta = [[-198.97684916][   2.14943403][   1.60796969]]
第 60000 次迭代,当前损失为: nan theta = [[-2.09611292e+02][ 3.50516521e+00][ 1.82175507e-01]]
第 70000 次迭代,当前损失为: nan theta = [[-216.42044919][   3.5220893 ][   0.25329443]]
第 80000 次迭代,当前损失为: nan theta = [[-223.27932611][   1.0536881 ][   2.34639088]]
第 90000 次迭代,当前损失为: nan theta = [[-231.07351365][   0.93703815][   2.99771369]]
第 100000 次迭代,当前损失为: nan theta = [[-238.25400395][   2.93014951][   0.90258989]]
第 110000 次迭代,当前损失为: nan theta = [[-245.04435034][   1.93799763][   1.55619345]]
第 120000 次迭代,当前损失为: nan theta = [[-247.34932834][   2.33836033][   1.58126479]]
第 130000 次迭代,当前损失为: nan theta = [[-247.77897791][   1.71475888][   2.42291139]]
第 140000 次迭代,当前损失为: nan theta = [[-248.1731205 ][   1.68472485][   2.28012846]]
第 150000 次迭代,当前损失为: nan theta = [[-247.4555695 ][   1.71254006][   2.41912703]]
第 160000 次迭代,当前损失为: nan theta = [[-247.6602936 ][   1.96919617][   1.83604848]]
第 170000 次迭代,当前损失为: nan theta = [[-247.982795  ][   2.33792003][   1.59153989]]
第 180000 次迭代,当前损失为: nan theta = [[-248.04938621][   1.3140158 ][   2.45261571]]
第 190000 次迭代,当前损失为: nan theta = [[-247.07525744][   0.8776164 ][   3.20085982]]
第 200000 次迭代,当前损失为: nan theta = [[-246.95287181][   1.96807141][   1.84921964]]
第 210000 次迭代,当前损失为: nan theta = [[-247.42955952][   1.68995524][   2.2696988 ]]
第 220000 次迭代,当前损失为: nan theta = [[-247.7493172 ][   2.04258878][   2.16660484]]
第 230000 次迭代,当前损失为: nan theta = [[-247.97539291][   2.37657393][   1.55682769]]
第 240000 次迭代,当前损失为: nan theta = [[-248.04658161][   2.99387595][   0.87684819]]
theta=[[-247.44837176][   2.78836624][   1.56814101]]
准确度 = 0.88
准确度 = 0.88

4.逻辑回归的正则化

1)理论部分

2)代码实现

将逻辑回归的代码实现修改代价函数,梯度下降法中迭代公式要改

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import accuracy_score# 定义加载数据的函数
def loaddata():data = np.loadtxt('data2.txt', delimiter=',')# 特征数n = data.shape[1] - 1X = data[:, 0:n]y = data[:, -1].reshape(-1, 1)return X, y# 定义散点图函数
def scatter(X, y):# 分别寻找y==1和y==0时,索引值的位置pos = np.where(y == 1)neg = np.where(y == 0)plt.scatter(X[pos[0], 0], X[pos[0], 1], marker='x')plt.scatter(X[neg[0], 0], X[neg[0], 1], marker='o')plt.xlabel('Exam 1 score')plt.xlabel('Exam 2 score')plt.show()# 实现sigmoid函数
def sigmoid(z):r = 1 / (1 + np.exp(-z))return r# 实现假设函数
def hypothesis(X, theta):z = np.dot(X, theta)return sigmoid(z)# 实现代价函数,先实现损失(返回值要改)
def computeCost(X, y, theta, lamda):m = X.shape[0]l = -y * np.log(hypothesis(X, theta)) - (1 - y) * np.log(1 - hypothesis(X, theta))# theta的二范式的表示,np.sum(np.power(theta,2))return np.sum(l) / m + (lamda / (2 * m)) * np.sum(np.power(theta, 2))# 梯度下降法求解(要改)
def gradientDescent(X, y, theta, iterations, alpha, lamda):# 数据量m = X.shape[0]# 在x最前面插入全为1的列# np.vstack():在竖直方向上堆叠# np.hstack表示在水平方向上平铺X = np.hstack((np.ones((m, 1)), X))for i in range(iterations):for j in range(len(theta)):theta[j] = theta[j] - (alpha / m) * (np.sum((hypothesis(X, theta) - y) * X[:, j].reshape(-1, 1)) + lamda * theta[j])if (i % 10000 == 0):# 每迭代10000次,输出一次损失值print('第', i, '次迭代,当前损失为:', computeCost(X, y, theta, lamda), 'theta =', theta)return theta# 画决策边界
def plotDescionBoundary(X, y, theta):# 样本点颜色cm_dark = mpl.colors.ListedColormap(['g', 'r'])plt.xlabel('Exam 1 score')plt.ylabel('Exam 2 score')# 根据y的结果自动的在cmap中选择颜色,c参数代表颜色plt.scatter(X[:, 0], X[:, 1], c=np.array(y).squeeze(), cmap=cm_dark, s=30)# 画分类决策面x1 = np.arange(min(X[:, 0]), max(X[:, 0]), 0.1)x2 = -(theta[0] + theta[1] * x1) / theta[2]plt.plot(x1, x2)plt.show()# 定义预测函数
def predict(X):m = X.shape[0]# 在x最前面插入全为1的列X = np.hstack((np.ones((m, 1)), X))# 求解假设函数的值(预测值)h = hypothesis(X, theta)# 根据概率值决定最终的分类,>=0.5为1类,<0.5为0类h[h >= 0.5] = 1h[h < 0.5] = 0return hif __name__ == '__main__':X, y = loaddata()scatter(X, y)# 特征数n = X.shape[1]# theta是列向量,+1是因为求梯度时X前会增加一个全1列theta = np.zeros(n + 1).reshape(n + 1, 1)iterations = 250000alpha = 0.08lamda = 0.01theta = gradientDescent(X, y, theta, iterations, alpha, lamda)print('theta=\n', theta)# 画决策面plotDescionBoundary(X, y, theta)# 预测p = predict(X)print('准确度 =', np.mean(y == p))print('准确度 =', accuracy_score(y, p))

5.逻辑回归实现多分类

1)原理



6.sklearn实现逻辑回归

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score# 加载数据
def loaddata():data = np.loadtxt('data2.txt', delimiter=',')n = data.shape[1] - 1X = data[:, 0:n]y = data[:, -1].ravel()  # reshape(-1,1)return X, y# 画决策边界
def plotDescionsBoundary(X, y, theta):cm_dark = mpl.colors.ListedColormap(['g', 'r'])plt.xlabel('Exam 1 score')plt.ylabel('Exam 2 score')# 根据y的结果自动的在cmap中选择颜色,c参数代表颜色# np.squeeze()函数转换后,要显示的数组变成了秩为1的数组plt.scatter(X[:, 0], X[:, 1], c=np.array(y).squeeze(), cmap=cm_dark, s=30)# 画分类决策面x1 = np.arange(min(X[:, 0]), max(X[:, 0]), 0.1)x2 = -(theta[0] + theta[1] * x1) / theta[2]plt.plot(x1, x2)plt.show()if __name__ == '__main__':X, y = loaddata()# 逻辑回归# 常用参数含义# C正则化参数(												

机器学习2-Logistic回归相关推荐

  1. 机器学习实战--Logistic回归与实例:从疝病症预测病马的死亡率

    声明 本文参考了<机器学习实战>书中代码,结合该书讲解,并加之自己的理解和阐述 机器学习实战系列博文 机器学习实战--k近邻算法改进约会网站的配对效果 机器学习实战--决策树的构建.画图与 ...

  2. 机器学习实战——Logistic回归

    书籍:<机器学习实战>中文版 IDE:PyCharm Edu 4.02 环境:Adaconda3  python3.6 关键词:sigmoid函数.批梯度上升法.随机梯度上升法 from ...

  3. 机器学习:Logistic回归处理用气象数据预测森林火灾的数据挖掘方法

    文章目录 线性模型与回归 最小二乘与参数求解 1.一维数据: 2.多维数据 最大似然估计 Logistic回归 基本介绍 基于Logistic回归和Sigmoid函数的分类 基于最优化方法的最佳回归系 ...

  4. 机器学习之Logistic回归(逻辑蒂斯回归)

    Logistic回归又称Logistic回归分析,主要在流行病学中应用较多,比较常用的情形是探索某疾病的危险因素,根据危险因素预测某疾病发生的概率,等等. 应用: 一.寻找危险因素,正如上面所说的寻找 ...

  5. 机器学习-监督学习-logistic回归,softMax回归

    本篇博文来总结一下回归模型里面两个非常重要的模型. logistic回归 softMAX回归 Logistic回归 logistics回归虽然有"回归"两字但是却是分类模型,并且是 ...

  6. python实现logistic_用Python实现机器学习算法—Logistic 回归算法

    在 Logistic 回归中,我们试图对给定输入特征的线性组合进行建模,来得到其二元变量的输出结果.例如,我们可以尝试使用竞选候选人花费的金钱和时间信息来预测选举的结果(胜或负).Logistic 回 ...

  7. 机器学习:Logistic回归介绍

    Logistic回归定义 简单来说, 逻辑回归(Logistic Regression)是一种用于解决二分类(0 or 1)问题的机器学习方法,用于估计某种事物的可能性.比如某用户购买某商品的可能性, ...

  8. 机器学习实战 - Logistic回归

    假设我们有 一些数据点,我们用一条直线对其进行拟合,那么拟合的过程就称为回归. 实际上Logistic回归经常用于二类分类,也就是一般只用于只存在两种诸如"是"与"不是& ...

  9. 【机器学习】Logistic回归---学习笔记(重新整理)

    Logistic回归学习笔记 Logistic回归学习线路 预备知识:建议先去B站学习一下信息量,熵,BL散度,交叉熵的概念. Logistic回归的函数模型 损失函数.损失最小化架构 对数损失作为损 ...

  10. 入门机器学习(四)--Logistic回归

    1.分类(Classification) 如何开发一个分类算法,以对肿瘤进行恶性或良性分类为例. 如果要对以上数据进行线性回归可以这么做: 如果h(x)≥0.5,那么输出为"y=1" ...

最新文章

  1. android上传本地图片到服务器上,Android使用post方式上传图片到服务器的方法
  2. 组队学习:学习者参考手册
  3. Android开发之Service与IntentService的区别与使用场景(源代码剖析)
  4. 浪潮信息:企业互联网化下的数据平台升级 | 云·创课程实录
  5. java 面向组件_Java 面向对象
  6. 【Android 安装包优化】资源打包配置 ( resources.arsc 资源映射表 | 配置国际化资源 )
  7. Android中ActivityManagerService与应用程序(客户端)通信模型分析
  8. 【Python】透视表、统计表、汇总表、报表
  9. thinkphp传递参数
  10. 基础编程题之查找组成一个偶数最接近的两个素数
  11. 点击按钮刷新_Chrome扩展推荐:抢票太累?后台监视网页,页面自动刷新和提醒...
  12. gcc之UTF-8编码
  13. 奈飞文化手册_《奈飞文化手册》速阅提炼分享3
  14. R 绘制风洞实验数据曲线
  15. ps一点通精品知识库
  16. html鼠标经过自动下拉菜单,用纯CSS实现鼠标经过后出现下拉菜单,实例讲解(附代码)...
  17. java guardedby_java 多线程并发设计模式之三:Guarded suspension 模式
  18. 带你深入了解Web3开发者堆栈
  19. android设备怎么支持8021x,android WiFi ASSOC_REJECT 流程跟踪
  20. 计算机专业选山大还是西工大,王牌专业

热门文章

  1. (转) EF三种编程方式的区别Database first ,Model first ,code first
  2. 国内国外最好的java开发论坛及站点 [转]
  3. spring框架Annotation之CRUD
  4. Best Cow Line (POJ 3217)
  5. c#读写apk的 comment
  6. python3的包(package)在centos中的安装地址
  7. 面向对象程序的设计模式
  8. 洛谷.3065.第一!First!(Trie 拓扑)
  9. NOIP2016愤怒的小鸟 题解报告 【状压DP】
  10. linux安装jdk1.8之后报错Error: dl failure on line 893的解决办法