User:Cortiz

From Noisebridge
Jump to: navigation, search

C code for the machine learning class 03/11/09

I used a different scale than the rest of the class. I worked entirely with integers, threshold is 500.

Scroll down for partial output. cheers.

/*=================================================================
Author:         Cristian Ortiz (co.ortiz@gmail.com)
Description:    Coded for the perceptron class @noisebridge. peace.
===================================================================*/

#include <stdio.h>
#include <stdlib.h>

int dot_prod(int * A, int * B, int n){
    int i=0;
    int R=0;
    for(i=0;i<n;i++){
        R+=A[i]*B[i];
    }
    return R;
}
int * sca_prod(int * A, int n, int x){
    int i=0;
    int * R;
    for(i=0;i<n;i++){
        R[i]=A[i]*x;
    }
    return R;
}
int main(void) {
    int input_vec[]={1,0,0,1,0,1,1,1,0,1,1,1};
    int expected[]={1,1,1,0};
    int input_offset=0;
    int w_vec[]={1,1,1};
    int learned=0;
    int i=0;
    int output=0;
    int dot_result=0;
	int * pvec;
	int th=500;
    int adjust=0;	
    
    while (learned!=4){
        //printf("input offset: %d\n", input_offset);
        pvec=input_vec+(input_offset*3);
        dot_result=dot_prod(pvec, w_vec, 3);
        output=(dot_result>th);
        printf("ouput: %d supposed to be %d", output, expected[input_offset]);
        
        if(output==expected[input_offset]){printf("\t\t\t<OK!>\n");}
        else {printf("\t\t\t<Miss!>\n");}
        
        if(output>expected[input_offset]){adjust=-1;}
        else if (output<expected[input_offset]){adjust=1;}
        else { learned++; }
        
        if(output!=expected[input_offset]){
            for(i=0;i<3;i++){
            	w_vec[i]=w_vec[i]+(input_vec[i+input_offset*3]*(adjust));
            	printf("new w_vec[%d]: %d\n", i, w_vec[i]);	
            }
            learned=0;
        }
        input_offset=(input_offset==3)?0:input_offset+1;
    }
    for(i=0;i<3;i++){
        printf("Final w_vec[%d]=%d\n", i, w_vec[i]);
    }
    return 0;
}

Last 20 lines of output:

ouput: 0 supposed to be 1			<Miss!>
new w_vec[0]: 503
new w_vec[1]: -1
new w_vec[2]: -1
ouput: 1 supposed to be 0			<Miss!>
new w_vec[0]: 502
new w_vec[1]: -2
new w_vec[2]: -2
ouput: 1 supposed to be 1			<OK!>
ouput: 0 supposed to be 1			<Miss!>
new w_vec[0]: 503
new w_vec[1]: -2
new w_vec[2]: -1
ouput: 1 supposed to be 1			<OK!>
ouput: 0 supposed to be 0			<OK!>
ouput: 1 supposed to be 1			<OK!>
ouput: 1 supposed to be 1			<OK!>
Final w_vec[0]=503
Final w_vec[1]=-2
Final w_vec[2]=-1

Personal tools