0% found this document useful (0 votes)
5 views

Practical 7 Thsem

Uploaded by

gautampratik717
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Practical 7 Thsem

Uploaded by

gautampratik717
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Name : - Ayush Nautiyal

Year : - 4th
Semester:- 7th
Branch: CSE-AIML
Subject: Machine Learning for Data Science
Experiment 1

Q1 Write a program in Python to implement a divide and

conquer algorithm.

def max_number(arr):

if len(arr) == 1:

return arr[0]

else:

mid = len(arr) // 2

left_max = max_number(arr[:mid])

right_max = max_number(arr[mid:])

return max(left_max, right_max)

# Test the function

arr = [3, 7, 2, 9, 5, 8, 4, 1, 6]

result = max_number(arr)

print("The maximum number in the list is:", result)


Experiment 2

Write a program in Python to study the application of

randomization in algorithms.

import random

# Function to shuffle a list using randomization

def shuffle_list(input_list):

shuffled_list = input_list[:]

random.shuffle(shuffled_list)

return shuffled_list

# Test the function

original_list = [1, 2, 3, 4, 5]

shuffled_result = shuffle_list(original_list)

print("Original List:", original_list)

print("Shuffled List:", shuffled_result)


Experiment 3

Write a program in Python to study the application of

randomization in algorithms.

from collections import defaultdict

class Graph:

def __init__(self):

self.graph = defaultdict(list)

def add_edge(self, u, v):

self.graph[u].append(v)

def bfs(self, start):

visited = [False] * (len(self.graph))

queue = []

queue.append(start)

visited[start] = True

while queue:

start = queue.pop(0)
print(start, end=" ")

for i in self.graph[start]:

if not visited[i]:

queue.append(i)

visited[i] = True

# Create a graph

graph = Graph()

graph.add_edge(0, 1)

graph.add_edge(0, 2)

graph.add_edge(1, 2)

graph.add_edge(2, 0)

graph.add_edge(2, 3)

graph.add_edge(3, 3)

# Perform BFS traversal starting from vertex 2

print("BFS Traversal from vertex 2:")

graph.bfs(2)
Experiment 4

Write a program in Python to implement a search tree data

structure and evaluate its efficiency

class Node:

def __init__(self, key):

self.left = None

self.right = None

self.val = key

class BST:

def __init__(self):

self.root = None

def insert(self, root, key):

if root is None:

return Node(key)

if key < root.val:

root.left = self.insert(root.left, key)

else:

root.right = self.insert(root.right, key)

return root
def search(self, root, key):

if root is None or root.val == key:

return root

if root.val < key:

return self.search(root.right, key)

return self.search(root.left, key)

# Example usage:

bst = BST()

root = None

root = bst.insert(root, 50)

bst.insert(root, 30)

bst.insert(root, 20)

bst.insert(root, 40)

bst.insert(root, 70)

bst.insert(root, 60)

bst.insert(root, 80)

# Searching for a value in the tree

result = bst.search(root, 60)


if result:

print("Element 60 is found in the tree.")

else:

print("Element 60 is not found in the tree.")


Experiment 5

Write a program in Python to solve a linear programming

problem related to personal genomics data analysis.

from scipy.optimize import linprog

# Objective function coefficients (expression of genes)

c = [-3, -5, -4] # Replace with actual coefficients for each gene

# Coefficients of the inequality constraints matrix (resource


availability)

A=[

[1, 1, 1], # Constraint 1 coefficients (e.g., resource 1 usage for


genes)

[10, 5, 12], # Constraint 2 coefficients (e.g., resource 2 usage for


genes)

# Add more constraints as needed

# Constraints' upper bounds (resource availability limits)

b = [20, 50] # Replace with actual upper bounds for each constraint
# Bounds for variables (expression of genes)

x_bounds = [(0, None), (0, None), (0, None)] # Non-negative


expression values for genes

# Solve the linear programming problem

res = linprog(c, A_ub=A, b_ub=b, bounds=x_bounds, method='highs')

# Display results

if res.success:

print("Optimal expression values of genes:", res.x)

print("Maximum combined expression:", -res.fun)

else:

print("No feasible solution found.")


Experiment 6

Write a program in Python to understand NP completeness

through a practical problem-solving example.

def subset_sum(nums, target):

if target == 0:

return True

if not nums or target < 0:

return False

return subset_sum(nums[:-1], target - nums[-1]) or


subset_sum(nums[:-1], target)

# Example data

nums = [3, 7, 10, 12, 5]

target = 22

result = subset_sum(nums, target)

if result:

print(f"There exists a subset that sums up to the target {target}.")

else:

print(f"No subset found that sums up to the target {target}.").


Experiment 7

Write a program in Python to implement logistic regression on

a sample dataset.

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LogisticRegression

from sklearn.datasets import make_classification

from sklearn.metrics import accuracy_score, classification_report

# Generating a sample dataset

X, y = make_classification(n_samples=1000, n_features=10,
n_classes=2, random_state=42)

# Splitting the dataset into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,


random_state=42)

# Initializing and fitting the logistic regression model

model = LogisticRegression()

model.fit(X_train, y_train)

# Predicting on the test set

y_pred = model.predict(X_test)
# Evaluating the model

accuracy = accuracy_score(y_test, y_pred)

print(f"Accuracy: {accuracy:.2f}")

# Classification report

print("Classification Report:")

print(classification_report(y_test, y_pred))
Experiment 8

Write a program in Python to perform model selection using

cross-validation techniques on a machine learning problem.

from sklearn.datasets import load_iris

from sklearn.model_selection import cross_val_score

from sklearn.linear_model import LogisticRegression

# Load a sample dataset (for example, Iris dataset)

data = load_iris()

X, y = data.data, data.target

# Initialize the model (for example, Logistic Regression)

model = LogisticRegression()

# Perform cross-validation

cv_scores = cross_val_score(model, X, y, cv=5) # 5-fold cross-


validation

# Print the cross-validation scores

print("Cross-Validation Scores:", cv_scores)

print("Mean CV Score:", cv_scores.mean())


Experiment 9

Write a program in Python to implement a Naive Bayes

probabilistic model.

from sklearn.datasets import load_iris

from sklearn.model_selection import train_test_split

from sklearn.naive_bayes import GaussianNB

from sklearn.metrics import accuracy_score, classification_report

# Load a sample dataset (for example, Iris dataset)

data = load_iris()

X, y = data.data, data.target

# Split the dataset into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,


random_state=42)

# Initialize the Gaussian Naive Bayes model

model = GaussianNB()

# Fit the model on the training data

model.fit(X_train, y_train)
# Predict on the test data

y_pred = model.predict(X_test)

# Evaluate the model

accuracy = accuracy_score(y_test, y_pred)

print(f"Accuracy: {accuracy:.2f}")

# Classification report

print("Classification Report:")

print(classification_report(y_test, y_pred))
Experiment 10

Write a program in Python to clean and preprocess a real-

world dataset for machine learning applications.

import pandas as pd

from sklearn.preprocessing import StandardScaler, LabelEncoder

from sklearn.impute import SimpleImputer

# Load the dataset

data = pd.read_csv('your_dataset.csv')

# Display the first few rows of the dataset to understand its structure

print("Initial Dataset:")

print(data.head())

# Handling missing values (replace NaNs with mean value for


numerical columns)

imputer = SimpleImputer(strategy='mean')

data[numerical_columns] =
imputer.fit_transform(data[numerical_columns])

# Handling categorical data (label encoding or one-hot encoding)


label_encoder = LabelEncoder()

data['categorical_column'] =
label_encoder.fit_transform(data['categorical_column'])

# Scaling numerical features

scaler = StandardScaler()

data[numerical_columns] =
scaler.fit_transform(data[numerical_columns])

# Drop unnecessary columns if needed

data.drop(['column_to_drop1', 'column_to_drop2'], axis=1,


inplace=True)

# Save the cleaned dataset

data.to_csv('cleaned_dataset.csv', index=False) import pandas as pd

from sklearn.preprocessing import StandardScaler, LabelEncoder

from sklearn.impute import SimpleImputer

# Load the dataset

data = pd.read_csv('your_dataset.csv')

# Display the first few rows of the dataset to understand its structure
print("Initial Dataset:")

print(data.head())

# Handling missing values (replace NaNs with mean value for


numerical columns)

imputer = SimpleImputer(strategy='mean')

data[numerical_columns] =
imputer.fit_transform(data[numerical_columns])

# Handling categorical data (label encoding or one-hot encoding)

label_encoder = LabelEncoder()

data['categorical_column'] =
label_encoder.fit_transform(data['categorical_column'])

# Scaling numerical features

scaler = StandardScaler()

data[numerical_columns] =
scaler.fit_transform(data[numerical_columns])

# Drop unnecessary columns if needed

data.drop(['column_to_drop1', 'column_to_drop2'], axis=1,


inplace=True)

# Save the cleaned dataset

data.to_csv('cleaned_dataset.csv', index=False)
Name : - Ayush Nautiyal
Year : - 4th
Semester:- 7th
Branch: CSE-AIML
Subject: Internet and Web Technology
Experiment 1
Describe the CSS, CSS2 with suitable example
CSS (Cascading Style Sheets) and CSS2 (CSS Level 2) are style sheet languages used
to describe the presentation of a document written in markup languages like HTML
and XML. CSS2 is an extension of CSS that introduced several new features and
capabilities. Here's an overview of both:

CSS (Cascading Style Sheets):

CSS allows developers to control the style and layout of HTML elements. It defines
how HTML elements should be displayed on a web page

<!DOCTYPE html>

<html>

<head>

<title>My Website</title>

<style>

/* CSS styles */

body {

font-family: Arial, sans-serif;

background-color: #f0f0f0;

color: #333;

margin: 0;

padding: 20px;

}
h1 {

color: #0066cc;

p{

font-size: 16px;

line-height: 1.5;

</style>

</head>

<body>

<h1>Welcome to My Website</h1>

<p>This is a sample paragraph. CSS styles are applied to change


the appearance of this text.</p>

</body>

</html>

CSS2 (CSS Level 2):

CSS2 introduced additional capabilities and expanded the styling options compared
to the original CSS. It added features like positioning, media types, improved
selectors, and more.

<!DOCTYPE html>

<html>

<head>
<title>My Website</title>

<style>

/* CSS2 styles */

div {

border: 1px solid #ccc;

padding: 10px;

margin-bottom: 20px;

.highlight {

background-color: yellow;

#footer {

position: fixed;

bottom: 0;

width: 100%;

background-color: #333;

color: #fff;

padding: 10px;

text-align: center;
}

</style>

</head>

<body>

<div>

<h1>Welcome to My Website</h1>

<p>This is a sample paragraph.</p>

<p class="highlight">This paragraph has a highlight class


applied.</p>

</div>

<div id="footer">

Footer content goes here.

</div>

</body>

</html>
Experiment 2
Describe the chatting components on the
internet.
Certainly! Chatting components on the internet refer to various elements and
technologies that enable communication between users in real-time or near real-
time. These components facilitate different forms of online communication, from
text-based conversations to audio and video interactions. Here are some key
components:

1. Instant Messaging (IM) Platforms:

 Messaging Apps: Applications like WhatsApp, Facebook Messenger, Telegram, and


Signal provide instant messaging services across devices.
 Web-Based Chat Clients: Web-based platforms like Slack, Microsoft Teams, and
Google Chat offer real-time messaging for teams and businesses.

2. Communication Protocols:

 XMPP (Extensible Messaging and Presence Protocol): An open-source protocol


used for instant messaging and presence information. It's the basis for various chat
applications.
 IRC (Internet Relay Chat): A protocol for real-time text messaging in channels on
the internet.

3. Chat Components in Websites and Applications:

 Chat Widgets: Live chat functionality integrated into websites for customer support
and engagement.
 Chat APIs and SDKs: Development tools and kits provided by various platforms to
integrate chat features into applications.

4. Voice and Video Chat:

 VoIP (Voice over Internet Protocol): Technologies like Skype, Zoom, and Google
Meet enable voice and video calls over the internet.
 WebRTC (Web Real-Time Communication): A free, open-source project that
enables web browsers with real-time communication capabilities via simple APIs.
5. Chatbots and AI Assistants:

 Chatbots: Automated conversational agents used for customer service, information


retrieval, and task automation.
 AI Assistants: Advanced chatbots utilizing artificial intelligence and natural language
processing to provide more sophisticated interactions.

6. Social Media Messaging:

 Social Media Platforms: Messaging components within social media networks like
Facebook, Twitter, Instagram, and LinkedIn enable communication among users.

7. Security and Encryption:

 End-to-End Encryption: Implemented in many chat applications to ensure privacy


and security by encrypting messages between sender and receiver.

8. Notification Systems:

 Push Notifications: Alerts sent to users' devices to inform them about new
messages or interactions in chat applications.

These components collectively form the infrastructure and tools for various forms of
online communication, facilitating interactions between individuals, businesses,
teams, and communities on the internet. The advancements in these technologies
continue to shape and redefine how people connect and collaborate online
Experiment 3
Design a calculator using html, Java script & PHP
Language.
<!DOCTYPE html>

<html>

<head>

<title>Simple Calculator</title>

<style>

.calculator {

width: 200px;

border: 1px solid #ccc;

padding: 10px;

input[type="button"] {

width: 40px;

height: 40px;

</style>

</head><body>

<div class="calculator">

<input type="text" id="display" readonly>


<br>

<input type="button" value="1" onclick="addToDisplay('1')">

<input type="button" value="2" onclick="addToDisplay('2')">

<input type="button" value="3" onclick="addToDisplay('3')">

<input type="button" value="+" onclick="addToDisplay('+')">

<br>

<input type="button" value="4" onclick="addToDisplay('4')">

<input type="button" value="5" onclick="addToDisplay('5')">

<input type="button" value="6" onclick="addToDisplay('6')">

<input type="button" value="-" onclick="addToDisplay('-')">

<br>

<input type="button" value="7" onclick="addToDisplay('7')">

<input type="button" value="8" onclick="addToDisplay('8')">

<input type="button" value="9" onclick="addToDisplay('9')">

<input type="button" value="*" onclick="addToDisplay('*')">

<br>

<input type="button" value="C" onclick="clearDisplay()">

<input type="button" value="0" onclick="addToDisplay('0')"

<input type="button" value="=" onclick="calculate()">

<input type="button" value="/" onclick="addToDispl


Experiment 4
Create your first web page using notepad in
HTML.

<!DOCTYPE html>

<html>

<head>

<title>My First Web Page</title>

</head>

<body>

<h1>Hello, World!</h1>

<p>This is my first web page created using Notepad.</p>

</body>

</html>
Experiment 5
Create your login webpage for your college
website or
company
Web site.
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Login</title>

<link rel="stylesheet" href="styles.css"> <!-- Link to your CSS file


for styling -->

</head>

<body>

<div class="login-container">

<h2>Login to Your Account</h2>

<form action="login_process.php" method="post">

<div class="input-group">

<label for="username">Username</label>

<input type="text" id="username" name="username"


required>
</div>

<div class="input-group">

<label for="password">Password</label>

<input type="password" id="password" name="password"


required>

</div>

<button type="submit">Login</button>

</form>

</div>

</body>

</html>

body {

font-family: Arial, sans-serif;

background-color: #f4f4f4;

margin: 0;

padding: 0;

display: flex;

justify-content: center;

align-items: center;

height: 100vh;

}
.login-container {

background-color: #fff;

padding: 20px;

border-radius: 5px;

box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

h2 {

text-align: center;

.input-group {

margin-bottom: 15px;

label {

display: block;

margin-bottom: 5px;

input[type="text"],
input[type="password"] {

width: 100%;

padding: 8px;

border-radius: 3px;

border: 1px solid #ccc;

button {

width: 100%;

padding: 10px;

background-color: #007bff;

color: #fff;

border: none;

border-radius: 3px;

cursor: pointer;

button:hover {

background-color: #0056b3;

}
Experiment 6
Create the web page with the following
constraints
using HTML,CSS & PHP
(a) An image on the webpage.
(b) A hyperlink to college website
(c) a table of marks of AIML students.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>AIML Student Marks</title>

<link rel="stylesheet" href="styles.css"> <!-- Link to your CSS file


for styling -->

</head>

<body>

<div class="header">

<h1>AIML Student Marks</h1>


<a href="https://www.collegewebsite.com"
target="_blank">Visit College Website</a>

</div>

<div class="content">

<img src="image.jpg" alt="AIML Students" width="300"


height="200">

<table>

<caption>AIML Student Marks</caption>

<thead>

<tr>

<th>Student ID</th>

<th>Student Name</th>

<th>Marks</th>

</tr>

</thead>

<tbody>

<?php

// PHP code to fetch and display marks from a database


or array

$aiml_students = [

["S001", "John Doe", 85],


["S002", "Alice Smith", 78],

["S003", "Bob Johnson", 92],

// Add more student data as needed

];

foreach ($aiml_students as $student) {

echo "<tr>";

foreach ($student as $value) {

echo "<td>$value</td>";

echo "</tr>";

?>

</tbody>

</table>

</div>

</body>

</html>
Experiment 7
Show blinking effect on web page using java
script.
<!DOCTYPE html>

<html>

<head>

<title>Blinking Effect</title>

<style>

.blinking-text {

font-size: 24px;

font-weight: bold;

</style>

</head>

<body>

<p class="blinking-text" id="blink">Blinking Text</p>

<script>

function blink() {

var blinkText = document.getElementById('blink');

setInterval(function() {
blinkText.style.visibility = (blinkText.style.visibility ==
'hidden') ? 'visible' : 'hidden';

}, 500); // Change the interval (in milliseconds) for speed


adjustment

blink(); // Start blinking when the page loads

</script>

</body>

</html>
Experiment 8
Design a digital clock on your web page using
javascript.
<!DOCTYPE html>
<html>
<head>
<title>Digital Clock</title>
<style>
.clock {
font-size: 36px;
font-weight: bold;
text-align: center;
margin-top: 100px;
}
</style>
</head>
<body>
<div class="clock" id="clock"></div>

<script>
function updateClock() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();

// Add leading zeroes to single digit hours,


minutes, and seconds
hours = (hours < 10) ? '0' + hours : hours;
minutes = (minutes < 10) ? '0' + minutes :
minutes;
seconds = (seconds < 10) ? '0' + seconds :
seconds;
var time = hours + ':' + minutes + ':' +
seconds;

document.getElementById('clock').innerText =
time;
}

// Update the clock every second


setInterval(updateClock, 1000);

// Initialize the clock immediately


updateClock();
</script>
</body>
</html>
Experiment 9
Design a digital calculator using HTML and java
Script.
<!DOCTYPE html>

<html>

<head>

<title>Simple Calculator</title>

<link rel="stylesheet" href="styles.css"> <!-- Link to your CSS file


for styling -->

</head>

<body>

<div class="calculator">

<input type="text" id="display" readonly>

<br>

<button onclick="appendToDisplay('7')">7</button>

<button onclick="appendToDisplay('8')">8</button>

<button onclick="appendToDisplay('9')">9</button>

<button onclick="appendToDisplay('/')">/</button>

<br>

<button onclick="appendToDisplay('4')">4</button>

<button onclick="appendToDisplay('5')">5</button>
<button onclick="appendToDisplay('6')">6</button>

<button onclick="appendToDisplay('*')">*</button>

<br>

<button onclick="appendToDisplay('1')">1</button>

<button onclick="appendToDisplay('2')">2</button>

<button onclick="appendToDisplay('3')">3</button>

<button onclick="appendToDisplay('-')">-</button>

<br>

<button onclick="clearDisplay()">C</button>

<button onclick="appendToDisplay('0')">0</button>

<button onclick="calculate()">=</button>

<button onclick="appendToDisplay('+')">+</button>

</div>

<script>

function appendToDisplay(value) {

document.getElementById('display').value += value;

function clearDisplay() {

document.getElementById('display').value = '';
}

function calculate() {

var expression = document.getElementById('display').value;

var result = eval(expression);

document.getElementById('display').value = result;

</script>

</body>

</html>
Experiment 10
Design the any four pages of web site of your
college.
<!DOCTYPE html>

<html>

<head>

<title>College Name - Home</title>

<link rel="stylesheet" href="styles.css">

</head>

<body>

<header>

<h1>Welcome to College Name</h1>

<nav>

<ul>

<li><a href="index.html">Home</a></li>

<li><a href="courses.html">Courses</a></li>

<li><a href="about.html">About</a></li>

<li><a href="contact.html">Contact</a></li>

</ul>

</nav>

</header>
<main>

<section>

<h2>About Our College</h2>

<p>Welcome to our college. Learn and grow with us!</p>

</section>

<section>

<h2>Latest Events</h2>

<p>Stay tuned for our upcoming events and workshops.</p>

</section>

</main>

<footer>

<p>&copy; 2023 College Name. All rights reserved.</p>

</footer>

</body>

</html>

<!DOCTYPE html>

<html>
<head>

<title>College Name - Courses</title>

<link rel="stylesheet" href="styles.css">

</head>

<body>

<header>

<!-- Navigation links same as Home page -->

</header>

<main>

<section>

<h2>Available Courses</h2>

<ul>

<li>Course 1</li>

<li>Course 2</li>

<li>Course 3</li>

<!-- Add more courses as needed -->

</ul>

</section>

<section>
<h2>Course Details</h2>

<p>Details about selected courses.</p>

</section>

</main>

<footer>

<!-- Footer content same as Home page -->

</footer>

</body>

</html>

<!DOCTYPE html>

<html>

<head>

<title>College Name - About</title>

<link rel="stylesheet" href="styles.css">

</head>

<body>

<header>

<!-- Navigation links same as Home page -->

</header>
<main>

<section>

<h2>About Us</h2>

<p>Information about the college, its history, and vision.</p>

</section>

<section>

<h2>Faculty Members</h2>

<p>Details about faculty members.</p>

</section>

</main>

<footer>

<!-- Footer content same as Home page -->

</footer>

</body>

</html>

<!DOCTYPE html>

<html>

<head>
<title>College Name - Contact</title>

<link rel="stylesheet" href="styles.css">

</head>

<body>

<header>

<!-- Navigation links same as Home page -->

</header>

<main>

<section>

<h2>Contact Information</h2>

<p>Address, phone, email, etc.</p>

</section>

<section>

<h2>Get in Touch</h2>

<p>Contact form or other ways to connect.</p>

</section>

</main>

<footer> <!-- Footer content same as Home page -->

</footer>

</body>

</html>

You might also like