Upload
puneetshah15
View
49
Download
1
Embed Size (px)
DESCRIPTION
Uploaded from Google Docs
Citation preview
Experiment No. 1
/* Depth First Search Technique*/#include<iostream.h>#include<conio.h>#define T 1#define F 0class edge {int terminal; struct edge *next;};class vertex {int visit,vertex_no,path_length; char info; struct edge *edge_ptr; };void table(int,int matrix[size][size],struct vertex vert[size]);struct edge *insert_vertex(int,struct edge *);void DFS(int,int *dist,vertex vert[size]);void input(int,int a[size][size]);void output(int,int a[size][size]);struct edge * insert_vertex(int vertex_no,struct edge *first){struct edge *new1,*current;new1=(struct edge *) malloc(sizeof(struct edge));new1->terminal=vertex_no;new1->next=null;if(!first)return(new1);for(current=first;current->next;current=current->next);current->next=new1;return(first);}void table(int vertex_num,int matrix[size][size],struct vertex vert[size]){int i,j; for(i=0;i<vertex_num;i++){ vert[i].visit=F; vert[i].vertex_no=i+1; vert[i].info='A'+i; vert[i].path_length=0; vert[i].edge=null;}for(i=0;i<vertex_num;i++)for(j=0;j<vertex_no;j++)if(matrix[i][j]>0)vert[i].edge_ptr=insert_vertex(j,vert[i].edge_ptr);}void DFS(int index,int *dist,struct vertex vert[size]){struct edge *link; vert[index].visit=t; vert[index].path_length=*dist;*dist+=1; for(link=vert[index].edge_ptr;link;link=link->next)if(vert[link->terminal].visit==f) DFS(link->terminal,dist,vert);}void input(int number,int a[size][size]){ int i,j; cout<<"input the adjency matrix \n"; for(i=0;i<number;i++){ for(j=0;j,number;j++) { cin>>a[i][j]; }}}void output(int number,int a[size][size]){int i,j; cout<<"\n the adjency matrix \n";for(i=0;i<number;i++) { for(j=0;j,number;j++) { cout<<a[i][j]; } cout("\n"); }}void main() {int i; int number,index,dist; int a[size][size]; struct vertex vert[size];struct edge *list; cout<<"\n input the number of vertices in the graph";cin>>number; input(number,a); output(number,a);table(number,a,vert); cout<<"\n input the starting vertex 0-"<<number-1;cin>>index; dist=0; DFS(index,&dist,vert); cout<<"\n path length of the vertex "<<vert[index].info; cout<<"\n vertex length vertex connectivity \n";for(i=0;i<number;i++) { cout<<"\n vert[i].info,vert[i].path_length"; for(list=vert[i].edge_ptr;list;list=list->next) { cout<<" "; putchar(list->terminal+'A'); } } }
/*OUTPUT:-input the no. of vertices in the graph8input the adjacency matrix0 1 1 0 0 0 0 00 0 0 1 1 0 0 00 0 0 0 0 1 0 00 0 0 0 0 0 0 10 0 0 0 0 1 0 10 0 0 0 0 0 1 00 0 1 0 0 0 0 00 0 0 0 0 1 1 0
adjacency matrix:-
0 1 1 0 0 0 0 00 0 0 1 1 0 0 00 0 0 0 0 1 0 00 0 0 0 0 0 0 10 0 0 0 0 1 0 10 0 0 0 0 0 1 00 0 1 0 0 0 0 00 0 0 0 0 1 1 0input the starting0-7:4path length of the vertex from evertex length vertex connectivityA 0 BCB 0 DEC 3 FD 0 HE 0 FHF 1 GG 2 CH 1 FG */
Experiment No. 2
/* Breadth First Search Algorithm*/#include<iostream.h>class Queue{private: int data; Queue*next;public: void Enque(int); int Deque(); }*head,*tail;void Queue::Enque(int data){ Queue *temp; temp=new Queue; temp->data=data; temp->next=NULL; if(head==NULL) head=temp; else tail->next=temp; tail=temp; }int Queue::Deque(){ Queue* temp; temp=head; head=head->next; return temp->data; }int visit[100]; int bfs_span_tree[100][100];class graph{ private: int a; graph*next;public: void bfs(); graph* create(graph*); void ftraverse(graph*); }; graph* graph::create(graph*head){ int a; graph*last; head=last=NULL; graph*temp; cout<<”Enter adjecent node ,-1 to stop:\n”; cin>>a; while(a!=-1) { temp=new graph; temp->a=a; temp->next=NULL; if(head==NULL) head=temp; else last->next=temp; last=temp; cout<<”Enter adjecent node ,-1 to stop:\n”; cin>>a; } return head; }void graph::ftraverse(graph*h){ while(h!=NULL) { cout<<h->a<<”->”; h=h->next; } cout<<”NULL\n”; }void graph::bfs(){ cout<<”**********************************************************\n”; cout<<”This program is to implement bfs for an unweighted graph \n”; cout<<”**********************************************************\n”; graph *ptr[100]; int n; cout<<”Enter the no. of nodes in the grph:”; cin>>n; for(int i=1;i<=n;i++) { cout<<”Enter the adjacent nodes to node no. “<<i<<endl; cout<<”***************************************\n”; ptr[i]=create(ptr[i]); } cout<<”\n\nThe Entered Graph is ::\n”; for(i=1;i<=n;i++) { cout<<”< “<<i<<” > ::”; ftraverse(ptr[i]); } int x; cout<<”\nEnter the start node <1,…”<<n<<”>:”; cin>>x; cout<<”\n\nThe Breadth first search traversal is:\n”; Queue object; for(i=1;i<=n;i++) { visit[i]=0; } for(i=1;i<=n;i++) for(int j=1;j<=n;j++) bfs_span_tree[i][j]=0; object.Enque(x); int p; while(head!=NULL&&tail!=NULL) { p=object.Deque(); int x=p; while(ptr[p]!=NULL) { if(visit[ptr[p]->a]!=1)
{ cout<<”node “<<ptr[p]->a<<” is visited\n”; visit[ptr[p]->a]=1; bfs_span_tree[ptr[p]->a][x]=1; } //Enque all its adjacent nodes object.Enque(ptr[p]->a); ptr[p]=ptr[p]->next; } } cout<<”\n\nThe required bfs spanning tree is ::\n\n”; for(i=1;i<=n;i++) { for(int j=1;j<=n;j++) cout<<bfs_span_tree[i][j]<<’ ‘; cout<<endl; } cout<<endl;}int main(){ graph obj; obj.bfs(); return 0;}
Experiment No.3
/*HILL CLIMBING*/public static ScalesSolution RMHC(ArrayList<Double> weights,int n,int iter){ScalesSolution sol = new ScalesSolution(n);ScalesSolution oldSol = new ScalesSolution(sol.GetSol()); for(int i = 0; i < iter; i++){System.out.println("##NEW ITERATION##");System.out.println("Old Solution : ");oldSol.println(); double f = oldSol.ScalesFitness(weights);System.out.println("Old Fittness: ");System.out.println(f);//the new solution after copying the string from scalesolutionsol.SmallChange();System.out.println("New Solution : ");sol.println();System.out.println("New Fittness: ");System.out.println(sol.ScalesFitness(weights));if (oldSol.ScalesFitness(weights) > sol.ScalesFitness(weights)){oldSol = new ScalesSolution(sol.GetSol());}}return(oldSol);}My code within the main is as follows :-ArrayList<Double> weight = new ArrayList<Double>(); weight.add(1.0);weight.add(2.0);weight.add(3.0);weight.add(4.0);weight.add(10.0);System.out.println(" Final Solution: "+RMHC(weight,5,5).ScalesFitness(weight));
Output:-
##NEW ITERATION##Old Solution : 01010Old Fittness: 8.0New Solution : 00010
New Fittness: 12.0##NEW ITERATION##Old Solution : 01010Old Fittness: 8.0New Solution : 10010New Fittness: 10.0##NEW ITERATION##Old Solution : 01010Old Fittness: 8.0New Solution : 10000New Fittness: 18.0##NEW ITERATION##Old Solution : 01010Old Fittness: 8.0New Solution : 10100New Fittness: 12.0##NEW ITERATION##Old Solution : 01010Old Fittness: 8.0New Solution : 10101New Fittness: 8.0Final Solution: 8.0
Experiment No. 9/*ERROR BACK ALGORITHM*/#include "backprop.h"#include <time.h>#include <stdlib.h>CBackProp::CBackProp(int nl,int *sz,double b,double a):beta(b),alpha(a){ numl=nl; lsize=new int[numl]; for(int i=0;i<numl;i++){ lsize[i]=sz[i]; }out = new double*[numl];for( i=0;i<numl;i++){ out[i]=new double[lsize[i]]; }delta = new double*[numl];for(i=1;i<numl;i++){ delta[i]=new double[lsize[i]]; }weight = new double**[numl];for(i=1;i<numl;i++){ weight[i]=new double*[lsize[i]]; }for(i=1;i<numl;i++){ for(int j=0;j<lsize[i];j++){ weight[i][j]=new double[lsize[i-1]+1];}}prevDwt = new double**[numl];for(i=1;i<numl;i++){prevDwt[i]=new double*[lsize[i]];}for(i=1;i<numl;i++){for(int j=0;j<lsize[i];j++){prevDwt[i][j]=new double[lsize[i-1]+1];}}srand((unsigned)(time(NULL)));for(i=1;i<numl;i++) for(int j=0;j<lsize[i];j++) for(int k=0;k<lsize[i-1]+1;k++)weight[i][j][k]=(double)(rand())/(RAND_MAX/2) - 1;//32767for(i=1;i<numl;i++) for(int j=0;j<lsize[i];j++) for(int k=0;k<lsize[i-1]+1;k++)prevDwt[i][j][k]=(double)0.0; }CBackProp::~CBackProp(){for(int i=0;i<numl;i++)delete[] out[i];delete[] out; for(i=1;i<numl;i++) delete[] delta[i]; delete[] delta; for(i=1;i<numl;i++)for(int j=0;j<lsize[i];j++) delete[] weight[i][j];for(i=1;i<numl;i++) delete[] weight[i]; delete[] weight;for(i=1;i<numl;i++) for(int j=0;j<lsize[i];j++) delete[] prevDwt[i][j];for(i=1;i<numl;i++) delete[] prevDwt[i]; delete[] prevDwt; delete[] lsize; }double CBackProp::sigmoid(double in){ return (double)(1/(1+exp(-in))); }double CBackProp::mse(double *tgt) const{ double mse=0; for(int i=0;i<lsize[numl-1];i++){ mse+=(tgt[i]-out[numl-1][i])*(tgt[i]-out[numl-1][i]); } return mse/2; } double CBackProp::Out(int i) const{ return out[numl-1][i]; } void CBackProp::ffwd(double *in){ double sum; for(int i=0;i<lsize[0];i++)out[0][i]=in[i]; for(i=1;i<numl;i++){ for(int j=0;j<lsize[i];j++){ sum=0.0; for(int k=0;k<lsize[i-1];k++){ sum+= out[i-1][k]*weight[i][j][k]; }sum+=weight[i][j][lsize[i-1]]; out[i][j]=sigmoid(sum); }}}void CBackProp::bpgt(double *in,double *tgt){double sum;
// update output values for each neuronffwd(in);
// find delta for output layerfor(int i=0;i<lsize[numl-1];i++){delta[numl-1][i]=out[numl-1][i]*(1-out[numl-1][i])*(tgt[i]-out[numl-1][i]);}
// find delta for hidden layers for(i=numl-2;i>0;i--){for(int j=0;j<lsize[i];j++){sum=0.0;for(int k=0;k<lsize[i+1];k++){sum+=delta[i+1][k]*weight[i+1][k][j];}delta[i][j]=out[i][j]*(1-out[i][j])*sum;}}
// apply momentum ( does nothing if alpha=0 )for(i=1;i<numl;i++){for(int j=0;j<lsize[i];j++){for(int k=0;k<lsize[i-1];k++){weight[i][j][k]+=alpha*prevDwt[i][j][k];}weight[i][j][lsize[i-1]]+=alpha*prevDwt[i][j][lsize[i-1]];}}
// adjust weights usng steepest descent for(i=1;i<numl;i++){for(int j=0;j<lsize[i];j++){for(int k=0;k<lsize[i-1];k++){prevDwt[i][j][k]=beta*delta[i][j]*out[i-1][k];weight[i][j][k]+=prevDwt[i][j][k];}prevDwt[i][j][lsize[i-1]]=beta*delta[i][j];weight[i][j][lsize[i-1]]+=prevDwt[i][j][lsize[i-1]];}}}
Experiment No. 7/* Perception for AND */Program to implement perceptron learning rule#include <iostream>#include <cstdlib>#include <ctime>#include <cmath>using namespace std; intmain(){float w [3]; float t, o;const double eta = .1;int i; int count = 0;bool correct = 0;
int train [4] [3] = { 0, 0, 0,0, 1, 0,1, 0, 0,1, 1, 1 };int x0, x1, x2; float weightsum, deltaw1, deltaw2;
srand((unsigned)(time(0)));rand();
//initialize threshold
x0 = -1;w[0] = fabs((float)(rand())/(32767/2)-1);for ( i = 1; i < 3; ++i)w[i] = (float)(rand())/(32767/2) - 1; cout << "INITIAL WEIGHTS" << endl<< "---------------" << endl;cout << "w0 = " << w[0] << endl;cout << "w1 = " << w[1] << endl;cout << "w2 = " << w[2] << endl;while(!correct){correct = 1; count++; for (i = 0; i < 4; ++i){x1 = train[i][0]; //input for x1x2 = train[i][1]; //input for x2 //find weighted sum of inputs and threshold values
weightsum = x0 * w[0] + x1 * w[1] + x2 * w[2]; if (weightsum > 0) o = 1;else o = 0;if (o != t){ deltaw1 = eta * (t - o) * x1;w[1] = w[1] + deltaw1; deltaw2 = eta * (t - o) * x2;w[2] = w[2] + deltaw2; correct = 0;} } }
//OUTPUTcout << endl << endl;cout << "FINAL WEIGHTS" << endl<< "-------------" << endl;cout << "w0 = " << w[0] << endl;cout << "w1 = " << w[1] << endl;cout << "w2 = " << w[2] << endl;cout << "The delta rules were invoked " << count << " times"<<endl;return 0;}
Experiment no. 4/* Steepest Accent Hill Climbing*/// Algorithm implemented in the Ruby Programming Language
def onemax(vector) return vector.inject(0.0){|sum, v| sum + ((v=="1") ? 1 : 0)} end def random_bitstring(num_bits) return Array.new(num_bits){|i| (rand<0.5) ? "1" : "0"} end def random_neighbor(bitstring) mutant = Array.new(bitstring) pos = rand(bitstring.size) mutant[pos] = (mutant[pos]=='1') ? '0' : '1' return mutant end def search(max_iterations, num_bits) candidate = {} candidate[:vector] = random_bitstring(num_bits) candidate[:cost] = onemax(candidate[:vector]) max_iterations.times do |iter| neighbor = {} neighbor[:vector] = random_neighbor(candidate[:vector]) neighbor[:cost] = onemax(neighbor[:vector]) candidate = neighbor if neighbor[:cost] >= candidate[:cost] puts " > iteration #{(iter+1)}, best=#{candidate[:cost]}" break if candidate[:cost] == num_bits end return candidate end if __FILE__ == $0 # problem configuration num_bits = 64 # algorithm configuration max_iterations = 1000 # execute the algorithm best = search(max_iterations, num_bits) puts "Done. Best Solution: c=#{best[:cost]}, v=#{best[:vector].join}" end
Experiment No. 6/* A* Algorithm */
function A*(start,goal)closedset := the empty set // The set of nodes already evaluated.openset := set containing the initial node // The set of tentative nodes to be evaluated.came_from := the empty map // The map of navigated nodes.g_score[start] := 0 // Cost from start along best known path.h_score[start] := heuristic_cost_estimate(start, goal)f_score[start] := h_score[start] // Estimated total cost from start to goal through y.while openset is not emptyx := the node in openset having the lowest f_score[] valueif x = goalreturn reconstruct_path(came_from, came_from[goal])remove x from opensetadd x to closedsetforeach y in neighbor_nodes(x)if y in closedsetcontinuetentative_g_score := g_score[x] + dist_between(x,y)if y not in opensetadd y to opensettentative_is_better := trueelse if tentative_g_score < g_score[y]tentative_is_better := true else tentative_is_better := false if tentative_is_better = true came_from[y] := x g_score[y] := tentative_g_score h_score[y] := heuristic_cost_estimate(y, goal) f_score[y] := g_score[y] + h_score[y] return failure function reconstruct_path(came_from, current_node) if came_from[current_node] is set p = reconstruct_path(came_from, came_from[current_node]) return (p + current_node) else return current_node
Experiment No. 5
/* Best First Search Algorithm */#include<stdio.h>#include<stdlib.h> void main(){ int graph[15][15],s[15],pathestimate[15],mark[15]; int num_of_vertices,source,i,j,u,predecessor[15]; int count=0; int minimum(int a[],int m[],int k); void printpath(int,int,int[]); printf("\nenter the no.of vertices\n"); scanf("%d",&num_of_vertices); if(num_of_vertices<=0) { printf("\nthis is meaningless\n"); exit(1); } printf("\nenter the adjacent matrix\n"); for(i=1;i<=num_of_vertices;i++) { printf("\nenter the elements of row %d\n",i); for(j=1;j<=num_of_vertices;j++) { scanf("%d",&graph[i][j]); } } printf("\nenter the source vertex\n"); scanf("%d",&source); for(j=1;j<=num_of_vertices;j++) { mark[j]=0; pathestimate[j]=999; predecessor[j]=0; } pathestimate=0; while(count<num_of_vertices) { u=minimum(pathestimate,mark,num_of_vertices); s[++count]=u; mark[u]=1; for(i=1;i<=num_of_vertices;i++) { if(graph[u][i]>0) { if(mark[i]!=1) {
if(pathestimate[i]>pathestimate[u]+graph[u][i]) { pathestimate[i]=pathestimate[u]+graph[u][i]; predecessor[i]=u; } } } } } for(i=1;i<=num_of_vertices;i++) { printpath(source,i,predecessor); if(pathestimate[i]!=999) printf("->(%d)\n",pathestimate[i]); } }int minimum(int a[],int m[],int k) { int mi=999; int i,t; for(i=1;i<=k;i++) { if(m[i]!=1) { if(mi>=a[i]) { mi=a[i]; t=i; } }} return t; }void printpath(int x,int i,int p[]){ printf("\n");if(i==x){printf("%d",x);}else if(p[i]==0)printf("no path from %d to %d",x,i);else{printpath(x,p[i],p);printf("..%d",i);}}