天天看點

Machine Learning系列實驗--Logistic function解決分類問題

分類問題的值是離散的,差別于之前的線性回歸問題。本次采用Logistic回歸來解決分類問題,實驗還是參考了pennyliang的http://blog.csdn.net/pennyliang/article/details/7045372#comments。 Logistic回歸問題的

Machine Learning系列實驗--Logistic function解決分類問題

,寫出likelihood function

Machine Learning系列實驗--Logistic function解決分類問題
Machine Learning系列實驗--Logistic function解決分類問題

,目标是使得l()最大化。可采用梯度上升方法進行疊代,但不同的是求最大值。

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;

double h(double* x,double* q)
{
	double temp = q[0] * x[0] + q[1] * x[1] + q[2] * x[2] + q[3] * x[3];
	double e = pow(2.718281828, temp);
	return e / (e + 1);
}

void classifier(double* pre)
{
	double x[6][4]={{1,47,76,24},   
		{1,46,77,23},  
		{1,48,74,22},  
		{1,34,76,21},  
		{1,35,75,24},  
		{1,34,77,25},  
	};  

	double y[]={1,1,1,0,0,0};  
	double theta[]={1,1,1,1};

	int i, j, k;
	double l;
	for (i = 0; i < 10000; i++)
	{
		for (j=0; j<4; j++)
		{
			double sum=0;
			for (k = 0; k < 6; k++)
			{
				sum += (y[k] - h(x[k], theta)) * x[k][j];
			}
			theta[j] += 0.001 * sum;
			cout << theta[j] << " ";
		}
		cout << endl;
		
		l = 0;
		for (j = 0; j < 6; j++)
		{
			l += y[j] * log(h(x[j], theta)) + (1 - y[j]) * log(1 - h(x[j], theta));
		}
		//cout<< l << endl;
	}
	cout << i << endl;
	cout << h(pre, theta) << endl;
	cout << l << endl;

}
int main(void)
{
	double pre[] = {1, 48 ,74, 22};
	classifier(pre);
	return 0;
}
           

試驗中選擇了一個學習樣本進行測試,得到的h(x)=0.999984, 相似的極高,若填入的測試資料為其他,可根據h(x)值的大小進行判斷y值是0還是1.

繼續閱讀