热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Logistic回归模型(C++代码实现)

Logistic回归主要针对输入的数据是多个,输出则是有限的数值型,多为2个分类。涉及到以下方面:1.输出yw0+w1*x1+w2*x2+..(x1,x2,是样本的

Logistic回归主要针对输入的数据是多个,输出则是有限的数值型,多为2个分类。

涉及到以下方面:

1. 输出y = w0+w1*x1+w2*x2+..... (x1,x2,...是样本的属性值,为连续型的变量,w0,w1,w2,...为所要求的参数,y为有限的数值型变量,表示样本所属类别)。

2. logistic模型: 1/(1+exp(-z)),其中z= w0+w1*x1+w2*x2+..... 。

3.算法实现:

    w初始化为1;

    alph = 0.1; //设置步长,需根据情况逐步调整

    i = 0;

    while( i<样本数量)

          zi = w0+w1*xi1+w2*xi2+..... 

         h = 1/(1+exp(-zi));

         error = yi-h;

         while(...)

               wj = wj+alph *error*xij; // j表示第j个属性

          end

    end

以上算法过程在样本量比较小的时候可以实现,在样本量非常大的时候,需要考虑采用随机梯度下降法,即随机从总的样本的选出小的样本集来用于迭代过程(可以百度相关资料)。

本文主要采用了梯度下降法完成了参数值优化过程。以下程序主要将3中算法实现。主要包含main.h 和 main.cpp两个文件

测试结果发现预测的准确率可以到80%左右。但感觉这和参数的调整有很大关系,样本量还是太小(总样本量198,训练集:150,测试集:48),这里比较简便,不包含校准数据集,另外结果存在一些欠拟合的现象。


main.h

/*************
Logistic Regression( logistic 回归 )using newton gradient descent

CopyRight 2016/8/21 xukaiwen
All Rights Reserved

**************/

#ifndef MAIN_H
#define MAIN_H

#include "stdio.h"
#include "stdlib.h"
#include "iostream"
#include "string"
#include "string.h"
#include
#include

#include "math.h"

using namespace std;

#define maxClassLabelNum 10;
int curLabelNum = 0;


const double alph = 0.3; //set the newton gradient algorithm fixed step
const int attriNum = 33;
const int sampleNum = 198;
int trainNum = 140;

struct DataSample
{
double attriValue[attriNum];
bool classLabel;
};

double StringTodouble(char * src)
{
double a;
stringstream str;
str< str>>a;
str.clear();
return a;
}



int ReadData( DataSample* data, char *file)
{
FILE *pFile;
char buf[1024];
pFile = fopen(file,"rt");
if(pFile==NULL)
{
printf("the data file is not existing: %s\n", file);
return -1;
}

int row = 0; //data line
int cloumn = 0; //data attribute
char delim[] = ",";//data delimiter
char *tmpdata = NULL;//data cache

while(!feof(pFile)&&row {
buf[0] = '\0';
fgets(buf,1024,pFile);

if( buf[strlen(buf)-1]=='\n' )
{
buf[strlen(buf)-1]='\0';
}

//the first column is non-used,and second column is class label;
for( int column = 0;column<(attriNum+2);++column )
{
if( column==0 )
{
tmpdata = strtok(buf,delim);
continue;
}
else if( column==1 )
{
tmpdata = strtok(NULL,delim);


if( tmpdata[0]=='R' )
data[row].classLabel = 1; //R:1; N:0
else
data[row].classLabel = 0;

}
else
{
tmpdata = strtok(NULL,delim);

if(tmpdata[0]!='?')// '?' mean the loss attribute value
data[row].attriValue[column-2] = StringTodouble(tmpdata);
else
data[row].attriValue[column-2] = -1000;
}
}
++row;

}

return 1;
}

void Normalize( DataSample* data )
{
double atrriMinValue[attriNum];
double atrriMaxValue[attriNum];//for normalization (x-xmin)/(xmax-xmin)

//think about the first sample is none-loss
//get the min and max value of each attribute without thinking about the loss atrribute
for( int i=0;i {
atrriMinValue[i] = data[0].attriValue[i];
atrriMaxValue[i] = data[0].attriValue[i];
}

for( int row = 1; row for( int column = 0; column {
if( data[row].attriValue[column] > atrriMaxValue[column] && (data[row].attriValue[column]+1000)>0.0001 )
atrriMaxValue[column] = data[row].attriValue[column];

if( data[row].attriValue[column] 0.0001 )
atrriMinValue[column] = data[row].attriValue[column];
}

for( int row = 1; row for( int column = 0; column {
if( (data[row].attriValue[column]+1000)>0.0001)
data[row].attriValue[column] = (data[row].attriValue[column]-atrriMinValue[column])/(atrriMaxValue[column]-atrriMinValue[column]);
else
data[row].attriValue[column] = 0;//set loss value 0;
}
}

//use newton gradient descent algorithm to get the w
//logistic model: 1/(1+exp(-z))
//class label
void Logistic( DataSample* data, double *logisW )
{

//memset( logisW,1.0,(attriNum+1)*sizeof(double) );//initial

for( int i=0;i<(attriNum+1);++i )
{
logisW[i] = 1.0;
}


Normalize( data );

double h = 0.0;
double error = 0.0;
for( int row=0; row {
h = 0.0;
for( int column=0; column {
h += data[row].attriValue[column]*logisW[column];
}
h += logisW[attriNum]*1;
h = 1/(1+exp(-h));

error = data[row].classLabel-h;

for( int column=0; column {
logisW[column] += error*alph*data[row].attriValue[column];
}
logisW[attriNum] = error*alph*1;

}
}

bool Predict( DataSample sample, double *logisW )
{
double h = 0.0;
bool label = 0;
for( int column=0; column {
h += sample.attriValue[column]*logisW[column];
}
h += logisW[attriNum];

if( h>0.5 )
label = 1;
else
label = 0;

if( label==sample.classLabel )
return 1;
else
return 0;
}


#endif
main.cpp

/*************
Logistic Regression( logistic 回归 )using newton gradient descent

the Data:from UCI datalib named "wpbc.data"(that is about cancer )

CopyRight 2016/8/21 xukaiwen
All Rights Reserved

**************/

#include "main.h"

int main()
{
char *file = "C:\\Users\\Administrator\\Desktop\\machine_learnning\\wpbc.data";
DataSample *data = new DataSample[sampleNum];
double *logisW = new double[attriNum+1];

if( -1!=ReadData( data,file ) )
{
Logistic( data,logisW );
}

for(int i=0;i<(attriNum+1);++i)
{
printf("%f\t",logisW[i]);
}
printf("\n\n");

int correct = 0;
int sum = 0;
for(int i=trainNum;i {
++sum;
bool eva = Predict(data[i],logisW);
if(eva)
++correct;
}

double rp = double(correct)/sum;
printf("the right correction: %f\n",rp);

delete []data;
delete []logisW;

return 0;
}



推荐阅读
  • golang常用库:配置文件解析库/管理工具viper使用
    golang常用库:配置文件解析库管理工具-viper使用-一、viper简介viper配置管理解析库,是由大神SteveFrancia开发,他在google领导着golang的 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 题目描述:给定n个半开区间[a, b),要求使用两个互不重叠的记录器,求最多可以记录多少个区间。解决方案采用贪心算法,通过排序和遍历实现最优解。 ... [详细]
  • 深入解析JVM垃圾收集器
    本文基于《深入理解Java虚拟机:JVM高级特性与最佳实践》第二版,详细探讨了JVM中不同类型的垃圾收集器及其工作原理。通过介绍各种垃圾收集器的特性和应用场景,帮助读者更好地理解和优化JVM内存管理。 ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • 本文将介绍如何使用 Go 语言编写和运行一个简单的“Hello, World!”程序。内容涵盖开发环境配置、代码结构解析及执行步骤。 ... [详细]
  • 本文探讨了Hive中内部表和外部表的区别及其在HDFS上的路径映射,详细解释了两者的创建、加载及删除操作,并提供了查看表详细信息的方法。通过对比这两种表类型,帮助读者理解如何更好地管理和保护数据。 ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • 本文详细介绍了如何在Linux系统上安装和配置Smokeping,以实现对网络链路质量的实时监控。通过详细的步骤和必要的依赖包安装,确保用户能够顺利完成部署并优化其网络性能监控。 ... [详细]
  • 本文介绍如何利用动态规划算法解决经典的0-1背包问题。通过具体实例和代码实现,详细解释了在给定容量的背包中选择若干物品以最大化总价值的过程。 ... [详细]
  • 本文介绍了Java并发库中的阻塞队列(BlockingQueue)及其典型应用场景。通过具体实例,展示了如何利用LinkedBlockingQueue实现线程间高效、安全的数据传递,并结合线程池和原子类优化性能。 ... [详细]
  • 深入理解C++中的KMP算法:高效字符串匹配的利器
    本文详细介绍C++中实现KMP算法的方法,探讨其在字符串匹配问题上的优势。通过对比暴力匹配(BF)算法,展示KMP算法如何利用前缀表优化匹配过程,显著提升效率。 ... [详细]
  • 本文详细介绍了Java编程语言中的核心概念和常见面试问题,包括集合类、数据结构、线程处理、Java虚拟机(JVM)、HTTP协议以及Git操作等方面的内容。通过深入分析每个主题,帮助读者更好地理解Java的关键特性和最佳实践。 ... [详细]
  • Python自动化处理:从Word文档提取内容并生成带水印的PDF
    本文介绍如何利用Python实现从特定网站下载Word文档,去除水印并添加自定义水印,最终将文档转换为PDF格式。该方法适用于批量处理和自动化需求。 ... [详细]
  • 本文详细解析了Python中的os和sys模块,介绍了它们的功能、常用方法及其在实际编程中的应用。 ... [详细]
author-avatar
隔岸观火2502884207
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有