方法来自Andrew Ng的Machine Learning课件的note1的PartII,Classification and logsitic regression.
实验表明,通过多次迭代,能够最大化Likehood,使得分类有效,实验数据为人工构建,没有实际物理意义,matrix的第一列为x0,取常数1,第二列为区分列,第三列,第四列为非区分列,最后对预测起到主导地位的参数是theta[0]和theta[1]。
- #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 ",j,function_g(xi));
- sum += result[j]*log(function_g(xi)) + (1-result[j])*log(1-function_g(xi)) ;
- }
- printf("%f ",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 ",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 ",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 ",sum);
- printf("************************************ ");
- }
- return 0;
- }