c++实现LogisticRegression/用c++实现逻辑回归

本文介绍了使用C++实现逻辑回归的过程,强调了C++语法的学习和梯度下降算法的详细实现。代码涵盖梯度下降、随机梯度下降、批梯度下降三种学习方式,并提供了相关头文件和cpp源文件,读者可以直接编译运行。训练参数包括数据路径、迭代次数、学习速率、容差和训练方式等。
摘要由CSDN通过智能技术生成

今天没事学习c++,试着用c++实现了一个简单的逻辑回归。
因为重在学习c++语法和逻辑回归的具体实现细节,因此没有用到向量化矩阵化等操作,而是老老实实用遍历一步一步求解梯度。
代码具体实现了梯度下降、随梯度下降、批梯度下降三种学习算法。
本文仅包含代码实现部分,逻辑回归的理论可以参考:
http://blog.csdn.net/abcjennifer/article/details/7716281
代码包括两个头文件和一个cpp文件:

logisticregression.h

#ifndef _LOGISTICREGRESSION_H_
#define _LOGISTICREGRESSION_H_

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <assert.h>

struct DataSet {
    int numData;
    int numFeature;
    std::vector<std::vector<float> > features;
    std::vector<int> labels;
};

class LogisticRegression {
public:
    LogisticRegression(int max_iter, float learn_rate, float tol);

    ~LogisticRegression();

    DataSet loadData(std::string filename);

    void initWeights(int length);

    std::vector<float> oneSampleGrident(std::vector<float> feature, int label);

    void train(DataSet* dataset, std::string gdType);

    std::vector<float> getWeight();

    int predict(std::vector<float> feature);

    float predict_proba(std::vector<float> feature);

    float score(DataSet* dataset);

private:
    int maxIter_;
    float learnRate_;
    float tol_;
    std::vector<float> weights;
};

#endif

common.h

#ifndef _COMMON_H_
#define _COMMON_H_

#include <iostream>
#include <string>
#include <vector>
#include <cmath>

namespace common {

std::vector<std::string> Split(std::string line, char flag) {
    std::vector<std::string> ret;
    size_t start = 0;
    size_t index = line.find_first_of(flag, start);
    while (index != std::string::npos) {
        ret.push_back(line.substr(start, index));
        start = index + 1;
        index = line.find_first_of(flag, start);
    }
    ret.push_back(line.substr(start, index));
    return ret;
}

float Sigmoid(
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值