#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <fstream>
#include <sstream>
#include <functional>
double myfunction(double num) {
    return exp(num);
}
template <typename T>
void softmax(const typename::std::vector<T> &v, typename::std::vector<T> &s) {
    double sum=0.0;
    transform(v.begin(), v.end(), s.begin(), myfunction);
    sum=accumulate(s.begin(), s.end(), sum);
    for(size_t i=0; i<s.size(); ++i)
        s.at(i)/=sum;
}
template <typename T>
void hypothesis(const std::vector<std::vector<T> > &theta, const std::vector<T> &feature, std::vector<T> &prb) {
    prb.clear();
    double sum=0.0;
    for(size_t i=0; i<theta.size(); ++i) {
        double inner=0.0;
        inner=inner_product(theta.at(i).begin(), theta.at(i).end(), feature.begin(), inner);
        inner=exp(inner);
        sum+=inner;
    }
    for(size_t i=0; i<theta.size(); ++i) {
        double inner=0.0;
        inner=inner_product(theta.at(i).begin(), theta.at(i).end(), feature.begin(), inner);
        inner=exp(inner);
        prb.push_back(inner/sum);
    }
}
double stringtodouble(const std::string& s) {
    std::istringstream iss(s);
    double num;
    return iss>>num?num:0;
}
int indicator(const int &a, const int &b) {
    if(a==b)
        return 1;
    else
        return 0;
}
void print(int i) {
    std::cout<<i<<" ";
}
double CostFunc(const std::vector<std::vector<double> > &vv_iris, const std::vector<std::vector<double> > &theta) {
    double sum3=0.0;
    for(size_t i=0; i<vv_iris.size(); ++i) {
        double sum1=0.0;
        int k;
        for(size_t j=0; j<theta.size(); ++j) {
            double inner=0.0;
            int b=j+1;
            int indi=indicator(vv_iris.at(i).back(), b);
            if(indi)
                k=j;
            inner=inner_product(vv_iris.at(i).begin(), vv_iris.at(i).end()-1, theta.at(j).begin(), inner);
            sum1+=exp(inner);
        }
        sum1=log(sum1);
        double inner=0.0;
        inner=inner_product(vv_iris.at(i).begin(), vv_iris.at(i).end()-1, theta.at(k).begin(), inner);
        inner-=sum1;
        sum3+=inner;
    }
    sum3/=vv_iris.size();
    return -sum3;
}
void GetThetaGrad(const std::vector<std::vector<double> > &vv_iris, const std::vector<std::vector<double> > &theta, const int j, std::vector<double> &grad_theta) {
    double sum=0.0;
    for(size_t i=0; i<vv_iris.size(); ++i) {
        double sum1=0.0;
        for(size_t k=0; k<theta.size(); ++k) {
            double inner=0.0;
            inner=inner_product(vv_iris.at(i).begin(), vv_iris.at(i).end()-1, theta.at(k).begin(), inner);
            inner=exp(inner);
            sum1+=inner;
        }
        double inner=0.0;
        inner=inner_product(vv_iris.at(i).begin(), vv_iris.at(i).end()-1, theta.at(j).begin(), inner);
        inner=exp(inner);
        sum1=(-1)*inner/sum1;
        int b=j+1;
        int indi=indicator(vv_iris.at(i).back(), b);
        sum1+=indi;
        std::vector<double> v_temp(theta.front().size(), 0);
        transform(vv_iris.at(i).begin(), vv_iris.at(i).end()-1, v_temp.begin(), std::bind1st(std::multiplies<double>(), sum1));
        for(size_t l=0; l<theta.front().size(); ++l) {
            grad_theta.at(l)+=v_temp.at(l);
        }
    }
    for(size_t i=0; i<grad_theta.size(); ++i) {
        grad_theta.at(i)=(-1)*grad_theta.at(i)/vv_iris.size();
    }
}
void ReadDataFromCsv(std::string &filename, std::vector<std::vector<double> > &lines_feat) {
    std::ifstream vm_info(filename.c_str());
    std::string lines, var;
    std::vector<double> row;
    lines_feat.clear();
    while(!vm_info.eof()) {
        getline(vm_info, lines);
        if(lines.empty())
            break;
        std::istringstream stringin(lines);
        row.clear();
        row.push_back(1);
        while(std::getline(stringin, var, ',')) {
            if(var=="Iris-setosa")
                var="1";
            else if(var=="Iris-versicolor")
                var="2";
            else if(var=="Iris-virginica")
                var="3";
            double value=stringtodouble(var);
            row.push_back(value);
        }
        lines_feat.push_back(row);
    }
}
template <class DataType>
void ReadMatFromFile(std::string &filename, std::vector<std::vector<DataType> > &lines_feat) {
    std::ifstream vm_info(filename.c_str());
    std::string lines;
    DataType var;
    std::vector<DataType> row;
    lines_feat.clear();
    while(!vm_info.eof()) {
        getline(vm_info, lines);
        if(lines.empty())
            break;
        std::replace(lines.begin(), lines.end(), ',', ' ');
        std::stringstream stringin(lines);
        row.clear();
        while(stringin >> var) {
            row.push_back(var);
        }
        lines_feat.push_back(row);
    }
}
template <class T>
void Display2DVector(std::vector<std::vector<T> > &vv) {
    for(size_t i=0;i<vv.size();++i) {
        for(typename::std::vector<T>::const_iterator it=vv.at(i).begin();it!=vv.at(i).end();++it) {
            std::cout<<*it<<" ";
        }
        std::cout<<"\n";
    }
    std::cout<<"--------the total rows of the 2DVector is "<<vv.size()<<std::endl;
    std::cout<<"--------the total cols of the 2DVector is "<<vv.front().size()<<std::endl;
}
int main() {
    std::string file("Iris.csv"), weight("theta.csv");;
    std::vector<std::vector<double> > vv_iris;
    std::vector<std::vector<double> > theta;
    ReadDataFromCsv(file, vv_iris);
    ReadMatFromFile(weight, theta);
    Display2DVector(vv_iris);
    Display2DVector(theta);
    double old_cost=CostFunc(vv_iris, theta);
    std::cout<<"the orignal cost: "<<old_cost<<std::endl;
    for(;;) {
        for(size_t i=0; i<theta.size(); ++i) {
            std::vector<double> grad_theta(theta.front().size(), 0);
            GetThetaGrad(vv_iris, theta, i, grad_theta);
            for(size_t j=0; j<grad_theta.size(); ++j) {
                theta.at(i).at(j)=theta.at(i).at(j)-0.05*grad_theta.at(j);
            }
        }
        double new_cost=CostFunc(vv_iris, theta);
        std::cout<<"new_cost: "<<new_cost<<std::endl;
        if(fabs(new_cost-old_cost)<0.000000001)
            break;
        old_cost=new_cost;
    }
    Display2DVector(theta);
    return 0;
}

softmax regression in c++的更多相关文章

  1. Softmax回归(Softmax Regression)

    转载请注明出处:http://www.cnblogs.com/BYRans/ 多分类问题 在一个多分类问题中,因变量y有k个取值,即.例如在邮件分类问题中,我们要把邮件分为垃圾邮件.个人邮件.工作邮件 ...

  2. (六)6.10 Neurons Networks implements of softmax regression

    softmax可以看做只有输入和输出的Neurons Networks,如下图: 其参数数量为k*(n+1) ,但在本实现中没有加入截距项,所以参数为k*n的矩阵. 对损失函数J(θ)的形式有: 算法 ...

  3. Deep Learning 学习随记(三)续 Softmax regression练习

    上一篇讲的Softmax regression,当时时间不够,没把练习做完.这几天学车有点累,又特别想动动手自己写写matlab代码 所以等到了现在,这篇文章就当做上一篇的续吧. 回顾: 上一篇最后给 ...

  4. UFLDL实验报告1: Softmax Regression

    PS:这些是今年4月份,跟斯坦福UFLDL教程时的实验报告,当时就应该好好整理的…留到现在好凌乱了 Softmax Regression实验报告 1.Softmax Regression实验描述 So ...

  5. ufldl学习笔记和编程作业:Softmax Regression(softmax回报)

    ufldl学习笔记与编程作业:Softmax Regression(softmax回归) ufldl出了新教程.感觉比之前的好,从基础讲起.系统清晰,又有编程实践. 在deep learning高质量 ...

  6. 学习笔记TF024:TensorFlow实现Softmax Regression(回归)识别手写数字

    TensorFlow实现Softmax Regression(回归)识别手写数字.MNIST(Mixed National Institute of Standards and Technology ...

  7. TensorFlow实战之Softmax Regression识别手写数字

         关于本文说明,本人原博客地址位于http://blog.csdn.net/qq_37608890,本文来自笔者于2018年02月21日 23:10:04所撰写内容(http://blog.c ...

  8. R︱Softmax Regression建模 (MNIST 手写体识别和文档多分类应用)

    本文转载自经管之家论坛, R语言中的Softmax Regression建模 (MNIST 手写体识别和文档多分类应用) R中的softmaxreg包,发自2016-09-09,链接:https:// ...

  9. TensorFlow(2)Softmax Regression

    Softmax Regression Chapter Basics generate random Tensors Three usual activation function in Neural ...

  10. 逻辑回归与神经网络还有Softmax regression的关系与区别

    本文讨论的关键词:Logistic Regression(逻辑回归).Neural Networks(神经网络) 之前在学习LR和NN的时候,一直对它们独立学习思考,就简单当做是机器学习中的两个不同的 ...

随机推荐

  1. poj1091:跳蚤【容斥原理】

    题目大意:中文题就不翻译了 思路:假设跳蚤选择X1个第一张卡片,X2个第二张卡片...Xn个第n张卡片,Xn+1张写着m的卡片,那么就可以列出方程:a1*X1+a2*X2+…+an*Xn+m*X(n+ ...

  2. Java调用K3Cloud的密码加密算法实现登录密码检验

    背景: 最近要开始做K3Cloud移动,BOS平台的移动单据收费,就想单独做移动模块,搭建环境:后台SSH2,前端Android.在手机端登录时通过Ajax方式传递用户名和密码到后台校验,后台在去K3 ...

  3. Java开发笔记(一百)线程同步synchronized

    多个线程一起办事固然能够加快处理速度,但是也带来一个问题:两个线程同时争抢某个资源时该怎么办?看来资源共享的另一面便是资源冲突,正所谓鱼与熊掌不可兼得,系统岂能让多线程这项技术专占好处?果然是有利必有 ...

  4. linux显示系统时间

    date   查看系统时间 设置系统时间 # date --set “09/17/10 11:50" (月/日/年时:分:秒) # clock –systohc  将系统时间写入硬件时间

  5. 通过grub硬盘安装centos7

    centos7与centos6.x有了很大的不同,从硬盘安装的方法也有了很大的不同,故出此文章我机器环境如下:    有俩系统 Win7 和 RHEL6.4 ,是通过grub(非grub2)引导的,g ...

  6. 从头认识Spring-3.1 简单的AOP日志实现-某方法之前的前后记录日志

    这一章节我们引入简单的AOP日志实现. 1.domain 蛋糕类: package com.raylee.my_new_spring.my_new_spring.ch03.topic_1_1; pub ...

  7. 【Mongodb教程 第一课 】 MongoDB下载安装

    MongoDB是一个高性能,开源,无模式的文档型数据库,是当前NoSql数据库中比较热门的一种.它在许多场景下可用于替代传统的关系型数据库或键/值存储方式.Mongo使用C++开发.以window平台 ...

  8. 五分钟搭建 Flash 视频直播站

    想在家里对全世界直播网络视频节目吗?如今视频网站是多如牛毛,但能让你玩直播的估计没几个吧?看完这篇教程就能帮你实现网络主持人的梦想.不花钱,不懂编程,不用写代码也行哦~ 首先是最低机器要求:Windo ...

  9. LoadRunner系列之—-01 接口压力测试脚本

    LoadRunner中一般用如下函数进行接口测试: <一>. http或soap协议下的get请求接口,样例如下: web_url("integrated_query.jsp&q ...

  10. 责任链模式的具体应用 ServiceStack.Redis订阅发布服务的调用

    责任链模式的具体应用   1.业务场景 生产车间中使用的条码扫描,往往一把扫描枪需要扫描不同的条码来处理不同的业务逻辑,比如,扫描投入料工位条码.扫描投入料条码.扫描产出工装条码等,每种类型的条码位数 ...