pair <pair<double,vector<int>>, pair<double,vector<int>>> cross(pair<double,vector<int>> chromosome1, pair<double,vector<int>> chromosome2, vector<Data> train){ int n = chromosome1.second.size(); int v1 = Randint(0, n-1); int v2 = Randint(0, n-1); int min, max; vector<int> chromosome1_vector = chromosome1.second, chromosome2_vector = chromosome2.second; vector<int> song_1, song_2; if(v1 < v2){ min = v1; max = v2; } else{ min = v2; max = v1; } for (int i = 0; i < n; i++) { if (i <= min) { song_2.push_back(chromosome1_vector.at(i)); song_1.push_back(chromosome2_vector.at(i)); } else if (i > min && i < max) { song_1.push_back(chromosome1_vector.at(i)); song_2.push_back(chromosome2_vector.at(i)); } else if (i >= max) { song_2.push_back(chromosome1_vector.at(i)); song_1.push_back(chromosome2_vector.at(i)); } } return pair <pair<double,vector<int>>, pair<double,vector<int>>>(pair<double,vector<int>>(tasa_clas(song_1, train, train),song_1), pair<double,vector<int>>(tasa_clas(song_2, train, train),song_2)); }
void chromosome::remRule() { unsigned** matappo=new unsigned*[numRul]; int realRule; int numero; unsigned* appo; for (int i=0;i<numRul;i++) { matappo[i]=new unsigned[numVar]; for (int j=0;j<numVar;j++) matappo[i][j]=matR[i][j]; } realRule = deleteDup(matappo, numRul); //Eliminating the duplicates form the chromosome appo if (realRule>minRule) { numero=Randint(0,numRul-1); appo=matR[numero]; matR[numero]=matR[numRul-1]; matR[numRul-1]=appo; numRul--; } for (int i=0;i<numRul;i++) delete[] matappo[i]; delete[] matappo; }
vector<int> sol_random(int size){ vector<int> s; for(int i = 0; i < size; i++){ s.push_back(Randint(0,1)); } return s; }
void Mutate () { static int bits; /* number of bits per pop */ register int i; /* index of the Mutated structure */ register int j; /* position within the structure */ register char k; /* a random allele */ register int open; /* currently Unpacked Gene */ static int firstflag = 1; Trace("Mutate entered"); if (firstflag) { bits = Gapsize*Popsize*Length + 0.5; firstflag = 0; } if (M_rate > 0.0) { open = -1; while (Mu_next<bits) { i = Mu_next/ Length; /* Mutated structure */ j = Mu_next % Length; /* Mutated position */ if (open != i) { /* need to Unpack structure i */ Unpack (New[i].Gene , Bitstring, Length); open = i; } /* choose a random allele */ if (Randint(0,1)) k = '1'; else k = '0'; if (k != Bitstring[j]) { /* it's an effective mutation */ Bitstring[j] = k; New[i].Needs_evaluation = 1; } if (New[i].Needs_evaluation) Pack ( Bitstring , New[i].Gene , Length); /* update next mutation location */ if (M_rate < 1.0) Mu_next += ceil (log(Rand()) / log(1.0 - M_rate)); else Mu_next += 1; } /* adjust Mu_next for next Generation */ Mu_next -= bits; } Trace("Mutate completed"); } /* end Mutate */
//genera la matrice matR dopo aver generato la matrice di WM (Per la regressione) void chromosome::generateMatR(frbs& fis) { matR = new unsigned*[maxRule]; for (int i=0;i<maxRule;i++) matR[i]=new unsigned [numVar]; int maxDim; numRul=0; double peso; if (maxRule>=dimMatWM) //la matrice di WM ci va tutta!! { for (int j=0;j<dimMatWM;j++) { for (int k=0;k<numVar;k++) matR[numRul][k]=matWM[j][k]; //addDC(matR[numRul]); peso=fis.calcolaPeso((int*)matR[numRul],inOutTr,numPatterTr,realPart,pwLT); if (peso<=0) for (int k=0;k<numVar;k++) matR[numRul][k]=matWM[j][k]; else pesi[numRul]=peso; numRul++; } } else { int numRegxClasse=maxRule/numParts[numVar-1]; for (int i=0;i<numParts[numVar-1];i++) { if (indiciCL[i]>0) { if (numRegxClasse<indiciCL[i]) maxDim=numRegxClasse; else maxDim=indiciCL[i]; int indice; int indmin; if (i==0) indmin=0; else indmin=indiciCL[i-1]; for (int j=0;j<maxDim;j++) { indice=Randint(0,indiciCL[i]-1); for (int k=0;k<numVar;k++) matR[numRul][k]=matWM[indice+indmin][k]; //addDC(matR[numRul]); peso=fis.calcolaPeso((int*)matR[numRul],inOutTr,numPatterTr,realPart,pwLT); if (peso<=0) for (int k=0;k<numVar;k++) matR[numRul][k]=matWM[indice+indmin][k]; else pesi[numRul]=peso; numRul++; } } } } }
/************************************************************* ************************************************************* One-point crossover for the virtual RB ************************************************************* **************************************************************/ void crossRB(chromosome& par1, chromosome& par2, chromosome& suc1, chromosome& suc2) { int i, minVal, cut; suc1.numRul = par2.numRul; suc2.numRul = par1.numRul; for (i = 0; i < maxRule; i++) for (int j = 0; j < numVar; j++) { suc1.matR[i][j] = par1.matR[i][j]; suc2.matR[i][j] = par2.matR[i][j]; } if (par1.numRul != 1) { if (par2.numRul != 1) minVal = minN(par1.numRul - 1, par2.numRul - 1); else //par2->numRul==1 minVal = minN(par1.numRul - 1, par2.numRul); } else //par1->numRul==1 { if (par2.numRul != 1) minVal = minN(par1.numRul, par2.numRul - 1); else //par2->numRul==1 minVal = minN(par1.numRul, par2.numRul); // These nested if should ensure that the sons are different from parents if the number of genes of both parents are >1 } cut = Randint(minRule, minVal); for (i = cut; i < maxRule; i++) for (int j = 0; j < numVar; j++) { suc1.matR[i][j] = par2.matR[i][j]; suc2.matR[i][j] = par1.matR[i][j]; } suc1.numRul = suc1.deleteDup(suc1.matR, suc1.numRul); suc2.numRul = suc2.deleteDup(suc2.matR, suc2.numRul); if (suc1.numRul < minRule) suc1.copyChrom(par1); if (suc2.numRul<minRule) suc2.copyChrom(par2); if ((suc1.numRul == 0) || (suc2.numRul == 0)) cout << "One-point crossover error: son with 0 rule" << endl; }
/************************************************************* ************************************************************* Mutation for the granularity part ************************************************************* **************************************************************/ void chromosome::MutacionGR() { int g, k; //, maxpart; if (CLASSIFICATION) g = Randint(0, numVar - 2); //Selecting the linguistic variable else g = Randint(0, numVar - 1); int oldGran=realPart[g]; if (realPart[g] == MINPART) { realPart[g]++; return; } if (realPart[g] == numParts[g]) { realPart[g]--; } else { if (Rand() < 0.85) //increasing granularity { if(realPart[g]!=numParts[g]) { k = Randint(realPart[g] + 1, numParts[g]); realPart[g] = k; } } else //decreasing granularity { k = Randint(MINPART, realPart[g] - 1); realPart[g] = k; } } if (g==numVar-1 && realPart[g]==1) { realPart[g]=oldGran; return; } //int conta=0; }
/************************************************************* ************************************************************* Modifies a term in the virtual RB ************************************************************* **************************************************************/ void chromosome::modRule() { int m, f, numNoZero; chromosome app(*this); m = Randint(0, numRul - 1); //selecting the rule index if (!CLASSIFICATION) f = Randint(0, numVar - 1); //selecting the linguistic variable else f = Randint(0, numVar - 2); numNoZero = countNoZero(app.matR[m], numVar - 1); if (f == (numVar - 1)) //the consequent was selected app.matR[m][f] = Randint(1,realPart[numVar-1]); else //we are in an antecedent condition { if (numNoZero > minTerms && numNoZero < numVar-1)//no problems with the constrains { if (Rand()<=0.7) app.matR[m][f]=0; else app.matR[m][f] = Randint(1, realPart[f]); } else { if (numNoZero == minTerms)//limit condition on the minimum number of conditions { if (app.matR[m][f] == 0) app.matR[m][f] = Randint(0, realPart[f]); else app.matR[m][f] = Randint(1, realPart[f]);//the minimum number of rules will be saved } else //numNoZero==maxTerms: limit condition on the maximum number of conditions { if (Rand()<=0.5) app.matR[m][f]=0; else app.matR[m][f] = Randint(1, realPart[f]); } } }// end extern else app.numRul = app.deleteDup(app.matR, app.numRul); if (app.numRul >= minRule) { copyChrom(app); } }
void genera_sol_random(int *sol, int n_unidades){ int pos, aux; for(int i=0; i<n_unidades; i++) sol[i] = i+1; for(int j=0; j<n_unidades; j++){ pos = Randint(j,n_unidades-1); aux=sol[j]; sol[j]=sol[pos]; sol[pos]=aux; } }
/************************************************************* ************************************************************* Mutation for the piecewise ************************************************************* **************************************************************/ void chromosome::MutacionPW() { int g, h; int min1, max1; //range of variability of pwLT[i][j] int appo; double appo1; int ingressi=numVar; if (CLASSIFICATION) ingressi--; g = Randint(0, ingressi - 1); //selecting the variable to mutate if (numParts[g]==2) return; h = Randint(0, numParts[g]-3); //selecting the piece to mutate if (h == 0 || vinc) //the second fuzzy set min1 = pwLT_lim[0][g][h] * GrDig; else min1 = pwLT[g][h - 1] * GrDig; if (h == numParts[g]-2 - 1 || vinc) //the next-to-last fuzzy set max1 = pwLT_lim[1][g][h] * GrDig; else max1 = pwLT[g][h + 1] * GrDig; appo = Randint(min1, max1); appo1 = pwLT[g][h]; pwLT[g][h] = (double) appo / GrDig; //to eliminate duplicate pwLT[][] for (int i = 0; i < numParts[g]-2; i++) if (i != h && abs(pwLT[g][h] - pwLT[g][i]) < (double) (1 / GrDig)) { pwLT[g][h] = appo1; break; } }
pair<double, vector<int>> selectBestChromosome(multimap<double,vector<int>> chromosomes){ int n = chromosomes.size(); vector<int> numbers = vector_random(n); int pos_random = Randint(0,n-2); int max = numbers.at(pos_random); if(max < numbers.at(pos_random+1)) max = numbers.at(pos_random+1); multimap<double, vector<int>>::iterator it = chromosomes.begin(); for(int i = 0; i < max; i++) it++; return pair<double, vector<int>>((*it).first, (*it).second); }
void crossWM(chromosome& par1, chromosome& par2, chromosome& suc1,chromosome& suc2) { int i, minVal, cut; suc1.numRul = par2.numRul; suc2.numRul = par1.numRul; for (i = 0; i < maxRule; i++) { suc1.vettR[i].index=par1.vettR[i].index ; suc2.vettR[i].index=par2.vettR[i].index; for (int j = 0; j < numVar-1; j++) { suc1.vettR[i].vectAnt[j]=par1.vettR[i].vectAnt[j]; suc2.vettR[i].vectAnt[j]=par2.vettR[i].vectAnt[j]; } } if (par1.numRul != 1 && par2.numRul != 1) minVal = minN(par1.numRul - 1, par2.numRul - 1); else return; cut = Randint(minRule, minVal); for (i=cut; i < maxRule; i++) { suc1.vettR[i].index = par2.vettR[i].index; suc2.vettR[i].index = par1.vettR[i].index; for (int j = 0; j < numVar-1; j++) { suc1.vettR[i].vectAnt[j] = par2.vettR[i].vectAnt[j]; suc2.vettR[i].vectAnt[j] = par1.vettR[i].vectAnt[j]; } } suc1.ordinaIndex(); suc1.faiMatdaVec(); suc1.deleteDup(); suc2.ordinaIndex(); suc2.faiMatdaVec(); suc2.deleteDup(); if (suc1.numRul<minRule || (CLASSIFICATION && !suc1.controllaPresenzaClassi((int**)suc1.matR,suc1.numRul))) suc1 = par1; if (suc2.numRul<minRule || (CLASSIFICATION && !suc2.controllaPresenzaClassi((int**)suc2.matR,suc2.numRul))) suc2 = par2; }
/************************************************************* ************************************************************* One-point crossover for the partition part ************************************************************* **************************************************************/ void crossPart(chromosome& par1, chromosome& par2, chromosome& suc1, chromosome& suc2)//crosses the partition cromosome { int num = Randint(1, numVar - 1); int i; //crossing the partition cromosome for (i = 0; i < num; i++) { suc1.realPart[i] = par1.realPart[i]; suc2.realPart[i] = par2.realPart[i]; } for (; i < numVar; i++) { suc1.realPart[i] = par2.realPart[i]; suc2.realPart[i] = par1.realPart[i]; } int conta1=0,conta2=0; for (int i=0;i<numVar-1;i++) { if (suc1.realPart[i]>1) conta1++; if (suc2.realPart[i]>1) conta2++; } }
double chromosome::calcolaErroreC45(frbs& fis, double** inOutCamp, int numCamp,bool test, unsigned int** matAppo,int nRegole) { double uscita; fis.createFuzzySet(realPart, pwLT); fis.faiMatAttivazione(inOutCamp,numCamp,realPart,(int**)matAppo,nRegole,pesi,test); double* usc = new double[numCamp]; for (int i = 0; i < numCamp; i++) { int classe = fis.calcolaClasse(pesi,i,(int**)matAppo,nRegole); usc[i]=matAppo[classe][numVar-1]; if (fis.getTutto0() == true) { usc[i]=-1; } } int* numPuntixClasse=new int[numParts[numVar-1]]; int ** matConfusione=new int*[numParts[numVar-1]]; for (int i=0;i<numParts[numVar-1];i++) { numPuntixClasse[i]=0; matConfusione[i]=new int[numParts[numVar-1]]; for (int j=0;j<numParts[numVar-1];j++) matConfusione[i][j]=0; } int noClass=0; for (int i=0;i<numCamp;i++) { numPuntixClasse[(int)inOutCamp[i][numVar-1]-1]++; if (usc[i]!=-1) matConfusione[(int)(inOutCamp[i][numVar-1])-1][(int)usc[i]-1]++; else { while(true) { noClass=Randint(1,numParts[numVar-1]); if (noClass!=inOutCamp[i][numVar-1]) break; } matConfusione[(int)(inOutCamp[i][numVar-1])-1][noClass-1]++; } } int numPunti=0; for (int i=0;i<numParts[numVar-1];i++) { for (int j=0;j<numParts[numVar-1];j++) numPunti+=matConfusione[i][j]; } uscita=0; printMat<int>(matC45,dimmatC45,numVar,cout); cout<<endl; printMat<int>(matConfusione,numParts[numVar-1],numParts[numVar-1],cout); for (int i=0;i<numParts[numVar-1];i++) uscita+=matConfusione[i][i]; uscita/=(double)numCamp; fis. deleteFuzzySet(realPart); return (uscita); }
/************************************************************* ************************************************************* Add a random rule ************************************************************* **************************************************************/ void chromosome::addRule(frbs& fis) { int numNoZero; int flag = 1; unsigned** matappo; int num,num1; realNumRule = numRul; if (CLASSIFICATION) { num=Randint(0,dimMatWM-1); if (numRul<maxRule) { for (int i=0;i<numVar;i++) matR[numRul][i]= matWM[num][i]; //addDC(matR[numRul]); numRul++; } else { num1=Randint(0,maxRule-1); for (int i=0;i<numVar;i++) matR[num1][i]= matWM[num][i]; //addDC(matR[num1]); } numRul = deleteDup(matR, numRul); return; } if (numRul != 0 && ProbVarPartion) //calcolo il concrete RB { matappo = new unsigned*[numRul]; for (int i = 0; i < numRul; i++) { matappo[i] = new unsigned[numVar]; for (int j = 0; j < numVar; j++) matappo[i][j] = matR[i][j]; } convertimat(matappo, fis); realNumRule = deleteDup(matappo, numRul); //Eliminating the duplicates form the chromosome appo } else matappo = matR; if ((ProbVarPartion && realNumRule == maxRule) || (ProbVarPartion == 0 && numRul == maxRule)) { if (matappo != matR) { for (int i = 0; i < numRul; i++) delete[] matappo[i]; delete[] matappo; } return; } unsigned* candidate; while (flag == 1) { candidate = RandintRule(realPart, numVar); //extracting a candidate rule numNoZero = countNoZero(candidate, numVar - 1); if (((numNoZero < minTerms) || (numNoZero > numVar-1)) || (numRul != 0 && trovaVett(candidate, matappo, realNumRule))) { delete[] candidate; continue; }; flag = 0; } if (matappo != matR) { for (int i = 0; i < numRul; i++) delete[] matappo[i]; delete[] matappo; } if (numRul < maxRule) { matR[numRul] = candidate; numRul++; } else { num = Randint(0, numRul - 1); delete[] matR[num]; matR[num] = candidate; } }
/************************************************************* ************************************************************* Initializes a chromosome with random values without adding rule ************************************************************* **************************************************************/ void chromosome::inizializewithoutrule() { rank = 1; crowd_dist = 0; //unsigned maxpart; int ingressi=numVar; numFeat=0; if (CLASSIFICATION) ingressi--; allocateSpace(); float space; bool trovato; for (int i = 0; i < ingressi; i++) { if (TuningPW) { space = (double) 1 / (numParts[i]-2 + 1);// half of support of a fuzzy set in a uniform partition for (int j = 0; j < numParts[i]-2 ; j++) { if (vinc == true) //constrained version { pwLT_lim[0][i][j] = space * (j + 1) - space / 2; pwLT_lim[1][i][j] = space * (j + 1) + space / 2 - (double) 1 / GrDig; //pwLT[i][j] = Randint(pwLT_lim[0][i][j] * GrDig, pwLT_lim[1][i][j] * GrDig); pwLT[i][j]= space*(j+1)*GrDig; pwLT[i][j] /= (double) GrDig; } else { pwLT_lim[0][i][j] = 0.01; pwLT_lim[1][i][j] = 0.99; do { pwLT[i][j] = Randint(1, GrDig - 1); pwLT[i][j] /= (double) GrDig; trovato = false; for (int k = 0; k < j; k++) if (pwLT[i][j] == 0 || pwLT[i][j] == 1 || (j != 0 && abs(pwLT[i][j] - pwLT[i][k]) < (double) (1 / GrDig))) //to ensure that two genes cannot be equal and { trovato = true; break; } } while (trovato); } pwLT_lim[2][i][j] = space * (j + 1);// centroids of the uniform partition in [0,1] } if (!vinc) ordina(pwLT[i], numParts[i]-2 ); } for (int i=0;i<numVar;i++) realPart[i]=numParts[i]; } numRul = realNumRule = 0; for (int i = 0; i < maxRule; i++) for (int j = 0; j < numVar;j++) matR[i][j] = 0; for (int i = 0; i < sizeObjTot; i++) { objTot[i] = 56456465; objAlg[i]=56456465; } }
vector<int> AGG(vector<Data> train){ int n = train.at(0).attributes.size(); vector<int> chromosome; pair<double, vector<int>> elitism; multimap <double, vector<int>> chromosomes_initials, chromosomes_pre_cross, chromosomes_crossed, chromosomes_final; double pc = 0.7; double pm = 0.001; int num_gen_to_mute = pm*30*n; vector<int> gen_to_mute; vector<int> chromosome_to_mute; bool elitism_is; int evaluates = 0; for (int i = 0; i < 30; i++) { for (int j = 0; j < n; j++) chromosome.push_back(Randint(0, 1)); chromosomes_final.insert(pair<double, vector<int>>(tasa_clas(chromosome, train, train), chromosome)); chromosome.clear(); evaluates++; } while(evaluates < 5000) { elitism_is = false; gen_to_mute = vector_random(n); chromosome_to_mute = vector_random(30); chromosomes_initials = chromosomes_final; multimap<double, vector<int>>::iterator best = chromosomes_initials.end(); best--; elitism = *best; //Selection chromosomes_pre_cross.clear(); for (int i = 0; i < 30; i++) chromosomes_pre_cross.insert(selectBestChromosome(chromosomes_initials)); //Cross chromosomes_crossed = cross(chromosomes_pre_cross, pc, train); evaluates+=(30*pc); //Mutation for (int i = n; i > num_gen_to_mute; i--) gen_to_mute.pop_back(); for (int j = 30; j > num_gen_to_mute; j--) chromosome_to_mute.pop_back(); for (int i = 0; i < num_gen_to_mute; i++) { multimap<double, vector<int>>::iterator chromosome_selected = chromosomes_crossed.begin(); for (int j = 0; j < chromosome_to_mute.at(i); j++) chromosome_selected++; pair<double, vector<int>> element = *chromosome_selected; chromosomes_crossed.erase(chromosome_selected); element.second.at(gen_to_mute.at(i)) = (element.second.at(gen_to_mute.at(i)) == 1) ? 0 : 1; chromosomes_crossed.insert(pair<double,vector<int>>(tasa_clas(element.second, train, train), element.second)); evaluates++; } //Select elitism for (multimap<double, vector<int>>::iterator it = chromosomes_crossed.begin(); it != chromosomes_crossed.end() && !elitism_is; it++) { pair<double, vector<int>> element = *it; if (element.first == elitism.first && element.second == elitism.second) elitism_is = true; } if (!elitism_is) { chromosomes_crossed.erase(chromosomes_crossed.begin()); chromosomes_crossed.insert(elitism); } chromosomes_final = chromosomes_crossed; } multimap<double, vector<int>>::iterator best_chromosome = chromosomes_final.end(); best_chromosome--; pair<double, vector<int>> solution_final = *best_chromosome; return solution_final.second; }
vector<int> AGE(vector<Data> train){ int n = train.at(0).attributes.size(); vector<int> chromosome; multimap <double, vector<int>> chromosomes_initials, chromosomes_pre_cross, chromosomes_crossed; double pm = 0.001; int num_gen_to_mute = pm*2*n; vector<int> gen_to_mute; vector<int> chromosome_to_mute; int evaluates = 0; for (int i = 0; i < 30; i++) { for (int j = 0; j < n; j++) chromosome.push_back(Randint(0, 1)); chromosomes_initials.insert(pair<double, vector<int>>(tasa_clas(chromosome, train, train), chromosome)); chromosome.clear(); evaluates++; } while(evaluates < 5000) { //Selection chromosomes_pre_cross.clear(); for (int i = 0; i < 2; i++) chromosomes_pre_cross.insert(selectBestChromosome(chromosomes_initials)); //Cross multimap<double, vector<int>>::iterator it = chromosomes_pre_cross.begin(); it++; pair <pair<double,vector<int>>, pair<double,vector<int>>> chromosomes_songs = cross(*chromosomes_pre_cross.begin(), *it, train); chromosomes_crossed.insert(chromosomes_songs.first); chromosomes_crossed.insert(chromosomes_songs.second); evaluates+=2; //Mutation if(num_gen_to_mute > 0){ gen_to_mute = vector_random(n); for (int i = n; i > num_gen_to_mute; i--) gen_to_mute.pop_back(); for (int j = 0; j < num_gen_to_mute; j++) chromosome_to_mute.push_back(Randint(0, 1)); for (int i = 0; i < num_gen_to_mute; i++) { multimap<double, vector<int>>::iterator chromosome_selected = chromosomes_crossed.begin(); for (int j = 0; j < chromosome_to_mute.at(i); j++) chromosome_selected++; pair<double, vector<int>> element = *chromosome_selected; chromosomes_crossed.erase(chromosome_selected); element.second.at(gen_to_mute.at(i)) = (element.second.at(gen_to_mute.at(i)) == 1) ? 0 : 1; chromosomes_crossed.insert(pair<double,vector<int>>(tasa_clas(element.second, train, train), element.second)); evaluates++; } } for (multimap<double, vector<int>>::iterator it = chromosomes_crossed.begin(); it != chromosomes_crossed.end(); it++) { if((*chromosomes_initials.begin()).first < (*it).first) { chromosomes_initials.erase(chromosomes_initials.begin()); chromosomes_initials.insert(*it); } } } multimap<double, vector<int>>::iterator best_chromosome = chromosomes_initials.end(); best_chromosome--; pair<double, vector<int>> solution_final = *best_chromosome; return solution_final.second; }
/************************************************************* ************************************************************* Calculates the error on the training set and the complexity of the concrete RB - comp returns the complexity of the concrete RB - fis the fis is needed to convert the virtual RB into the concrete RB and to calculate the output - corr return the correlation if activated ************************************************************* **************************************************************/ double* chromosome::ECM(frbs& fis, double** inOutCamp, int numCamp,bool test) { double suma; unsigned** matAppo; bool nocop; double* usc; double output; double* uscCL=new double[10]; int* numPuntixClasse; int** matConfusione; if (CLASSIFICATION); usc=new double[numCamp]; comp = 0; realNumRule = numRul; if (ProbVarPartion != 0 ) //Partition learning { matAppo = new unsigned*[numRul]; for (int i = 0; i < numRul; i++) { matAppo[i] = new unsigned[numVar]; for (int j = 0; j < numVar; j++) matAppo[i][j] = matR[i][j]; } convertimat(matAppo, fis); realNumRule = deleteDup(matAppo, numRul); } else matAppo = matR; numFeat=giveActive(matAppo, realNumRule); for (int i = 0; i < realNumRule; i++) comp += countNoZero(matAppo[i], numVar - 1); //calculating the complexity as sum of the antecedents != 0 if (realNumRule < minRule) return 0; /*cout<<"Matrice da valuare"<<endl; for (int i=0;i<numRul;i++) { for (int j=0;j<numVar;j++) cout<<matR[i][j]<<' '; cout<<endl;*/ fis.createFuzzySet(realPart, pwLT); if (CLASSIFICATION) //calcola i pesi per le regole { fis.faiMatAttivazione(inOutCamp,numCamp,realPart,(int**)matAppo,realNumRule,pesi,test); int k; for (k=0;k<realNumRule;k++) if (pesi[k]> 0) break; if (k==realNumRule) { uscCL[0]=1; uscCL[1] = 0; //TPR uscCL[2] = 1; //FPR uscCL[3] = 0;//AUC return uscCL; } if (TYPE==0) { eliminaPesiNegativi(); //if (numParts[numVar-1]!=2) //controllaClassi(fis); } } suma = 0; int nocop1=0; for (int i = 0; i < numCamp; i++) { nocop = false; if (CLASSIFICATION) { //usc[i]=fis.calcolaClasse(pesi,i,(int**)matAppo,realNumRule); usc[i]=matAppo[fis.calcolaClasse(pesi,i,(int**)matAppo,realNumRule)][numVar-1]; if (fis.getTutto0() == true) { usc[i]=-1; nocop1++; } } else { output = FLC(inOutCamp[i], matAppo, realNumRule, fis, nocop); //calculating the output for each input pattern using the concrete RB suma += 0.5 * pow(inOutCamp[i][numVar - 1] - output, 2.0); //calculating the half of the MSE } } //fis.deleteFuzzySet(realPart); if (matAppo != matR) { for (int i = 0; i < numRul; i++) delete[] matAppo[i]; delete[] matAppo; } if (CLASSIFICATION) { numPuntixClasse=new int[numParts[numVar-1]]; matConfusione=new int*[numParts[numVar-1]]; for (int i=0;i<numParts[numVar-1];i++) { numPuntixClasse[i]=0; matConfusione[i]=new int[numParts[numVar-1]]; for (int j=0;j<numParts[numVar-1];j++) matConfusione[i][j]=0; } int noClass=0; for (int i=0;i<numCamp;i++) { numPuntixClasse[(int)inOutCamp[i][numVar-1]-1]++; if (usc[i]!=-1) matConfusione[(int)(inOutCamp[i][numVar-1])-1][(int)usc[i]-1]++; else { /*if (!test) {*/ while(true) { noClass=Randint(1,numParts[numVar-1]); if (noClass!=inOutCamp[i][numVar-1]) break; } matConfusione[(int)(inOutCamp[i][numVar-1])-1][noClass-1]++; //} } } int numPunti=0; for (int i=0;i<numParts[numVar-1];i++) for (int j=0;j<numParts[numVar-1];j++) numPunti+=matConfusione[i][j]; uscCL[0]=0; for (int i=0;i<numParts[numVar-1];i++) uscCL[0]+=matConfusione[i][i]; uscCL[0]/=(double)numCamp; uscCL[0]=1-uscCL[0]; double TPR,FPR,prob,AUC=0; #ifdef stampa if (test) { cout<<"Errore Test: "<<1-uscCL[0]<<endl<<"Matrice Confusione"<<endl; for (int i=0;i<MAXPARTO;i++) { for (int j=0;j<MAXPARTO;j++) cout<<matConfusione[i][j]<<' '; cout<<endl; } } #endif if (numParts[numVar-1]==2) //0 positivi 1 negativi { uscCL[2] = (double)matConfusione[1][0]/numPuntixClasse[1]; //FPR uscCL[1] = (double)matConfusione[0][0]/numPuntixClasse[0]; //TPR uscCL[3] = (1+uscCL[1]-uscCL[2])/2; //AUC } else { prob=(double)1/numParts[numVar-1]; TPR=0; FPR=0; AUC=0; double FP=0; double numF=0; for (int i=0;i<numParts[numVar-1];i++) { TPR+=(double)matConfusione[i][i]/numPuntixClasse[i]; FP=0; numF=0; for (int k=0;k<numParts[numVar-1];k++) if (i!=k) { FP+=matConfusione[k][i]; numF+=numPuntixClasse[k]; } FPR+=(double)FP/numF; } uscCL[2]=FPR*prob; uscCL[1]=TPR*prob; AUC+=(1+uscCL[1]-uscCL[2])/2; } delete[] usc; delete[] numPuntixClasse; for (int i=0;i<numParts[numVar-1];i++) delete[] matConfusione[i]; delete[] matConfusione; } else uscCL[0]= suma/(double)numCamp; fis.deleteFuzzySet(realPart); return uscCL; }
void Initialize () { FILE *fp; register int i, j; /* loop control */ int status; /* indicates end of file in initfile */ Trace("Initialize entered"); if (Totalexperiments > 1) sprintf(Bestfile, "%s.%d", Minfile, Experiment+1); /* prepare for new experiment */ Doneflag = 0; Curr_dump = 0; Bestsize = 0; /* set next mutation location */ if (M_rate < 1.0) Mu_next = ceil (log(Rand()) / log(1.0 - M_rate)); else Mu_next = 1; Trials = Gen = 0; Lost = Conv = 0; Plateau = 0; Spin = 0; Onsum = Offsum = 0.0; for (i=0; i<Windowsize; i++) Window[i] = 0.0; /* set up initial population */ i = 0; /* current structure */ if (Initflag) { /* get some structures from Initfile */ if ((fp = fopen(Initfile, "r")) == NULL) { char msg[40]; sprintf(msg, "Initialize: can't open %s", Initfile); Error(msg); } status = 1; if (Floatflag) { for (j = 0; j < Genes && status != EOF; j++) { status = fscanf(fp, "%lf", &Vector[j]); } } else status = fscanf(fp, "%s", Bitstring); while (status != EOF && i < Popsize) { if (Floatflag) StringRep(Vector, Bitstring, Genes); Pack(Bitstring, New[i].Gene, Length); New[i].Needs_evaluation = 1; i++; /* get the next structure */ if (Floatflag) for (j = 0; j < Genes && status != EOF; j++) status = fscanf(fp, "%lf", &Vector[j]); else status = fscanf(fp, "%s", Bitstring); } fclose(fp); } /********************************************************/ /* The seed for the random number generator is saved */ /* after the initialization of the first population */ /* in each experiment. The saved value is used as the */ /* Seed in subsequent experiments. The reason is: */ /* often we will run several experiments with one set */ /* of parameters, and compare the results with several */ /* experiments run with a different set of parameters. */ /* This means that for all runs which use the */ /* same population size, the initial populations for */ /* corresponding experiments will be the same. */ /********************************************************/ if ( Experiment > 0 ) Seed = Initseed; for (; i < Popsize; i++) { /* initialize remainder randomly */ for (j = 0; j < Length; j++) { if (Randint(0,1)) Bitstring[j] = '1'; else Bitstring[j] = '0'; } Pack(Bitstring , New[i].Gene , Length); New[i].Needs_evaluation = 1; } Initseed = Seed; Trace("Initialize completed"); } /* end Initialize */
void chromosome::mutSelection(double probMut) { int ind, num; chromosome app(*this); int realNumR; bool trovato=true; /* if (numRul>minRule && Rand()<0.1) { ind = Randint(0, numRul - 1); app.vettR[ind].index=dimMatWM; app.ordinaIndex(); //ordina gli indici e calcola il numRul app.faiMatdaVec(); app.deleteDup(); realNumR=app.numRul; if (realNumR >= minRule) { if (!CLASSIFICATION) copyChrom(app); else if (controllaPresenzaClassi((int**)app.matR,app.numRul)) copyChrom(app); } }*/ if (dimMatWM > maxRule && Rand() < 0.1) //modifico o aggiungo una regola { ind = Randint(0, maxRule - 1); //elemento del vettore da modificare while(trovato) { num = Randint(0, dimMatWM - 1); //seleziono una regola che non e' gia' presente trovato=false; for (int i=0;i<numRul;i++) if (app.vettR[i].index==num) { trovato=true; break; } } app.vettR[ind].index = num; /*if (app.vettR[ind].index==dimMatWM) //sto aggiungendo { */ for (int i=0;i<numVar-1;i++) if(matWM[num]!=0) app.vettR[ind].vectAnt[i]=true; else app.vettR[ind].vectAnt[i]=false; //} app.ordinaIndex(); //ordina gli indici e calcola il numRul app.faiMatdaVec(); app.deleteDup(); realNumR=app.numRul; if (realNumR >= minRule) { if (!CLASSIFICATION) copyChrom(app); else if (controllaPresenzaClassi((int**)app.matR,app.numRul)) copyChrom(app); } } int conta = 0; if (SIZE_POP_PR && Rand() < 0.7) { ind = Randint(0, app.numRul - 1); for (int i = 0; i < numVar-1; i++) if (matWM[ind][i]!=0 && Rand() < (double) 2 / (numVar-1)) app.vettR[ind].vectAnt[i] = !app.vettR[ind].vectAnt[i]; for (int i = 0; i < numVar-1; i++) if (app.vettR[ind].vectAnt[i] != 0) conta++; } if (conta >= minTerms) { app.faiMatdaVec(); app.deleteDup(); realNumR=app.numRul; if (realNumR >= minRule) { if (!CLASSIFICATION) copyChrom(app); else if (controllaPresenzaClassi((int**)app.matR,app.numRul)) copyChrom(app); } } }
void greedyAleatorio( string &relation, vector< vector< float> > &training, vector< vector< float> > &test, vector< bool> &seleccion, float tolerancia) { float acierto = 0; bool fin = false; bool vacio = false; int fp; float mejor = 0; float max = 0; int total = 0; int num_atributos; int num_ejemplos; vector< int> LRC; float cmejor = -1000000; float cpeor = 1000000; float umbral; int iaux; checkRelation( relation, num_atributos, num_ejemplos); vector< bool> solucion(num_atributos, 0); vector< bool> LC( num_atributos, 0); if( num_ejemplos % 2 == 0) { num_ejemplos = num_ejemplos/2; } else { num_ejemplos = (num_ejemplos/2)-1; } // Mientras que no acabemos o la lista de atributos esté vacía while( !vacio && !fin) { // Identificamos cual es el mejor y el peor valor for( int i = 0; i < num_atributos-1; i++) { if( LC[i] == 0) { LC[i] = 1; acierto = getExito( relation, training, test, LC); if( acierto > cmejor) { cmejor = acierto; } if( acierto < cpeor) { cpeor = acierto; } LC[i] = 0; } } // Calculamos el umbral umbral = cmejor - tolerancia*( cmejor - cpeor); // Metemos en LRC las características cuyo éxito superan el umbral for( int i = 0; i < num_atributos-1; i++) { if( LC[i] == 0) { LC[i] = 1; acierto = getExito( relation, training, test, LC); if( acierto >= umbral) { LRC.push_back(i); } LC[i] = 0; } } // Cogemos una característica de LRC de forma aleatoria iaux = Randint(0, LRC.size()-1); fp = LRC[iaux]; solucion[fp] = 1; max = getExito( relation, training, test, solucion); // Comprobamos si el mejor éxito anterior es mejor que el mejor éxito hasta el momento, en caso contrario acabamos if( max >= mejor) { seleccion = solucion; LC = solucion; LRC.clear(); mejor = max; } else { fin = true; } // Comprobamos todos los atributos total++; if( total == num_atributos-1) { vacio = true; } } }
Crossover() { register int mom, dad; /* participants in the crossover */ register int xpoint1; /* first crossover point w.r.t. structure */ register int xpoint2; /* second crossover point w.r.t. structure */ register int xbyte1; /* first crossed byte */ register int xbit1; /* first crossed bit in xbyte1 */ register int xbyte2; /* last crossed byte */ register int xbit2; /* last crossed bit in xbyte2 */ register int i; /* loop control variable */ register char temp; /* used for swapping alleles */ static int last; /* last element to undergo Crossover */ int diff; /* set if parents differ from offspring */ char *kid1; /* pointers to the offspring */ char *kid2; static int firstflag = 1; Trace("Crossover entered"); Dtrace("crossover"); if (firstflag) { last = (C_rate*Popsize*Gapsize) - 0.5 ; firstflag = 0; } for (mom=0; mom < last ; mom += 2) { dad = mom + 1; /* kids start as identical copies of parents */ kid1 = New[mom].Gene; kid2 = New[dad].Gene; /* choose two Crossover points */ xpoint1 = Randint(0,Length); xpoint2 = Randint(0,Length-1); /* guarantee that xpoint1 < xpoint2 */ if (xpoint2 >= xpoint1) xpoint2++; else { i = xpoint1; xpoint1 = xpoint2; xpoint2 = i; } xbyte1 = xpoint1 / CHARSIZE; xbit1 = xpoint1 % CHARSIZE; xbyte2 = xpoint2 / CHARSIZE; xbit2 = xpoint2 % CHARSIZE; /* do parents differ outside cross segment? */ diff = 0; for (i=0; i < xbyte1; i++) diff += (kid1[i] != kid2[i]); diff += ( (kid1[xbyte1] & premask[xbit1]) != (kid2[xbyte1] & premask[xbit1]) ); diff += ( (kid1[xbyte2] & postmask[xbit2]) != (kid2[xbyte2] & postmask[xbit2]) ); for (i=xbyte2+1; i < Bytes; i++) diff += (kid1[i] != kid2[i]); if (diff) /* they do */ { /* perform crossover */ temp = kid1[xbyte1]; kid1[xbyte1] = (kid1[xbyte1] & premask[xbit1]) | (kid2[xbyte1] & postmask[xbit1]); kid2[xbyte1] = (kid2[xbyte1] & premask[xbit1]) | (temp & postmask[xbit1]); diff = ((kid1[xbyte1] & postmask[xbit1]) != (kid2[xbyte1] & postmask[xbit1]) ); for (i=xbyte1 + 1; i < xbyte2; i++) { temp = kid1[i]; kid1[i] = kid2[i]; kid2[i] = temp; diff += (kid1[i] != kid2[i]); } if (xbyte1 < xbyte2) { temp = kid1[xbyte2]; kid1[xbyte2] = (kid1[xbyte2] & postmask[xbit2]) | (kid2[xbyte2] & premask[xbit2]); kid2[xbyte2] = (kid2[xbyte2] & postmask[xbit2]) | (temp & premask[xbit2]); diff += ((kid1[xbyte2] & premask[xbit2]) != (kid2[xbyte2] & premask[xbit2]) ); } else { temp = kid1[xbyte2]; kid1[xbyte2] = (kid1[xbyte2] & premask[xbit2]) | (kid2[xbyte2] & postmask[xbit2]); kid2[xbyte2] = (kid2[xbyte2] & premask[xbit2]) | (temp & postmask[xbit2]); diff = ((kid1[xbyte2] & postmask[xbit1] & premask[xbit2]) != (kid2[xbyte2] & postmask[xbit1] & premask[xbit2]) ); } if (diff) /* kids differ from parents */ { /* set evaluation flags */ New[mom].Needs_evaluation = 1; New[dad].Needs_evaluation = 1; } } } Trace("Crossover completed"); }