Department of Computer Engineering BE Laboratory Practice-I A.Y 2021-22 SEM1
Department of Computer Engineering BE Laboratory Practice-I A.Y 2021-22 SEM1
Department of Computer Engineering BE Laboratory Practice-I A.Y 2021-22 SEM1
Patil Pratishthan’s
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
Assignment - 1
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++)
{
printf(" c conttents are =%d\n", c[i]);
}
*/
cudaFree(dev_a);
cudaFree(dev_b);
cudaFree(dev_c);
return 0;
}
Output:
Name – Palash N Doshi
Roll No – BACO18164
Assignment - 2
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
max<<<1,SIZE>>>(dev_a,dev_c); // call
kernel function <<<number of blocks, number of threads
printf("\nmin = %d ",c);
printf("");
return 0;
}
Output:
Name – Palash N Doshi
Roll No – BACO18164
Assignment – 3
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);
*/
srand(time(0));
printf("%d\t", fst[c][d]);
}
printf("\n");
}
}
printf("\n");
}
Name – Palash N Doshi
Roll No – BACO18164
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));
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);
// 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
}
}
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);
Output:
Name – Palash N Doshi
Roll No – BACO18164
Assignment - 5
{
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;
}
{
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
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
Assignment -1
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;
/** 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;
/*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);
}
{
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
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() {
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;
}
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;
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
}
}
}
}
}
@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
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
data.head()
data.dtypes
data.describe()
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()
plt.show()
data.head()
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
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
import numpy as np
predicted_class = ['Outcome']
X = data[featured_values].values
Name – Palash N Doshi
Roll No – BACO18164
Y = data[predicted_class].values
clf = GaussianNB()
clf.fit(x_train, y_train.flatten())
predictions = clf.predict(x_test)
data1.head()
predicted_class = ['Outcome']
X = data1[featured_values].values
Y = data1[predicted_class].values
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(results)
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
data.head()
data.describe()
data.dtypes
labelencoder = LabelEncoder()
data.sample(7)
labelencoder = LabelEncoder()
data.sample(7)
Name – Palash N Doshi
Roll No – BACO18164
data.describe()
data['Bike number'].unique()
import numpy as np
X = data[featured_values].values
Y = data[predicted_class].values
clf = GaussianNB()
clf.fit(x_train, y_train.flatten())
predictions = clf.predict(x_test)
a = pd.DataFrame(y_test)
a.nunique()
print(results)
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()
stemmer = PorterStemmer()
def clean_sentences(text):
text = text.lower()
return text
x = train['tweet']
y = train['label']
x = x.map(lambda a: clean_sentences(a))
x.head()
x_train.head()
vectorizer = TfidfVectorizer(stop_words='english')
x_train = vectorizer.fit_transform(x_train)
x_text = vectorizer.transform(x_test)
model.fit(x_train,y_train)
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