Department of Computer Engineering BE Laboratory Practice-I A.Y 2021-22 SEM1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

Dr. D. Y.

Patil Pratishthan’s

DR. D. Y. PATIL INSTITUTE OF ENGINEERING, MANAGEMENT & RESEARCH

Department of Computer Engineering


BE Laboratory Practice-I
A.Y 2021-22 SEM1

Index
Experiment Title of Experiment Page No
No
High Performance Computing
1 Addition of two large vectors using CUDA C 02
2 Maximum and Minimum element in vectors using CUDA C 04
3 Multiplication of matrix and vector using CUDA C 06
4 Odd and even sorting using CUDA C 11
5 Multiplication of matrix by vector using OpenMP 13
6 Multiplication of matrix by using OpenMP. 15
7 Bubble sort using OpenMP 17
Artificial Intelligence & Robotics
1 Implement Tic Tac Toe using A* algorithm 18
2 Solve 8-puzzle problem using A* algorithm. Assume any initial 21
configuration and define goal configuration clearly
3 Use Heuristic Search Techniques to Implement Hill- 28
Climbing Algorithm.
4 Use Heuristic Search Techniques to Implement Best first search 31
and A* algorithm
Data Analytics
1 Display Features of Iris Flower Data Set 36
2 Analyze Pima Indian Diabetics Dataset using Naïve Bayes 38
Algorithm
3 Trip History Analysis 41
4 Big mart Sales analysis 44

Mrs. Deepali Jawale


Prof. P.P. Shevatekar
Mr. Ishwar Kalbandi Prof. P.P. Shevatekar
Practical Batch Incharge HOD
Name – Palash N Doshi
Roll No – BACO18164

HIGH PERFORMANCE COMPUTING

Assignment - 1

Addition of two large vectors Using CUDA C.


Code:
%%cu
#include <stdio.h>
#include <stdlib.h>
#define N 100
__global__ void add(int *a, int *b, int *c) {
int tid = threadIdx.x;
if (tid < N) {
c[tid] = a[tid] + b[tid];
}

int main(void) {
int a[N], b[N], c[N];
int *dev_a, *dev_b, *dev_c;
cudaError_t err = cudaSuccess;
err = cudaMalloc((void**)&dev_a, N * sizeof(int));
if (err != cudaSuccess)
{
printf("failed to allocate on device \n");
printf("error is:\n");
printf("%s", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
cudaMalloc((void**)&dev_b, N * sizeof(int));
cudaMalloc((void**)&dev_c, N * sizeof(int));

for (int i = 0; i < N; i++)


{
a[i] = i;
b[i] = i * i;
c[i] = 0;
}

/*
for(int i=0;i<N;i++)
{
printf(" c conttents are =%d\n", c[i]);
}
*/

cudaMemcpy(dev_a, a, N * sizeof(int), cudaMemcpyHostToDevice);


cudaMemcpy(dev_b, b, N * sizeof(int), cudaMemcpyHostToDevice);
Name – Palash N Doshi
Roll No – BACO18164

cudaMemcpy(dev_c, c, N * sizeof(int), cudaMemcpyHostToDevice);


add << <1, N >> > (dev_a, dev_b, dev_c);

err = cudaMemcpy(c, dev_c, N * sizeof(int), cudaMemcpyDeviceToHost);


if (err != cudaSuccess)
{
printf("failed to copy from device \n");
exit(EXIT_FAILURE);
}

for (int i = 0; i < N; i++) {


printf("%d +%d=%d\n", a[i], b[i], c[i]);
}

cudaFree(dev_a);
cudaFree(dev_b);
cudaFree(dev_c);

return 0;
}

Output:
Name – Palash N Doshi
Roll No – BACO18164

Assignment - 2

Maximum and Minimum element in vectors using CUDA C.

Code:
%%cu
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
__global__ void max(int *a, int *c)
{
int i = threadIdx.x; // initialize i to thread ID
*c = a[0];
if(a[i] < *c)
{
*c = a[i];
}
}

int main()
{
int i;
srand(time(NULL)); //makes use of the computer's internal clock to control the choice of the
seed
int a[SIZE]={12,4,7,3,9,5,11,6,1,76};
int c;
int *dev_a, *dev_c; //GPU / device parameters

cudaMalloc((void **) &dev_a, SIZE*sizeof(int)); //assign memory to parameters on GPU from


CUDA runtime API
cudaMalloc((void **) &dev_c, SIZE*sizeof(int));

//for( i = 0 ; i < SIZE ; i++)


//{
//a[i] = i; // input the numbers
// }

cudaMemcpy(dev_a , a, SIZE*sizeof(int),cudaMemcpyHostToDevice); //copy the array from CPU to


GPU

max<<<1,SIZE>>>(dev_a,dev_c); // call
kernel function <<<number of blocks, number of threads

cudaMemcpy(&c, dev_c, SIZE*sizeof(int),cudaMemcpyDeviceToHost); // copy the result back


from GPU to CPU

printf("\nmin = %d ",c);

cudaFree(dev_a); // Free the allocated memory


cudaFree(dev_c);
Name – Palash N Doshi
Roll No – BACO18164

printf("");

return 0;
}

Output:
Name – Palash N Doshi
Roll No – BACO18164

Assignment – 3

Multiplication of matrix and vector using CUDA C


Code:
%%cu
#include <stdio.h>
#include <stdlib.h>
#define m 5
__global__ void mul_r(int *a, int *b, int*c)
{
int tid = threadIdx.x;
if (tid < m)
{
c[tid] = a[tid] * b[tid];
}

int main()
{
int n, c, d, fst[10][10], snd[10][10], t_snd[10][10];
int row, col, sum_c, a[10], b[10], ans[10];

/*
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
*/

n = m; //square matrix only

//printf("Enter the elements of first matrix\n");


//for true randum value of vector

srand(time(0));

for (c = 0; c < m; c++)


{
for (d = 0; d < n; d++)
{
//scanf("%d", &first[c][d]);
fst[c][d] = rand() % 10 + 1;
}
}

printf("display the elements of first matrix\n");

for (c = 0; c < m; c++)


{
for (d = 0; d < n; d++)
{
Name – Palash N Doshi
Roll No – BACO18164

printf("%d\t", fst[c][d]);
}
printf("\n");
}

// take next matrix


//for true randum value of vector
//srand(time(0));

for (c = 0; c < m; c++)


{
for (d = 0; d < n; d++)
{
//scanf("%d", &first[c][d]);
snd[c][d] = rand() % 10 + 1;
}
}

printf("display the elements of second matrix\n");

for (c = 0; c < m; c++)


{
for (d = 0; d < n; d++)
{
printf("%d\t", snd[c][d]);
}
printf("\n");
}

// transpose of second matrix

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
{
t_snd[d][c] = snd[c][d];
}

// Displaying the transpose of matrix a

printf("\nTranspose of second Matrix:\n");

for (c = 0; c < n; c++)


{
for (d = 0; d < m; d++)
{
printf("%d\t", t_snd[c][d]);

}
printf("\n");
}
Name – Palash N Doshi
Roll No – BACO18164

// now multiply on cuda

int *dev_a, *dev_b, *dev_ans;

cudaError_t err = cudaSuccess;

// allocate memory on GPU

err = cudaMalloc((void**)&dev_a, m * sizeof(int));

if (err != cudaSuccess)
{
printf("failed to allocate on device \n");
printf("error is:\n");
printf("%s", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
//printf("first ok\n");

cudaMalloc((void**)&dev_b, m * sizeof(int));

cudaMalloc((void**)&dev_ans, m * sizeof(int));

//printf("first finished ok\n");

row = 0;
col = 0;
for (row = 0; row < m; row++)
{
for (d = 0; d < m; d++)
{
a[d] = fst[row][d];
}
// printf("ok a\n");
cudaMemcpy(dev_a, a, m * sizeof(int), cudaMemcpyHostToDevice);

for (col = 0; col < m; col++)


{
for (d = 0; d < m; d++)
{
b[d] = t_snd[col][d];
ans[d] = 0;
}

// printf("ok b\n");
cudaMemcpy(dev_b, b, m * sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(dev_ans, ans, m * sizeof(int), cudaMemcpyHostToDevice);
mul_r << <1, m >> > (dev_a, dev_b, dev_ans);
err = cudaMemcpy(ans, dev_ans, m * sizeof(int), cudaMemcpyDeviceToHost);
Name – Palash N Doshi
Roll No – BACO18164

if (err != cudaSuccess)
{
printf("failed to copy from device \n");
exit(EXIT_FAILURE);
}
sum_c = 0;
for (d = 0; d < m; d++)
{
//printf("%d\t", ans[d]);
sum_c += ans[d];
}
snd[row][col] = sum_c;}}
printf(" Matrix multipliation ans=:\n");
for (c = 0; c < n; c++)
{
for (d = 0; d < m; d++)
{
printf("%d\t", snd[c][d]);
}
printf("\n");
}
//
return 0;
}

Output:
Name – Palash N Doshi
Roll No – BACO18164

Assignment – 4

Odd and even sorting using CUDA


Code
%%cu
#include <stdio.h>
#include <stdlib.h>
#define N 9
__global__ void even(int *a)
{
int tid = threadIdx.x;
int temp;

tid = tid * 2; // as even sort


if (tid <= N - 2)
{
if (a[tid] > a[tid + 1])
{
temp = a[tid];
a[tid] = a[tid + 1];
a[tid + 1] = temp;
}
}
}

__global__ void odd(int *a)


{
int tid = threadIdx.x;
int temp;
tid = tid * 2 + 1; // as odd sort
if (tid <= N - 2)
{
if (a[tid] > a[tid + 1])
{
temp = a[tid];
a[tid] = a[tid + 1];
a[tid + 1] = temp;
}

}
}

int main(void) {
int b[N];
int *dev_a; //,*dev_c;
int a[N] = { 56,4,10,95,23,89,78,12,9 };
printf("ORIGINAL ARRAY : \n");
for (int i = 0; i < N; i++)
{
printf("%d ", a[i]);
Name – Palash N Doshi
Roll No – BACO18164

}
printf(" \n");
cudaError_t err = cudaSuccess;
err = cudaMalloc((void**)&dev_a, N * sizeof(int));
if (err != cudaSuccess)
{
printf("failed to allocate on device \n");
printf("error is:\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
//cudaMalloc((void**)&dev_c, sizeof(int));
cudaMemcpy(dev_a, a, N * sizeof(int), cudaMemcpyHostToDevice);
//cudaMemcpy(dev_c,c,sizeof(int), cudaMemcpyHostToDevice);

for (int i = 0; i < N / 2; i++)


{
odd << <1, N >> > (dev_a);
even << <1, N >> > (dev_a);
}
cudaMemcpy(b, dev_a, sizeof(int)*N, cudaMemcpyDeviceToHost);
printf("\nSORTED ARRAY : \n");
for (int i = 0; i < N; i++)
{
printf("%d ", b[i]);
}
cudaFree(dev_a);
//cudaFree(dev_c);
return 0;
}

Output:
Name – Palash N Doshi
Roll No – BACO18164

Assignment - 5

Multiplication of matrix by vector using OpenMP


Code:
#include<stdio.h>
#include<iostream>
#include<cstdlib>
#include<omp.h>
using namespace std;
int main()
{
int m=3,n=2;
int mat[m][n],vec[n],out[m];
//matrix of size 3x2
for(int row=0;row<m;row++)

{
for(int col=0;col<n;col++)
{
mat[row][col]=10;
}
}
//display matrix
cout<<"Input Matrix"<<endl;
for(int row=0;row<m;row++)
{
for(int col=0;col<n;col++)
{
cout<<"\t"<<mat[row][col];
}
cout<<""<<endl;
}

//column vector of size 2x1


for(int row=0;row<n;row++)
{
vec[row]=2;
}
//display vector
cout<<"Input Col-Vector"<<endl;
for(int row=0;row<n;row++)

{
cout<<vec[row]<<endl;
}
//before multiplication check condition, no_of_cols(matrix)==no_of_rows(vector)
#pragma omp parallel
{
#pragma omp parallel for
for(int row=0;row<m;row++)
Name – Palash N Doshi
Roll No – BACO18164

{
out[row]=0;
for(int col=0;col<n;col++)
{
out[row]+=mat[row][col]*vec[col];
//int count=out[row];
//printf("\n%d\n",count);
}
}
}
//display resultant vector
cout<<"Resultant Col-Vector"<<endl;
for(int row=0;row<m;row++)
{
cout<<"\nvec["<<row<<"]:"<<out[row]<<endl;
}
return 0;

Output:
Name – Palash N Doshi
Roll No – BACO18164

Assignment - 6

Multiplication of matrix by using OpenMP.


Code
#include<stdio.h>
#include<iostream>
#include<cstdlib>
#include<omp.h>
using namespace std;
int main()
{
int m=3,n=2;
int mat[m][n],vec[n],out[m];

//matrix of size 3x2


for(int row=0;row<m;row++)
{
for(int col=0;col<n;col++)
{
mat[row][col]=10;
}
}
//display matrix
cout<<"Input Matrix"<<endl;
for(int row=0;row<m;row++)
{
for(int col=0;col<n;col++)
{
cout<<"\t"<<mat[row][col];
}
cout<<""<<endl;
}
//column vector of size 2x1
for(int row=0;row<n;row++)
{
vec[row]=5;
}
//display vector
cout<<"Input Col-Vector"<<endl;

for(int row=0;row<n;row++)
{
cout<<vec[row]<<endl;
}
//before multiplication check condition, no_of_cols(matrix)==no_of_rows(vector)
#pragma omp parallel
{
#pragma omp parallel for
for(int row=0;row<m;row++)
Name – Palash N Doshi
Roll No – BACO18164

{
out[row]=0;
for(int col=0;col<n;col++)
{
out[row]+=mat[row][col]*vec[col];
//int count=out[row];
//printf("\n%d\n",count);
}
}
}
//display resultant vector
cout<<"Resultant Col-Vector"<<endl;

for(int row=0;row<m;row++)
{
cout<<"\nvec["<<row<<"]:"<<out[row]<<endl;

}
return 0;
}

Output:
Name – Palash N Doshi
Roll No – BACO18164

Assignment - 7
Bubble Sort by using OpenMP.
Code:
#include <omp.h>
#include <iostream>
#define NUM_THREADS 1 //defining the number of threads that openmp can use. Threads are Numbered as 0,1,.....
int main()
{//omp_set_num_threads(NUM_THREADS); //set openmp number of threads double start = omp_get_wtime();
double start = omp_get_wtime();
int A[10000];
int j = 10000;
for(int i =0;i<10000;i++) A[i] = j--;
for(int k =0;k<10000;k++){ //number of passes
if(k%2==0){ //if k is even then do even indices, i.e, 0-1, 2-3,
#pragma omp parallel for//achieve parallelism by telling each thread to take one set of indices (0-1, 2-3...)
for(int i =0;i<10000;i+=2)
{
//printf("Thread ID : %d\n", omp_get_thread_num()); if(A[i]>A[i+1]){
int temp = A[i]; A[i] = A[i+1];
A[i+1] = temp;
}
}
else
{ //if odd then take indices 1-2, 3-4, 5-6...
#pragma omp parallel for //achieve parallelism by telling each thread to take one set of indices (1-2,3-4...)
for(int i =1;i<10000-1;i+=2){
//printf("Thread ID : %d\n", omp_get_thread_num()); if(A[i]>A[i+1]){
int temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
}
}
}
for(int i =0;i<10000;i++) printf("%d ", A[i]);
double end = omp_get_wtime();
printf("\nTime taken in second(s) is %g \n", end - start);
}
Output:
Name – Palash N Doshi
Roll No – BACO18164

Artificial Intelligence & Robotics

Assignment -1

Implement Tic Tac Toe using A* Algorithm


Code –
import java.util.Scanner;
public class TicTacToeTest{

public static void main(String[ ] args) {

TicTacToe t = new TicTacToe();


Scanner s = new Scanner(System.in);
int x=0,y=0;
do
{
System.out.println(t.player==t.X?"Player X turn":"Player O turn");
System.out.println("Enter x and y places");
x=s.nextInt();
y=s.nextInt();

t.putSign(x, y);
System.out.println(t.toString());
System.out.println("_____________________________");
t.displayWinner();

}while(t.isEmpty);
}
}
class TicTacToe
{
public static final int X = 1, O = -1;
public static final int EMPTY = 0;
public int player = X;
private int[][] board = new int[3][3];
public boolean isEmpty = false;

/** Puts an X or O mark at position i,j. */


public void putSign(int x, int y)
{
if(x<0 || x>2 || y<0 || y>2)
{
System.out.println("Invalid board position");
return;
}
if(board[x][y] != EMPTY)
{
System.out.println("Board position occupied");
return;
}
board[x][y] = player; // place the mark for the current player
player = -player; // switch players (uses fact that O = - X)
}
Name – Palash N Doshi
Roll No – BACO18164

/** Checks whether the board configuration is a win for the given player. */
public boolean isWin(int player)
{
return ((board[0][0] + board[0][1] + board[0][2] == player*3) ||
(board[1][0] + board[1][1] + board[1][2] == player*3) ||
(board[2][0] + board[2][1] + board[2][2] == player*3) ||
(board[0][0] + board[1][0] + board[2][0] == player*3) ||
(board[0][1] + board[1][1] + board[2][1] == player*3) ||
(board[0][2] + board[1][2] + board[2][2] == player*3) ||
(board[0][0] + board[1][1] + board[2][2] == player*3) ||
(board[2][0] + board[1][1] + board[0][2] == player*3));
}
/**display the winning player or indicate a tie (or unfinished game).*/
public void displayWinner()
{
if(isWin(X))
{
System.out.println("\n X wins...!!");
isEmpty=false;
}
else if(isWin(O))
{
System.out.println("\n O wins...!!");
isEmpty=false;
}
else
{
if(!isEmpty)
{
System.out.println("its a tie");
}
}
}
public String toString()
{
StringBuilder s = new StringBuilder();
isEmpty = false;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
switch(board[i][j])
{
case X:
s.append(" X ");
break;
case O:
s.append(" O ");
break;
case EMPTY:
s.append(" ");
isEmpty=true;
break;
}
Name – Palash N Doshi
Roll No – BACO18164

if(j<2)
{
s.append("|");
}

}
if(i<2)
{
s.append("\n-----------\n");
}
}
return s.toString();
}

Output –
Name – Palash N Doshi
Roll No – BACO18164

Assignment - 2

Solve 8-puzzle problem using A*algorithm. Assume any initial configuration and Define
goal configuration clearly
Code: //file – Solution.java
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Scanner;
public class Solution
{
//priority queue is created for holding all the state objects created.
// Array List 'expanded' is created for holding all expanded states information.
public static PriorityQueue<State> pq = new PriorityQueue<State>();
public static ArrayList<State> expanded = new ArrayList<State>();
public static String[][] goal;
//Below constructor of Solution Class is initiated by the State class object 'first'
public Solution(State first) {
if(first==null) {
System.out.println("Please provide an input");
}
pq.add(first);
ArrayList<State> list = new ArrayList<State>();
while(!pq.isEmpty())
{
int visited;
State current = pq.poll(); //returns and deletes the first node of the
priority queue and store it in 'current' variable.
expanded.add(current); //Adds current object to the 'end' list<State> which
holds all the expanded nodes
if(Arrays.deepEquals(current.blocks, goal))
{
break;
}
list = current.expand(current); //expands the current node and the child
nodes are stored in the list<State>
//Below code verify whether the node expanded is already visited by verifying in the 'end' array
list
for (State l:list)
{
visited = 0;
for (State e:expanded)
{
if(Arrays.deepEquals(l.blocks, e.blocks))
{
visited = 1;
}
}
Name – Palash N Doshi
Roll No – BACO18164

if(visited==1)
continue;
pq.add(l);
}
}
}
public static void main(String args[])
{
String a[][];
int i,j,rows,columns;
rows=columns=3;
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
a = new String[rows][columns];
goal = new String[rows][columns];
System.out.println("Please input the elements for initial state :");
// The below code validates the input provided by the user and terminates for invalid input.
for (i=0;i<a.length;i++)
{
for(j=0;j<a.length;j++)
{
a[i][j] = sc.nextLine();
if(a[i][j].length()!=1 || (a[i][j].charAt(0)<'1' && a[i][j].charAt(0)!='
') || a[i][j].charAt(0)>'8')
{
System.out.println("Error: Input should be any number
between 1 to 8 or a single space\nProgram Terminated");
return;
}
}
}
System.out.println("Please input the Goal state:");
// The below code validates the goal input provided by the user and terminates for invalid input.

for (i=0;i<goal.length;i++)
{
for(j=0;j<goal.length;j++)
{
goal[i][j] = sc.nextLine();
if(goal[i][j].length()!=1 || (a[i][j].charAt(0)<'1' &&
a[i][j].charAt(0)!=' ') || a[i][j].charAt(0)>'8')
{
System.out.println("Error: Input should be any number
between 1 to 8 or a single space\nProgram Terminated");
return;
}
}
}
long startTime=System.currentTimeMillis();
State state = new State(a,0);
Name – Palash N Doshi
Roll No – BACO18164

new Solution(state);
for(State states:expanded) {
for (int l = 0;l<3;l++)
{
for (int m=0;m<3;m++)
{
System.out.print(states.blocks[l][m]+"\t");
}
System.out.println();
}
System.out.println("f(n) :"+states.f);
System.out.println("h(n) :"+(states.f-states.level));
System.out.println("g(n) :"+(states.level));
System.out.println('\n');
}
System.out.println("Total Nodes expanded:"+expanded.size());
System.out.println("Total Nodes generated"+(expanded.size()+pq.size()));
//Below code is responsible for calculating the total time taken for generating the nodes and
display the output.
long endTime=System.currentTimeMillis();
System.out.println("Time Taken in milli seconds: "+(endTime-startTime));
}
}
//file state.java
package airprograms;

import java.util.ArrayList;

import airprograms.Solution;

public class State implements Comparable<State>


{
public int f;
public String[][] blocks;
public int level;

public State(String[][] a, int level)


{
int N = a.length;
this.blocks = new String[N][N];
for (int i=0;i<N;i++)
{
for (int j=0; j<N; j++)
{
this.blocks[i][j] = a[i][j];
}
}
this.level = level;
this.f = manhattan()+level;
}
Name – Palash N Doshi
Roll No – BACO18164

/*Below function calculates the Manhattan distance(heuristic value) for each state or node.
I.e the sum of the distances of the tiles from their goal positions*/
private int manhattan()
{
int sum=0;
int[] index= new int[2];
int N = Solution.goal.length;
for (int i = 0;i<N;i++)
{
for (int j = 0; j<N; j++)
{
if(this.blocks[i][j].trim().isEmpty())
{
continue;
}
index = find_index(Integer.parseInt(this.blocks[i][j]));
sum = sum + (Math.abs(i-index[0])+Math.abs(j-index[1]));
}
}
return sum;
}
//Below method find the indices of a particular element in the goal state and return them in an array.
private int[] find_index(int a)
{
int[] index = new int[2];
int N = Solution.goal.length;
for (int i = 0;i<N; i++)
{
for (int j = 0; j<N; j++)
{
if(Solution.goal[i][j].trim().isEmpty())
{
continue;
}
if (Solution.goal[i][j].trim().equals(String.valueOf(a)))
{
index[0]=i;
index[1]=j;
return index;
}
}
}
return index;
}
//Below method generates all the possible child nodes from a given parent node.
public ArrayList<State> expand(State parent)
{
ArrayList<State> successor= new ArrayList<State>();
int N = this.blocks.length;
for (int i=0; i< N; i++)
Name – Palash N Doshi
Roll No – BACO18164

{
for (int j = 0; j<N; j++)
{
if (parent.blocks[i][j].trim().isEmpty()) //search for the index of
space in the state(where a tile can be moved)
{
if(i-1>=0)//checks whether tile can be moved towards top.
{
String[][] a = new String[N][N];
for (int l=0;l<N;l++)
{
for(int m=0;m<N;m++)
{
a[l][m]=parent.blocks[l][m];
}
}
a = swap(a,i,j,i-1,j);
State b = new State(a,parent.level+1);
successor.add(b);
}

if(j-1>=0)//checks whether a tile can be moved towards left of the space.


{
String[][] a = new String[N][N];
for (int l=0;l<N;l++)
{
for(int m=0;m<N;m++)
{
a[l][m]=parent.blocks[l][m];
}
}
a = swap(a,i,j,i,j-1);
State b = new State(a,parent.level+1);
successor.add(b);
}
if(i+1<N)//checks whether a tile can be moved towards downward.
{
String[][] a = new String[N][N];
for (int l=0;l<N;l++)
{
for(int m=0;m<N;m++)
{
a[l][m]=parent.blocks[l][m];
}
}
a = swap(a,i,j,i+1,j);
State b = new State(a,parent.level+1);
successor.add(b);
}
if(j+1<N)//checks whether a tile can be moved towards right side.
Name – Palash N Doshi
Roll No – BACO18164

{
String[][] a = new String[N][N];
for (int l=0;l<N;l++)
{
for(int m=0;m<N;m++)
{
a[l][m]=parent.blocks[l][m];
}
}
a = swap(a,i,j,i,j+1);
State b = new State(a,parent.level+1);
successor.add(b);
}
}
}
}
return successor;
}
//Below method is for swapping the desired elements in the indices of the blocks provided
private String[][] swap(String[][] a,int row1, int col1, int row2, int col2)
{
String[][] copy = a;
String tmp = copy[row1][col1];
copy[row1][col1] = copy[row2][col2];
copy[row2][col2] = tmp;

return copy;
}
@Override
public int compareTo(State o) {
if(this.f==o.f)
{
return ((this.manhattan() - o.manhattan()));
}
return this.f-o.f;
}}

Output:
Name – Palash N Doshi
Roll No – BACO18164
Name – Palash N Doshi
Roll No – BACO18164

Assignment - 3

Use Heuristic Search Techniques to Implement Hill-Climbing Algorithm.


Code:
import java.util.*;

public class HillClimbingAlgorithm {


state gstate, cstate, sstate;
Scanner sc = new Scanner(System.in);
ArrayList<state> ngb = new ArrayList<state>();

HillClimbingAlgorithm() {
gstate = new state();
cstate = new state();
sstate = new state();
}

void display(state s) {
int k = 0;
for (int j = 0; j < 3; j++) {
for (int i = 0; i < 3; i++) {
System.out.print(" " + s.arr[k]);
k++;
}
System.out.println();
}

void input() {

System.out.println("Enter the start state");


for (int i = 0; i < 9; i++) {
sstate.arr[i] = sc.nextInt();
}

System.out.println("Enter the goal state");


for (int i = 0; i < 9; i++) {
gstate.arr[i] = sc.nextInt();
}

int h(state s) {
int hvalue = 0;
for (int i = 0; i < 9; i++) {
if (s.arr[i] != gstate.arr[i]) {
hvalue++;
}
}

return hvalue;
}

int blpos(state s) {
for (int j = 0; j < 9; j++) {
if (s.arr[j] == 0) {
return j;
Name – Palash N Doshi
Roll No – BACO18164

}
}
return 0;
}

void Movegen(state s) {
int p = blpos(s);
// int temp=0;
ngb.clear();
if (p % 3 != 0) {
state n1 = new state(s);
// temp=n1.arr[p];
n1.arr[p] = n1.arr[p - 1];
n1.arr[p - 1] = 0;
n1.h = h(n1);
ngb.add(n1);
}

if (p < 6) {
state n1 = new state(s);
// temp=n1.arr[p];
n1.arr[p] = n1.arr[p + 3];
n1.arr[p + 3] = 0;
n1.h = h(n1);
ngb.add(n1);
}
if (p > 2 && p < 9) {
state n1 = new state(s);
// temp=n1.arr[p];
n1.arr[p] = n1.arr[p - 3];
n1.arr[p - 3] = 0;
n1.h = h(n1);
ngb.add(n1);
}
if (p % 3 != 2) {
state n1 = new state(s);
// temp=n1.arr[p];
n1.arr[p] = n1.arr[p + 1];
n1.arr[p + 1] = 0;
n1.h = h(n1);
ngb.add(n1);
}

int lowestscore() {
int i = 0, min = 999;
for (int j = 0; j < ngb.size(); j++) {
if (min > ngb.get(j).h) {
min = ngb.get(j).h;
i = j;
}
}

return i;
}
// ============== Actual algorithm
state hillclimbing() {
int low = 0, done = 0;
state n, nn;
Name – Palash N Doshi
Roll No – BACO18164

sstate.h = h(sstate);
sstate.paraent = null;
n = sstate;
Movegen(n);
low = lowestscore();
nn = ngb.get(low);
display(n);
System.out.println();
while (nn.h < n.h) {
display(nn);
System.out.println();
nn.paraent = n;
n = nn;

Movegen(n);
low = lowestscore();
nn = ngb.get(low);
}
return nn;

public static void main(String[] args) {


// TODO Auto-generated method stub

HillClimbingAlgorithm ob = new HillClimbingAlgorithm();


ob.input();
ob.hillclimbing();

}
Output:
Name – Palash N Doshi
Roll No – BACO18164

Assignment - 4

Use Heuristic Search Techniques to Implement Best first search and A*algorithm
Code:
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.PriorityQueue;
import java.util.Scanner;

public class BestFirstSearch


{
private PriorityQueue<Vertex> priorityQueue;
private int heuristicvalues[];
private int numberOfNodes;

public static final int MAX_VALUE = 999;

public BestFirstSearch(int numberOfNodes)


{
this.numberOfNodes = numberOfNodes;
this.priorityQueue = new PriorityQueue<Vertex>(this.numberOfNodes,
new Vertex());
}

public void bestFirstSearch(int adjacencyMatrix[][], int[] heuristicvalues,int source)


{
int evaluationNode;
int destinationNode;
int visited[] = new int [numberOfNodes + 1];
this.heuristicvalues = heuristicvalues;

priorityQueue.add(new Vertex(source, this.heuristicvalues[source]));


visited[source] = 1;

while (!priorityQueue.isEmpty())
{
evaluationNode = getNodeWithMinimumHeuristicValue();
destinationNode = 1;

System.out.print(evaluationNode + "\t");
while (destinationNode <= numberOfNodes)
{
Vertex vertex = new Vertex(destinationNode,this.heuristicvalues[destinationNode]);
if ((adjacencyMatrix[evaluationNode][destinationNode] != MAX_VALUE
&& evaluationNode != destinationNode)&& visited[destinationNode] == 0)
{
priorityQueue.add(vertex);
visited[destinationNode] = 1;
}
destinationNode++;
Name – Palash N Doshi
Roll No – BACO18164

}
}
}

private int getNodeWithMinimumHeuristicValue()


{
Vertex vertex = priorityQueue.remove();
return vertex.node;
}

public static void main(String... arg)


{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
int heuristicvalues[];

Scanner scan = new Scanner(System.in);


try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
heuristicvalues = new int[number_of_vertices + 1];

System.out.println("Enter the Weighted Matrix for the graph");


for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = MAX_VALUE;
}
}
}
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
{
adjacency_matrix[j][i] = 1;
}
Name – Palash N Doshi
Roll No – BACO18164

}
}

System.out.println("Enter the heuristic values of the nodes");


for (int vertex = 1; vertex <= number_of_vertices; vertex++)
{
System.out.print(vertex + ".");
heuristicvalues[vertex] = scan.nextInt();
System.out.println();
}

System.out.println("Enter the source ");


source = scan.nextInt();

System.out.println("The graph is explored as follows");


BestFirstSearch bestFirstSearch = new BestFirstSearch(number_of_vertices);
bestFirstSearch.bestFirstSearch(adjacency_matrix, heuristicvalues,source);

} catch (InputMismatchException inputMismatch)


{
System.out.println("Wrong Input Format");
}
scan.close();
}
}

class Vertex implements Comparator<Vertex>


{
public int heuristicvalue;
public int node;

public Vertex(int node, int heuristicvalue)


{
this.heuristicvalue = heuristicvalue;
this.node = node;
}

@Override
public int compare(Vertex vertex1, Vertex vertex2)
{
if (vertex1.heuristicvalue < vertex2.heuristicvalue)
return -1;
if (vertex1.heuristicvalue > vertex2.heuristicvalue)
return 1;
return 0;
}

@Override
public boolean equals(Object obj)
{
Name – Palash N Doshi
Roll No – BACO18164

if (obj instanceof Vertex)


{
Vertex node = (Vertex) obj;
if (this.node == node.node)
{
return true;
}
}
return false;
}
}

Output:
Name – Palash N Doshi
Roll No – BACO18164

Data Analytics
Assignment - 1
Download the Iris flower dataset or any other dataset into a DataFrame. (eg.
https://archive.ics.uci.edu/ml/datasets/Iris ) Use Python/R and Perform following – • How many features are
there and what are their types (e.g., numeric, nominal)? • Compute and display summary statistics for each
feature available in the dataset. (eg. minimum value, maximum value, mean, range, standard deviation, variance
and percentiles • Data Visualization-Create a histogram for each feature in the dataset to illustrate the feature
distributions. Plot each histogram. • Create a boxplot for each feature in the dataset. All of the boxplots should
be combined into a single plot. Compare distributions and identify outliers.

Code :
import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

data = pd.read_csv("F:/apuu c++/BEsubmission/LP-I Submission/DA Assign/Assign1/iris.csv")

data.head()

data.dtypes

data.describe()

range_sepal_length = [data['Sepal length'].min(),data['Sepal length'].max()]

range_sepal_width = [data['Sepal width'].min(),data['Sepal width'].max()]

range_petal_length = [data['Petal length'].min(),data['Petal length'].max()]

range_petal_width = [data['Petal width'].min(),data['Petal width'].max()]

print("Range of sepal length is {} ".format(range_sepal_length))

print("Range of sepal width is {} ".format(range_sepal_width))

print("Range of petal length is {} ".format(range_petal_length))

print("Range of petal width is {} ".format(range_petal_width))

plt.hist(data['Sepal length'],bins=10)

plt.ylabel('No of times')

plt.xlabel('Sepal Length')
Name – Palash N Doshi
Roll No – BACO18164

plt.show()

data.head().plot.bar()

n, bins, patches = plt.hist(df.head(), 4, facecolor='blue', alpha=0.5)

plt.show()

data.head()

df = pd.DataFrame(data,columns=['Sepal width', 'Sepal length', 'Petal length', 'Petal width'])

boxplot =df.boxplot(column=['Sepal width', 'Sepal length', 'Petal length', 'Petal width'])

Output:
Name – Palash N Doshi
Roll No – BACO18164
Name – Palash N Doshi
Roll No – BACO18164

Assignment - 2
Download Pima Indians Diabetes dataset. Use Naive Bayes Algorithm for classification Load the data from
CSV file and split it into training and test datasets. summarize the properties in the training dataset so that we
can calculate probabilities and make predictions. Classify samples from a test dataset and a summarized training
dataset

Code :
import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

import seaborn as sns

data = pd.read_csv('F:/apuu c++/BEsubmission/LP-I Submission/DA Assign/Assign2/diabetes.csv')

data.head()

data.shape

data.corr()

data.describe()

data_true = len(data.loc[data['Outcome']==True])

data_false = len(data.loc[data['Outcome']==False])

data_true,data_false

data.dtypes

from sklearn.naive_bayes import GaussianNB

from sklearn.metrics import accuracy_score

from sklearn.model_selection import train_test_split

import numpy as np

featured_values=['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness',

'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age']

predicted_class = ['Outcome']

X = data[featured_values].values
Name – Palash N Doshi
Roll No – BACO18164

Y = data[predicted_class].values

x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=.2, random_state=5)

clf = GaussianNB()

clf.fit(x_train, y_train.flatten())

predictions = clf.predict(x_test)

print('Accuracy Score: ', accuracy_score(predictions, y_test))

data1 = pd.read_csv('F:/apuu c++/BEsubmission/LP-I Submission/DA Assign/Assign2/diabetes.csv')

data1.head()

featured_values=['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness',

'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age']

predicted_class = ['Outcome']

X = data1[featured_values].values

Y = data1[predicted_class].values

x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=.2, random_state=5)

from sklearn.preprocessing import Imputer

fill_values = Imputer(missing_values=0, strategy="mean", axis=0)

x_train = fill_values.fit_transform(x_train)

x_test = fill_values.fit_transform(x_test)

clf = GaussianNB()

clf.fit(x_train, y_train.flatten())
Name – Palash N Doshi
Roll No – BACO18164

predictions = clf.predict(x_test)

print('Accuracy Score: ', accuracy_score(predictions, y_test))

from sklearn.metrics import confusion_matrix

results = confusion_matrix(y_test, predictions)

print(results)

from sklearn.metrics import classification_report

print(classification_report(y_test,predictions))

Output :
Name – Palash N Doshi
Roll No – BACO18164

Assignment - 3
Trip History Analysis: Use trip history dataset that is from a bike sharing service in the United States. The data is
provided quarter-wise from 2010 (Q4) onwards. Each file has 7 columns. Predict the class of user. Sample Test data set
available here https://www.capitalbikeshare.com/trip-history-data .

Code:
import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

data = pd.read_csv('F:/apuu c++/BEsubmission/LP-I Submission/DA Assign/Assign3/tripdata.csv')

data.head()

data.describe()

data.dtypes

data = data.drop('Start date',axis=1)

data = data.drop('End date',axis=1)

data = data.drop('Start station',axis=1)

data = data.drop('End station',axis=1)

from sklearn.preprocessing import LabelEncoder

labelencoder = LabelEncoder()

data['Member type'] = labelencoder.fit_transform(data['Member type'])

data.sample(7)

from sklearn.preprocessing import LabelEncoder

labelencoder = LabelEncoder()

data['Bike number'] = labelencoder.fit_transform(data['Bike number'])

data.sample(7)
Name – Palash N Doshi
Roll No – BACO18164

data.describe()

data['Bike number'].unique()

from sklearn.naive_bayes import GaussianNB

from sklearn.metrics import accuracy_score

from sklearn.model_selection import train_test_split

import numpy as np

featured_values=['Duration', 'Start station number', 'End station number', 'Bike number']

predicted_class = ['Member type']

X = data[featured_values].values

Y = data[predicted_class].values

x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=.2)

clf = GaussianNB()

clf.fit(x_train, y_train.flatten())

predictions = clf.predict(x_test)

print('Accuracy Score: ', accuracy_score(predictions, y_test))

a = pd.DataFrame(y_test)

a.nunique()

from sklearn.metrics import confusion_matrix

results = confusion_matrix(y_test, predictions)

print(results)

from sklearn.metrics import classification_report


Name – Palash N Doshi
Roll No – BACO18164

print(classification_report(y_test,predictions))

Output :
Name – Palash N Doshi
Roll No – BACO18164

Assignment - 4
Twitter Data Analysis: Use Twitter data for sentiment analysis. The dataset is 3MB in size and has 31,962 tweets. Identify
the tweets which are hate tweets and which are not.Implement the sentiment analysis of twitter data. Implement the
following operations: 1. Sentiment analysis of twitter dataset. 2. Classify the tweets as positive and negative tweets from
dataset.

Code:
import pandas as pd

import re

train=pd.read_csv("train.csv")

train.head()

train.drop("id",inplace=True,axis=1)

import nltk

nltk.download()

from nltk.stem import PorterStemmer

stemmer = PorterStemmer()

def clean_sentences(text):

text = text.lower()

text = re.sub(r"[^a-z0-9^,!.\/']", " ", text)

text = " ".join(text.split())

text = " ".join(stemmer.stem(word) for word in text.split())

return text

x = train['tweet']

y = train['label']

x = x.map(lambda a: clean_sentences(a))

x.head()

from sklearn.model_selection import train_test_split


Name – Palash N Doshi
Roll No – BACO18164

x_train, x_test, y_train, y_test = train_test_split(x,y,stratify=y,random_state=42)

x_train.head()

from sklearn.feature_extraction.text import TfidfVectorizer

vectorizer = TfidfVectorizer(stop_words='english')

x_train = vectorizer.fit_transform(x_train)

x_text = vectorizer.transform(x_test)

from sklearn.svm import LinearSVC

model = LinearSVC(C=1.05, tol=0.5)

model.fit(x_train,y_train)

from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, f1_score, recall_score

confusion_matrix(y_test,model.predict(x_test))

accuracy_score(y_test,model.predict(x_test))

recall_score(y_test,model.predict(x_test))

precision_score(y_test,model.predict(x_test))

f1_score(y_test,model.predict(x_test))

Output :
Name – Palash N Doshi
Roll No – BACO18164

You might also like