converted_text (1)
converted_text (1)
BFS
#include<iostream>
#include<omp.h>
#include<vector>
#include<stack>
#include<queue>
#include<chrono>
using namespace std;
class Graph{
public:
int vertices = 6;
int edges = 5;
void printGraph(){
for(int i = 0; i < vertices; i++){
cout << i << " -> ";
for(int j = 0; j < graph[i].size();j++){
cout << graph[i][j] << " ";
}
cout << endl;
}
}
void initialize_visited(){
visited.assign(vertices,false);
}
while(q.empty() != true){
int current = q.front();
q.pop();
cout << current << " ";
while(q.empty() != true){
int current;
#pragma omp critical
{ current = q.front(); q.pop(); }
return 0;
}
=========================================
DFS
#include<iostream>
#include<omp.h>
#include<vector>
#include<stack>
#include<queue>
#include<chrono>
using namespace std;
class Graph{
public:
int vertices = 6;
int edges = 5;
vector<vector<int>> graph = {{1},{0,2,3},{1,4,5},{1,4},{2,3},{2}};
vector<bool> visited;
void printGraph(){
for(int i = 0; i < vertices; i++){
cout << i << " -> ";
for(int j = 0; j < graph[i].size();j++){
cout << graph[i][j] << " ";
}
cout << endl;
}
}
void initialize_visited(){
visited.assign(vertices,false);
}
};
int main()
{
Graph g;
cout << "Adjacency List:\n";
g.printGraph();
g.initialize_visited(); //set all vertices to unvisited , -1
return 0;
}
============================================
Write a program to implement Parallel Bubble Sort and Merge sort using OpenMP. Use existing
algorithms and measure the performance of sequential and parallel algorithms.
Bubble-Sort
#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>
#include <omp.h>
if (k % 2 == 0) {
#pragma omp parallel for
for (int i = 1; i < arr.size() - 1; i += 2) {
if (arr[i] > arr[i + 1]) {
swap(arr[i], arr[i + 1]);
}
}
} else {
#pragma omp parallel for
for (int i = 0; i < arr.size() - 1; i += 2) {
if (arr[i] > arr[i + 1]) {
swap(arr[i], arr[i + 1]);
}
}
}
}
}
vector<int> array;
cout << "\nTotal Time Required: " << duration.count() << " µs\n";
==================================================
Merge-Sort
#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>
#include <omp.h>
return 0;
}
======================================================
3.Implement Min, Max, Sum and Average operations using Parallel Reduction.
#include <iostream>
#include <vector>
#include <omp.h>
#include <climits>
int main() {
vector<int> arr;
arr.push_back(5);
arr.push_back(2);
arr.push_back(9);
arr.push_back(1);
arr.push_back(7);
arr.push_back(6);
arr.push_back(8);
arr.push_back(3);
arr.push_back(4);
min_reduction(arr);
max_reduction(arr);
sum_reduction(arr);
average_reduction(arr);
}
=============================
Write a CUDA Program for : Matrix Multiplication
#include <cuda_runtime.h>
#include <iostream>
// Free memory
cudaFree(dev_A);
cudaFree(dev_B);
cudaFree(dev_C);
cudaFreeHost(A);
cudaFreeHost(B);
cudaFreeHost(C);
return 0;
}
============================
#include <iostream>
#include <cuda_runtime.h>
int main()
{
int n = 1000000;
int* A, * B, * C;
int size = n * sizeof(int);
// Free memory
cudaFree(dev_A);
cudaFree(dev_B);
cudaFree(dev_C);
cudaFreeHost(A);
cudaFreeHost(B);
cudaFreeHost(C);
return 0;
}
==============================================================================
===========
deep learning
Assignment 1: Linear regression by using Deep Neural network: Implement Boston housing price
prediction problem by Linear regression using Deep Neural network. Use Boston House price
prediction dataset
# Import necessary libraries
import numpy as np # For numerical operations
import pandas as pd # For handling datasets
from sklearn.model_selection import train_test_split # Splitting data into train & test sets
from sklearn.linear_model import LinearRegression # Linear Regression Model
from sklearn.preprocessing import StandardScaler # Standardization of data
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score # Evaluation
metrics
new_data_scaled = scaler.transform(new_data)
# Applying the same standardization as training data
#OutPut
1/1 0s 36ms/step
=====================================
2. Multiclass classification using Deep Neural Networks: Example: Use the OCR letter
recognition
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt
from sklearn import metrics
# X_train and X_test are our array of images while y_train and y_test are our array of labels for
each image.
# The first tuple contains the training set features (X_train) and the training set labels (y_train).
# The second tuple contains the testing set features (X_test) and the testing set labels (y_test).
# For example, if the image shows a handwritten 7, then the label will be the intger 7.
# image appears black and white and that each axis of the plot ranges from 0 to 28.
# This is because of the format that all the images in the dataset have:
# 1. All the images are grayscale, meaning they only contain black, white and grey.
# 2. The images are 28 pixels by 25 pixels in size (28x28).
print(x_train[0])
# image data is just an array of digits. You can almost make out a 5 from the pattern of the digits
in the array.
# Array of 28 values
# a grayscale pixel is stored as a digit between 0 and 255 where 0 is black, 255 is white and
values in between are different shades of gray.
# Therefore, each value in the [28][28] array tells the computer which color to put in that position
when we display the actual image.
# reformat our X_train array and our X_test array because they do not have the correct shape.
# Reshape the data to fit the model
print("X_train shape", x_train.shape)
print("y_train shape", y_train.shape)
print("X_test shape", x_test.shape)
print("y_test shape", y_test.shape)
# Here you can see that for the training sets we have 60,000 elements and the testing sets have
10,000 elements.
# y_train and y_test only have 1 dimensional shapes because they are just the labels of each
element.
# x_train and x_test have 3 dimensional shapes because they have a width and height (28x28
pixels) for each element.
# (60000, 28, 28) 1st parameter in the tuple shows us how much image we have 2nd and 3rd
parameters are the pixel values from x to y (28x28)
# The pixel value varies between 0 to 255.
# (60000,) Training labels with integers from 0-9 with dtype of uint8. It has the shape (60000,).
# (10000, 28, 28) Testing data that consists of grayscale images. It has the shape (10000, 28, 28)
and the dtype of uint8. The pixel value varies between 0 to 255.
# (10000,) Testing labels that consist of integers from 0-9 with dtype uint8. It has the shape
(10000,).
# Regarding the division by 255, this is the maximum value of a byte (the input feature's type
before the conversion to float32),
# so this will ensure that the input features are scaled between 0.0 and 1.0.
# USING svm-https://mgta.gmu.edu/courses/ml-with-python/
handwrittenDigitRecognition.php#:~:text=Remember%20that%20X_train%20has
%2060%2C000,keras.
# Convert class vectors to binary class matrices
num_classes = 10
y_train = np.eye(num_classes)[y_train] # Return a 2-D array with ones on the diagonal and zeros
elsewhere.
y_test = np.eye(num_classes)[y_test] # f your particular categories is present then it mark as 1
else 0 in remain row
========================================================================
3. Convolutional neural network (CNN): Use MNIST Fashion Dataset and create a classifier
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow import keras
import numpy as np
# There are 10 image classes in this dataset and each class has a mapping corresponding to the
following labels:
#0 T-shirt/top
#1 Trouser
#2 pullover
#3 Dress
#4 Coat
#5 sandals
#6 shirt
#7 sneaker
#8 bag
#9 ankle boot
# https://ml-course.github.io/master/09%20-%20Convolutional%20Neural%20Networks.pdf
plt.imshow(x_train[1])
plt.imshow(x_train[0])
# Next, we will preprocess the data by scaling the pixel values to be between 0 and 1, and then
reshaping the images to be 28x28 pixels.
# 28, 28 comes from width, height, 1 comes from the number of channels
# -1 means that the length in that dimension is inferred.
# This is done based on the constraint that the number of elements in an ndarray or Tensor when
reshaped must remain the same.
# each image is a row vector (784 elements) and there are lots of such rows (let it be n, so there
are 784n elements). So TensorFlow can infer that -1 is n.
# converting the training_images array to 4 dimensional array with sizes 60000, 28, 28, 1 for 0th
to 3rd dimension.
x_train.shape
x_test.shape
y_train.shape
y_test.shape
# We will use a convolutional neural network (CNN) to classify the fashion items.
# The CNN will consist of multiple convolutional layers followed by max pooling,
# dropout, and dense layers. Here is the code for the model:
model = keras.Sequential([
keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
# 32 filters (default), randomly initialized
# 3*3 is Size of Filter
# 28,28,1 size of Input Image
# No zero-padding: every output 2 pixels less in every dimension
# in Paramter shwon 320 is value of weights: (3x3 filter weights + 32 bias) * 32 filters
# 32*3*3=288(Total)+32(bias)= 320
keras.layers.MaxPooling2D((2,2)),
# It shown 13 * 13 size image with 32 channel or filter or depth.
keras.layers.Dropout(0.25),
# Reduce Overfitting of Training sample drop out 25% Neuron
keras.layers.MaxPooling2D((2,2)),
# It shown 5 * 5 size image with 64 channel or filter or depth.
keras.layers.Dropout(0.25),
keras.layers.Flatten(),
keras.layers.Dense(128, activation='relu'),
# 128 Size of Node in Dense Layer
# 1152*128 = 147584
keras.layers.Dropout(0.25),
keras.layers.Dense(10, activation='softmax')
# 10 Size of Node another Dense Layer
# 128*10+10 bias= 1290
])
model.summary()
# Finally, we will evaluate the performance of the model on the test data.
==========================================================================