package svm.instances.binary;

import java.util.ArrayList;
import java.util.Arrays;

import svm.Mode;
import svm.SVMStruct;
import svm.SVMStructKernel;
import base.DenseVector;
import base.Example;

public class BinaryClassificationProblem
{
	public static void main(String[] args)
	{

		ArrayList<Example<DenseVector, BinaryLabel>> train = new ArrayList<>();
		double[] w =new double[]{1,-2};
		// new double[2]
//		for (int i = 0; i < 2; i++)
//		{
//			w[i] = Math.random()-0.5;
//		}
		for (int i = 0; i < 1000; i++)
		{
			DenseVector x = new DenseVector(2);
			double s = 0;
			for (int j = 0; j < x.length(); j++)
			{
				x.x[j] = Math.random()*2-1;
				System.out.print(x.x[j]+",");
				s += x.x[j] * w[j];
			}
			
			
			BinaryLabel y;
			if(s<0) y = BinaryLabel.ypos();
			else y = BinaryLabel.yneg();
			if(Math.random()<0.1)
				y.y*=-1;
			System.out.println("\t"+y.y);
			Example<DenseVector, BinaryLabel> p = new Example<DenseVector, BinaryLabel>(x, y);
			p.i = i;
			train.add(p);
		}

		SVMStruct<DenseVector, BinaryLabel> svmstruct = new SVMStruct<DenseVector, BinaryLabel>(new BinaryClassificationInstance(), 10000, 0.0001, Mode.MARGIN_RESCALING);
		svmstruct.train(train);
		
		System.out.println("================================");
		
		SVMStructKernel<DenseVector, BinaryLabel> svmstructKernel = new SVMStructKernel<DenseVector, BinaryLabel>(new BinaryClassificationKernelInstance(), 10000, 0.0001, Mode.MARGIN_RESCALING);
		svmstructKernel.train(train);
		double[] w2 =new double[w.length];
		int n = svmstructKernel.data.size();
		for(int i=0;i<svmstructKernel.alphas.size();i++)
		{
			for(int j=0;j<svmstructKernel.data.size();j++)
			{
				//Example<DenseVector,BinaryLabel> e = svmstructKernel.data.get(j);
				for(int d = 0;d<w2.length;d++)
				{
					w2[d]+=1.0/n*svmstructKernel.alphas.get(i)*svmstructKernel.data.get(j).x.x[d]*(svmstructKernel.data.get(j).y.y-svmstructKernel.constraints.get(i).ybar.get(j).y);
				}
			}
		}
		for(int d = 0;d<w2.length;d++)
			w2[d]/=w[d];
		System.out.println(Arrays.toString(w2));
	}
}
