欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何运用逻辑回归解决分类问题

最编程 2024-07-25 14:34:44
...
  • #include "stdio.h"  
  • #include "math.h"  
  •   
  • double matrix[6][4]={{1,47,76,24}, //include x0=1  
  •               {1,46,77,23},  
  •               {1,48,74,22},  
  •               {1,34,76,21},  
  •               {1,35,75,24},  
  •               {1,34,77,25},  
  •                 };  
  •   
  • double result[]={1,1,1,0,0,0};  
  • double theta[]={1,1,1,1}; // include theta0  
  •   
  • double function_g(double x)  
  • {  
  •         double ex = pow(2.718281828,x);  
  •         return ex/(1+ex);  
  • }  
  • int main(void)  
  • {  
  •         double likelyhood = 0.0;  
  •         float sum=0.0;  
  •         for(int j = 0;j<6;++j)  
  •         {  
  •                 double xi = 0.0;  
  •                 for(int k=0;k<4;++k)  
  •                 {  
  •                         xi += matrix[j][k]*theta[k];  
  •                 }  
  •                 printf("sample %d,%f\n",j,function_g(xi));  
  •                 sum += result[j]*log(function_g(xi)) + (1-result[j])*log(1-function_g(xi)) ;  
  •         }  
  •         printf("%f\n",sum);  
  •   
  •         for(int i =0 ;i<1000;++i)  
  •         {  
  •                 double error_sum=0.0;  
  •                 int j=i%6;  
  •                 {  
  •                         double h = 0.0;  
  •                         for(int k=0;k<4;++k)  
  •                         {  
  •                                 h += matrix[j][k]*theta[k];  
  •   
  •                         }  
  •                         error_sum = result[j]-function_g(h);  
  •                         for(int k=0;k<4;++k)  
  •                         {  
  •                                 theta[k] = theta[k]+0.001*(error_sum)*matrix[j][k];  
  •                         }  
  •                 }  
  •                 printf("theta now:%f,%f,%f,%f\n",theta[0],theta[1],theta[2],theta[3]);  
  •                 float sum=0.0;  
  •                 for(int j = 0;j<6;++j)  
  •                 {  
  •                         double xi = 0.0;  
  •                         for(int k=0;k<4;++k)  
  •                         {  
  •                                 xi += matrix[j][k]*theta[k];  
  •   
  •                         }  
  •                         printf("sample output now: %d,%f\n",j,function_g(xi));  
  •                         sum += result[j]*log(function_g(xi)) + (1-result[j])*log(1-function_g(xi)) ;  
  •                 }  
  •                 printf("maximize the log likelihood now:%f\n",sum);  
  •                 printf("************************************\n");  
  •         }  
  •         return 0;  
  • }  
  •                           
  • 推荐阅读