c++实现logistic回归代码
测试题目:
代码说明:
1.在main中我用了一个输入文件来表示输入,测试时应去除
2.以下函数分别是计算预测值,计算costfunction,罗辑回归的执行
3.具体类似于线性回归,可参考线性回归之梯度下降
代码如下:
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #include<vector> #include<iostream> using namespace std; double hypothesis(vector<double> &feature,vector<double>&w){ double sum=0.0; for(int i=0;i<feature.size();i++){ sum+=w[i]*feature[i]; } return 1/(1+exp(-sum)); } double cost_fuction(vector<vector<double> > &feature_sample,vector<double> &w,vector<double>&lable){ double sum=0.0; for(int i=0;i<lable.size();i++){ sum+=-lable[i]*log(hypothesis(feature_sample[i],w))-(1-lable[i])*log(1-hypothesis(feature_sample[i],w)); } return sum/lable.size(); } void logic_regression(vector<vector<double> >&feature_sample,vector<double> &lable,vector<double> &w,double a){ vector<double> delta_w; for(int j=0;j<feature_sample[0].size();j++){ double sum=0.0; for(int i=0;i<lable.size();i++){ sum+=(hypothesis(feature_sample[i],w)-lable[i])*feature_sample[i][j]; } delta_w.push_back(sum/lable.size()*a); } for(int i=0;i<w.size();i++){ w[i]-=delta_w[i]; } cout<<cost_fuction(feature_sample,w,lable)<<endl; } int main(){ freopen("in.txt","r",stdin); int feature_num,training_num,t; double a; cin>>feature_num>>training_num>>a>>t; vector<vector<double> >feature_sample; vector<double> tem; vector<double> lable; vector<double> w; double m; for(int i=0;i<training_num;i++){ tem.clear(); tem.push_back(1); for(int j=0;j<feature_num;j++){ cin>>m; tem.push_back(m); } cin>>m; lable.push_back(m); feature_sample.push_back(tem); } for(int i=0;i<=feature_num;i++) w.push_back(0); while(t--) logic_regression(feature_sample,lable,w,a); for(int i=0;i<=feature_num;i++) cout<<w[i]<<" "; return 0; }
运行结果解图
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。