logistic regression,这个算法只能解决简单的线性二分类,在众多的机器学习分类算法中并不出众,但它能被改进为多分类,并换了另外一个名字softmax, 这可是深度学习中响当当的分类算法。

Reference: denny的学习专栏  // 臭味相投的一个博客

  • Xml保存图片的方法和读取的方式。
  • Mat显示内部的多个图片。
  • Mat::t() 显示矩阵内容。

本文用它来进行手写数字分类。

在opencv3.0中提供了一个xml文件,里面存放了40个样本,分别是20个数字0的手写体和20个数字1的手写体。本来每个数字的手写体是一张28*28的小图片,在xml使用1*784 的向量保存在<data>中。

这个文件的位置: \opencv\sources\samples\data\data01.xml

  1. /*//////////////////////////////////////////////////////////////////////////////////////
  2. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  3.  
  4. // By downloading, copying, installing or using the software you agree to this license.
  5. // If you do not agree to this license, do not download, install,
  6. // copy or use the software.
  7.  
  8. // This is a implementation of the Logistic Regression algorithm in C++ in OpenCV.
  9.  
  10. // AUTHOR:
  11. // Rahul Kavi rahulkavi[at]live[at]com
  12. //
  13.  
  14. // contains a subset of data from the popular Iris Dataset (taken from
  15. // "http://archive.ics.uci.edu/ml/datasets/Iris")
  16.  
  17. // # You are free to use, change, or redistribute the code in any way you wish for
  18. // # non-commercial purposes, but please maintain the name of the original author.
  19. // # This code comes with no warranty of any kind.
  20.  
  21. // #
  22. // # You are free to use, change, or redistribute the code in any way you wish for
  23. // # non-commercial purposes, but please maintain the name of the original author.
  24. // # This code comes with no warranty of any kind.
  25.  
  26. // # Logistic Regression ALGORITHM
  27.  
  28. // License Agreement
  29. // For Open Source Computer Vision Library
  30.  
  31. // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
  32. // Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved.
  33. // Third party copyrights are property of their respective owners.
  34.  
  35. // Redistribution and use in source and binary forms, with or without modification,
  36. // are permitted provided that the following conditions are met:
  37.  
  38. // * Redistributions of source code must retain the above copyright notice,
  39. // this list of conditions and the following disclaimer.
  40.  
  41. // * Redistributions in binary form must reproduce the above copyright notice,
  42. // this list of conditions and the following disclaimer in the documentation
  43. // and/or other materials provided with the distribution.
  44.  
  45. // * The name of the copyright holders may not be used to endorse or promote products
  46. // derived from this software without specific prior written permission.
  47.  
  48. // This software is provided by the copyright holders and contributors "as is" and
  49. // any express or implied warranties, including, but not limited to, the implied
  50. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  51. // In no event shall the Intel Corporation or contributors be liable for any direct,
  52. // indirect, incidental, special, exemplary, or consequential damages
  53. // (including, but not limited to, procurement of substitute goods or services;
  54. // loss of use, data, or profits; or business interruption) however caused
  55. // and on any theory of liability, whether in contract, strict liability,
  56. // or tort (including negligence or otherwise) arising in any way out of
  57. // the use of this software, even if advised of the possibility of such damage.*/
  58.  
  59. #include <iostream>
  60.  
  61. #include <opencv2/core.hpp>
  62. #include <opencv2/ml.hpp>
  63. #include <opencv2/highgui.hpp>
  64.  
  65. using namespace std;
  66. using namespace cv;
  67. using namespace cv::ml;
  68.  
  69. /*
  70. * Jeff --> Show mutiple-photos from Mat.
  71. */
  72. static void showImage(const Mat &data, int columns, const String &name)
  73. {
  74. // columns = 28
  75. Mat bigImage;
  76. for(int i = 0; i < data.rows; ++i)
  77. {
  78. //rows: number of photos.
  79. // vector --> reshape --> col 28, col 28 ...
  80. // push_back: show each pic from left to right.
  81. bigImage.push_back(data.row(i).reshape(0, columns));
  82.  
  83. }
  84. imshow(name, bigImage.t());
  85. }
  86.  
  87. static float calculateAccuracyPercent(const Mat &original, const Mat &predicted)
  88. {
  89. return 100 * (float)countNonZero(original == predicted) / predicted.rows;
  90. }
  91.  
  92. int main()
  93. {
  94. const String filename = "../data/data01.xml";
  95. cout << "**********************************************************************" << endl;
  96. cout << filename
  97. << " contains digits 0 and 1 of 20 samples each, collected on an Android device" << endl;
  98. cout << "Each of the collected images are of size 28 x 28 re-arranged to 1 x 784 matrix"
  99. << endl;
  100. cout << "**********************************************************************" << endl;
  101.  
  102. Mat data, labels;
  103. {
  104. /*
  105. * Jeff --> Load xml.
  106. * transform to Mat.
  107. * FileStorage.
  108. */
  109. cout << "loading the dataset...";
  110. // Step 1.
  111. FileStorage f;
  112. if(f.open(filename, FileStorage::READ))
  113. {
  114. // Step 2.
  115. f["datamat"] >> data;
  116. f["labelsmat"] >> labels;
  117. f.release();
  118. }
  119. else
  120. {
  121. cerr << "file can not be opened: " << filename << endl;
  122. return 1;
  123. }
  124. // Step 3.
  125. data.convertTo(data, CV_32F);
  126. labels.convertTo(labels, CV_32F);
  127.  
  128. cout << "read " << data.rows << " rows of data" << endl;
  129. }
  130.  
  131. Mat data_train, data_test;
  132. Mat labels_train, labels_test;
  133. for(int i = 0; i < data.rows; i++)
  134. {
  135. // Step 4.
  136. if(i % 2 == 0)
  137. {
  138. data_train.push_back(data.row(i));
  139. labels_train.push_back(labels.row(i));
  140. }
  141. else
  142. {
  143. data_test.push_back(data.row(i));
  144. labels_test.push_back(labels.row(i));
  145. }
  146. }
  147. cout << "training/testing samples count: " << data_train.rows << "/" << data_test.rows << endl;
  148.  
  149. // display sample image
  150. showImage(data_train, 28, "train data");
  151. showImage(data_test, 28, "test data");
  152.  
  153. /**************************************************************************/
  154.  
  155. // simple case with batch gradient
  156. cout << "training...";
  157.  
  158. // Step (1), create classifier.
  159. Ptr<LogisticRegression> lr1 = LogisticRegression::create();
  160.  
  161. // Step (2),
  162. lr1->setLearningRate(0.001);
  163. lr1->setIterations(10);
  164. lr1->setRegularization(LogisticRegression::REG_L2);
  165. lr1->setTrainMethod(LogisticRegression::BATCH);
  166. lr1->setMiniBatchSize(1);
  167.  
  168. // Step (3), train.
  169. //! [init]
  170. lr1->train(data_train, ROW_SAMPLE, labels_train);
  171. cout << "done!" << endl;
  172.  
  173. //--------------------------------------------------------------------------
  174.  
  175. cout << "predicting...";
  176.  
  177. // Step (4), predict.
  178. Mat responses;
  179. lr1->predict(data_test, responses);
  180. cout << "done!" << endl;
  181.  
  182. // Step (5), show prediction report
  183. cout << "original vs predicted:" << endl;
  184. // Jeff --> CV_32S is a signed 32bit integer value for each pixel.
  185. labels_test.convertTo(labels_test, CV_32S);
  186.  
  187. cout << labels_test.t() << endl;
  188. cout << responses.t() << endl;
  189. cout << "accuracy: " << calculateAccuracyPercent(labels_test, responses) << "%" << endl;
  190.  
  191. // Step (6), save the classfier
  192. const String saveFilename = "NewLR_Trained.xml";
  193. cout << "saving the classifier to " << saveFilename << endl;
  194. lr1->save(saveFilename);
  195.  
  196. /****************************** End ***************************************/
  197.  
  198. // load the classifier onto new object
  199. cout << "loading a new classifier from " << saveFilename << endl;
  200. Ptr<LogisticRegression> lr2 = StatModel::load<LogisticRegression>(saveFilename);
  201.  
  202. // predict using loaded classifier
  203. cout << "predicting the dataset using the loaded classfier...";
  204. Mat responses2;
  205. lr2->predict(data_test, responses2);
  206. cout << "done!" << endl;
  207.  
  208. // calculate accuracy
  209. cout << labels_test.t() << endl;
  210. cout << responses2.t() << endl;
  211. cout << "accuracy: " << calculateAccuracyPercent(labels_test, responses2) << "%" << endl;
  212.  
  213. waitKey(0);
  214. return 0;
  215. }

关于逻辑回归:http://blog.csdn.net/pakko/article/details/37878837

什么是逻辑回归?

Logistic回归与多重线性回归实际上有很多相同之处,最大的区别就在于它们的因变量不同,其他的基本都差不多。正是因为如此,这两种回归可以归于同一个家族,即广义线性模型(generalizedlinear model)。

这一家族中的模型形式基本上都差不多,不同的就是因变量不同。

  • 如果是连续的,就是多重线性回归;
  • 如果是二项分布,就是Logistic回归;
  • 如果是Poisson分布,就是Poisson回归;
  • 如果是负二项分布,就是负二项回归。

Logistic回归的因变量可以是二分类的,也可以是多分类的,但是二分类的更为常用,也更加容易解释。所以实际中最常用的就是二分类的Logistic回归。

Logistic回归的主要用途:

  • 寻找危险因素:寻找某一疾病的危险因素等;
  • 预测:根据模型,预测在不同的自变量情况下,发生某病或某种情况的概率有多大;
  • 判别:实际上跟预测有些类似,也是根据模型,判断某人属于某病或属于某种情况的概率有多大,也就是看一下这个人有多大的可能性是属于某病。

Logistic回归主要在流行病学中应用较多,比较常用的情形是探索某疾病的危险因素,根据危险因素预测某疾病发生的概率,等等。例如,想探讨胃癌发生的危险因素,可以选择两组人群,一组是胃癌组,一组是非胃癌组,两组人群肯定有不同的体征和生活方式等。这里的因变量就是是否胃癌,即“是”或“否”,自变量就可以包括很多了,例如年龄、性别、饮食习惯、幽门螺杆菌感染等。自变量既可以是连续的,也可以是分类的。

常规步骤

Regression问题的常规步骤为:

  1. 寻找h函数(即hypothesis); ==> Sigmoid函数
  2. 构造J函数(loss函数);
  3. 想办法使得J函数最小并求得回归参数(θ)

详见reference博客。

[OpenCV] Samples 06: [ML] logistic regression的更多相关文章

  1. [OpenCV] Samples 06: logistic regression

    logistic regression,这个算法只能解决简单的线性二分类,在众多的机器学习分类算法中并不出众,但它能被改进为多分类,并换了另外一个名字softmax, 这可是深度学习中响当当的分类算法 ...

  2. [OpenCV] Samples 02: [ML] kmeans

    注意Mat作为kmeans的参数的含义. 扩展:高维向量的聚类. #include "opencv2/highgui.hpp" #include "opencv2/cor ...

  3. [OpenCV] Samples 10: imagelist_creator

    yaml写法的简单例子.将 $ ./ 1 2 3 4 5 命令的参数(代表图片地址)写入yaml中. 写yaml文件. 参考:[OpenCV] Samples 06: [ML] logistic re ...

  4. ML 逻辑回归 Logistic Regression

    逻辑回归 Logistic Regression 1 分类 Classification 首先我们来看看使用线性回归来解决分类会出现的问题.下图中,我们加入了一个训练集,产生的新的假设函数使得我们进行 ...

  5. [机器学习] Coursera ML笔记 - 逻辑回归(Logistic Regression)

    引言 机器学习栏目记录我在学习Machine Learning过程的一些心得笔记,涵盖线性回归.逻辑回归.Softmax回归.神经网络和SVM等等.主要学习资料来自Standford Andrew N ...

  6. 在opencv3中实现机器学习之:利用逻辑斯谛回归(logistic regression)分类

    logistic regression,注意这个单词logistic ,并不是逻辑(logic)的意思,音译过来应该是逻辑斯谛回归,或者直接叫logistic回归,并不是什么逻辑回归.大部分人都叫成逻 ...

  7. SAS PROC MCMC example in R: Logistic Regression Random-Effects Model(转)

    In this post I will run SAS example Logistic Regression Random-Effects Model in four R based solutio ...

  8. [Machine Learning & Algorithm]CAML机器学习系列1:深入浅出ML之Regression家族

    声明:本博客整理自博友@zhouyong计算广告与机器学习-技术共享平台,尊重原创,欢迎感兴趣的博友查看原文. 符号定义 这里定义<深入浅出ML>系列中涉及到的公式符号,如无特殊说明,符号 ...

  9. SparkMLlib之 logistic regression源码分析

    最近在研究机器学习,使用的工具是spark,本文是针对spar最新的源码Spark1.6.0的MLlib中的logistic regression, linear regression进行源码分析,其 ...

随机推荐

  1. android开发学习之Level List篇

    Level List google 说明:A Drawable that manages a number of alternate Drawables, each assigned a maximu ...

  2. java-多线程新特性

    Java定时器相关Timer和TimerTask类 每个Timer对象相对应的是单个后台线程,用于顺序地执行所有计时器任务TimerTask对象. Timer有两种执行任务的模式,最常用的是sched ...

  3. mysqld 已死,但是 subsys 被锁

    1. Obviously the 'ole check the log file for anything nasty cat /var/log/mysqld.log 2. Stop the serv ...

  4. Deploying JRE (Native Plug-in) for Windows Clients in Oracle E-Business Suite Release 12 (文档 ID 393931.1)

    In This Document Section 1: Overview Section 2: Pre-Upgrade Steps Section 3: Upgrade and Configurati ...

  5. lxc on centos

    终于把lxc的网络配通了,也不知道对不对,记一下 一开始都是雷同的地方 yum install libcgroup lxc lxc-templates 安装lxc cgroup 然后记得 chkcon ...

  6. mac下android环境搭建笔记(android studio)

    本文记录了本人在mac上配置android开发环境的一些过程,为了方便直接选用了官方的IDE– Android Studio .本文包括了android studio的安装.创建第一个hello wo ...

  7. .net开发笔记(十二) 设计时与运行时的区别(续)

    上一篇博客详细讲到了设计时(DesignTime)和运行时(RunTime)的概念与区别,不过没有给出实际的Demo,今天整理了一下,做了一个例子,贴出来分享一下,巩固前一篇博客讲到的内容. 简单回顾 ...

  8. 渣渣小本求职复习之路每天一博客系列——Unix&Linux入门(5)

    前情回顾:昨天简单地介绍了一下如何使用vi编辑器,例如命令模式和插入模式的切换,以及一些简单命令的讲解. —————————————————————————直接就开始吧———————————————— ...

  9. C#Light/Evil合体啦

    决定将C#Light和C#Evil合并成一个项目,毕竟C#Evil包含C#Light所有的功能,分开两个,基本的表达式方面有什么bug还得两头改 暂时就C#Light/Evil这么叫吧,庆祝合体,画了 ...

  10. 不插网线,看不到IP的解决办法

    在Windows中,如果不插网线,就看不到IP地址,即使这个块网卡已经绑定了固定IP,原因是操作系统开启了DHCP Media Sense功能,该功能的作用如下: 在一台使用 TCP/IP 的基于 W ...