Пример #1
0
double NeuralNet::train(cube x,cube y, double alpha, long int epoch){
    
    double cst = 0 ;
    int rnd = 0;
    cube sample_x;
    cube sample_y;

    for(int i=0; i < epoch; i++){
        rnd = rand() % (x.n_slices - 1);
        sample_x =(x.slices(rnd, rnd));
        sample_y =(y.slices(rnd, rnd));
        cst = computeCost(sample_x, sample_y);
        backprop(sample_x, sample_y);
        updateWeights(alpha);
        cout << "Epoch[" << i << "]: " << cst << endl;
    }


    
    double total = 0;
    double ctotal = 0;
    for(int i=0; i < x.n_slices; i++){
        sample_x = (x.slices(i,i));
        sample_y = (y.slices(i,i));
        cst = computeCost(sample_x, sample_y);
        total += cst;
        
        // classification error:
        uword rid, cid, sid;
        cube p = pred(sample_x);
        p.max(rid,cid,sid);
        if(sample_y(rid,cid,sid) == 1)
            ctotal++;   
    }
    total  /= x.n_slices;
    ctotal /= x.n_slices;
    cout << "Mean Training Error: " << total << endl;
    cout << "Classification Error: " << ctotal << endl;
    return 0;
}
void white(const mat& x1, const mat& x2, const uvec& sti, const cube& matphi1, const cube& matphi2, cube& wX, const uvec& End, const uvec & wEnd){
	int T = x1.n_rows, L = matphi1.n_slices, P = x1.n_cols, m = End.n_elem-1;
	mat multiply(P,P);
	cube X(3*P,P,T);
	for(int t=0;t<T;t++){
		X.slice(t)=join_cols(join_cols(diagmat(x1.row(t)),diagmat(x2.row(t))),diagmat(ones(1,P)));
	}
	for(int run=0;run<m;run++){
		wX.slices(wEnd[run],wEnd[run+1]-1) = X.slices(End[run]+L,End[run+1]-1);
		if(L>0){
			for(unsigned int t=End[run]+L;t<End[run+1];t++){
				for(int l=0;l<L;l++){
					multiply = sti[t-l-1]?(matphi1.slice(l)):(matphi2.slice(l));
					wX.slice(t-L*(run+1)) -= X.slice(t-l-1)*multiply;
				}
			}
		}
	}
}
void white(const mat& Hc, const rowvec vec_beta, const uvec& sti, const cube& matphi1, const cube& matphi2, cube& wHX, const uvec& End, const uvec & wEnd){
	int T = Hc.n_rows, J = Hc.n_cols/2, L = matphi1.n_slices, P = matphi1.n_rows, m = End.n_elem-1;
	mat multiply(P,P);
	cube X = zeros(J*P,P,T);
	for(int t=0;t<T;t++){
		for(int p=0; p<P;p++){
			X.slice(t).col(p).rows(J*p, J*(p+1)-1) = trans(Hc.submat(t, 0, t, J-1))*vec_beta[p] + trans(Hc.submat(t, J, t, 2*J-1))*vec_beta[P+p];
		}
	}
	for(int run=0;run<m;run++){
		wHX.slices(wEnd[run],wEnd[run+1]-1) = X.slices(End[run]+L,End[run+1]-1);
		if(L>0){
			for(unsigned int t=End[run]+L;t<End[run+1];t++){
				for(int l=0;l<L;l++){
					multiply = sti[t-l-1]?(matphi1.slice(l)):(matphi2.slice(l));
					wHX.slice(t-L*(run+1)) -= X.slice(t-l-1)*multiply;
				}
			}
		}
	}

}