單層感知機實現或運算


慢慢發現,百度上很多東西都沒有,還是得自己去寫,代碼很簡單,慢慢看就容易看懂,建議看之前,先看這篇文章

轉載請注明:http://www.cnblogs.com/gambler/p/9039607.html

#include<bits/stdc++.h>
using namespace std;
#define MAX_SIZE 1000000

//或運算結果圖
//0 0 0
//1 0 1
//0 1 0
//1 1 0
//
int expdata[MAX_SIZE][2];//訓練數據
double w[2];//權值
double jud;//閾值
double spe;//訓練速率
int    Y=0;//實際輸出值
int    M;//理論輸出值
int    N;//表示有多少組數據
void init(void){//初始化數據
    cout<<"請輸入初始權值:"<<endl;
    cin>>w[0]>>w[1];
    cout<<"請輸入初始閾值和訓練速率:"<<endl;
    cin>>jud>>spe;
    cout<<"開始訓練!"<<endl;
    freopen("input.txt","r",stdin);
    cin>>N;
    int j;
    for(j=0;j<N;j++){
        cin>>expdata[j][0]>>expdata[j][1];
    }
}

int T(int a,int b){
    if(a==1||b==1){
            return 1;
    }else{
        return 0;
    }
}

//加權修正公式為:w[i]=w[i]+spe*(T-Y)*x
void weighteinterpolation(int a,int b){
    w[0]=w[0]+spe*(M-Y)*a;
    w[1]=w[1]+spe*(M-Y)*b;
}

void display(int a){
    cout<<""<<a+1<<"次訓練:"<<endl;
    cout<<"輸入:  X0="<<expdata[a][0]<<"\tX1="<<expdata[a][1]<<endl;
    cout<<"權值:  w[0]="<<w[0]<<"\tw[1]="<<w[1]<<endl;
    cout<<"理論值:M="<<M<<"\ts實際值="<<Y<<endl;

}

void trainperceptron(){//進行訓練
    int result=0;
    int i;
    for(i=0;i<N;i++){
        result=w[0]*expdata[i][0]+w[1]*expdata[i][1]-jud;
        if(result<=0){
            Y=0;
        }else{
            Y=1;
        }
        M=T(expdata[i][0],expdata[i][1]);
        if(T(expdata[i][0],expdata[i][1])!=Y){
        weighteinterpolation(expdata[i][0],expdata[i][1]);
        }
        display(i);
    }

}

void show(){
    cout<<"訓練結束!!!"<<endl;
    cout<<"訓練后的權值是:"<<endl;
    cout<<"w[0]:"<<w[0]<<"\tw[1]:"<<w[1]<<endl;
}

int main(){
    init();
    trainperceptron();
    show();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM