///////////////////////////////////////////////////////////////////////////////////////1// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.23// By downloading, copying, installing or using the software you agree to this license.4// If you do not agree to this license, do not download, install,5// copy or use the software.67// This is a implementation of the Logistic Regression algorithm in C++ in OpenCV.89// AUTHOR:10// Rahul Kavi rahulkavi[at]live[at]com11//1213// contains a subset of data from the popular Iris Dataset (taken from "http://archive.ics.uci.edu/ml/datasets/Iris")1415// # You are free to use, change, or redistribute the code in any way you wish for16// # non-commercial purposes, but please maintain the name of the original author.17// # This code comes with no warranty of any kind.1819// #20// # You are free to use, change, or redistribute the code in any way you wish for21// # non-commercial purposes, but please maintain the name of the original author.22// # This code comes with no warranty of any kind.2324// # Logistic Regression ALGORITHM252627// License Agreement28// For Open Source Computer Vision Library2930// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.31// Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved.32// Third party copyrights are property of their respective owners.3334// Redistribution and use in source and binary forms, with or without modification,35// are permitted provided that the following conditions are met:3637// * Redistributions of source code must retain the above copyright notice,38// this list of conditions and the following disclaimer.3940// * Redistributions in binary form must reproduce the above copyright notice,41// this list of conditions and the following disclaimer in the documentation42// and/or other materials provided with the distribution.4344// * The name of the copyright holders may not be used to endorse or promote products45// derived from this software without specific prior written permission.4647// This software is provided by the copyright holders and contributors "as is" and48// any express or implied warranties, including, but not limited to, the implied49// warranties of merchantability and fitness for a particular purpose are disclaimed.50// In no event shall the Intel Corporation or contributors be liable for any direct,51// indirect, incidental, special, exemplary, or consequential damages52// (including, but not limited to, procurement of substitute goods or services;53// loss of use, data, or profits; or business interruption) however caused54// and on any theory of liability, whether in contract, strict liability,55// or tort (including negligence or otherwise) arising in any way out of56// the use of this software, even if advised of the possibility of such damage.5758#include "test_precomp.hpp"5960namespace opencv_test { namespace {6162bool calculateError( const Mat& _p_labels, const Mat& _o_labels, float& error)63{64CV_TRACE_FUNCTION();65error = 0.0f;66float accuracy = 0.0f;67Mat _p_labels_temp;68Mat _o_labels_temp;69_p_labels.convertTo(_p_labels_temp, CV_32S);70_o_labels.convertTo(_o_labels_temp, CV_32S);7172CV_Assert(_p_labels_temp.total() == _o_labels_temp.total());73CV_Assert(_p_labels_temp.rows == _o_labels_temp.rows);7475accuracy = (float)countNonZero(_p_labels_temp == _o_labels_temp)/_p_labels_temp.rows;76error = 1 - accuracy;77return true;78}7980//--------------------------------------------------------------------------------------------8182class CV_LRTest : public cvtest::BaseTest83{84public:85CV_LRTest() {}86protected:87virtual void run( int start_from );88};8990void CV_LRTest::run( int /*start_from*/ )91{92CV_TRACE_FUNCTION();93// initialize variables from the popular Iris Dataset94string dataFileName = ts->get_data_path() + "iris.data";95Ptr<TrainData> tdata = TrainData::loadFromCSV(dataFileName, 0);9697if (tdata.empty()) {98ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);99return;100}101102// run LR classifier train classifier103Ptr<LogisticRegression> p = LogisticRegression::create();104p->setLearningRate(1.0);105p->setIterations(10001);106p->setRegularization(LogisticRegression::REG_L2);107p->setTrainMethod(LogisticRegression::BATCH);108p->setMiniBatchSize(10);109p->train(tdata);110111// predict using the same data112Mat responses;113p->predict(tdata->getSamples(), responses);114115// calculate error116int test_code = cvtest::TS::OK;117float error = 0.0f;118if(!calculateError(responses, tdata->getResponses(), error))119{120ts->printf(cvtest::TS::LOG, "Bad prediction labels\n" );121test_code = cvtest::TS::FAIL_INVALID_OUTPUT;122}123else if(error > 0.05f)124{125ts->printf(cvtest::TS::LOG, "Bad accuracy of (%f)\n", error);126test_code = cvtest::TS::FAIL_BAD_ACCURACY;127}128129{130FileStorage s("debug.xml", FileStorage::WRITE);131s << "original" << tdata->getResponses();132s << "predicted1" << responses;133s << "learnt" << p->get_learnt_thetas();134s << "error" << error;135s.release();136}137ts->set_failed_test_info(test_code);138}139140//--------------------------------------------------------------------------------------------141class CV_LRTest_SaveLoad : public cvtest::BaseTest142{143public:144CV_LRTest_SaveLoad(){}145protected:146virtual void run(int start_from);147};148149150void CV_LRTest_SaveLoad::run( int /*start_from*/ )151{152CV_TRACE_FUNCTION();153int code = cvtest::TS::OK;154155// initialize variables from the popular Iris Dataset156string dataFileName = ts->get_data_path() + "iris.data";157Ptr<TrainData> tdata = TrainData::loadFromCSV(dataFileName, 0);158159Mat responses1, responses2;160Mat learnt_mat1, learnt_mat2;161162// train and save the classifier163String filename = tempfile(".xml");164try165{166// run LR classifier train classifier167Ptr<LogisticRegression> lr1 = LogisticRegression::create();168lr1->setLearningRate(1.0);169lr1->setIterations(10001);170lr1->setRegularization(LogisticRegression::REG_L2);171lr1->setTrainMethod(LogisticRegression::BATCH);172lr1->setMiniBatchSize(10);173lr1->train(tdata);174lr1->predict(tdata->getSamples(), responses1);175learnt_mat1 = lr1->get_learnt_thetas();176lr1->save(filename);177}178catch(...)179{180ts->printf(cvtest::TS::LOG, "Crash in write method.\n" );181ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION);182}183184// and load to another185try186{187Ptr<LogisticRegression> lr2 = Algorithm::load<LogisticRegression>(filename);188lr2->predict(tdata->getSamples(), responses2);189learnt_mat2 = lr2->get_learnt_thetas();190}191catch(...)192{193ts->printf(cvtest::TS::LOG, "Crash in write method.\n" );194ts->set_failed_test_info(cvtest::TS::FAIL_EXCEPTION);195}196197CV_Assert(responses1.rows == responses2.rows);198199// compare difference in learnt matrices before and after loading from disk200Mat comp_learnt_mats;201comp_learnt_mats = (learnt_mat1 == learnt_mat2);202comp_learnt_mats = comp_learnt_mats.reshape(1, comp_learnt_mats.rows*comp_learnt_mats.cols);203comp_learnt_mats.convertTo(comp_learnt_mats, CV_32S);204comp_learnt_mats = comp_learnt_mats/255;205206// compare difference in prediction outputs and stored inputs207// check if there is any difference between computed learnt mat and retrieved mat208209float errorCount = 0.0;210errorCount += 1 - (float)countNonZero(responses1 == responses2)/responses1.rows;211errorCount += 1 - (float)sum(comp_learnt_mats)[0]/comp_learnt_mats.rows;212213if(errorCount>0)214{215ts->printf( cvtest::TS::LOG, "Different prediction results before writing and after reading (errorCount=%d).\n", errorCount );216code = cvtest::TS::FAIL_BAD_ACCURACY;217}218219remove( filename.c_str() );220221ts->set_failed_test_info( code );222}223224TEST(ML_LR, accuracy) { CV_LRTest test; test.safe_run(); }225TEST(ML_LR, save_load) { CV_LRTest_SaveLoad test; test.safe_run(); }226227}} // namespace228229230