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

3170724-machine-learning-lab-manual

Uploaded by

naresh.asus.tuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

3170724-machine-learning-lab-manual

Uploaded by

naresh.asus.tuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

INDEX

Sr. Practical Page Date Sign


No. No.

1 Write a program to Implementation of mean, 1


median and mode

2 Write a program to implement Data distribution 2


histogram.

3 Write a program to implement scatter plot using 3


given dataset

4 Write a program to Implementation of linear 4


regression from given dataset

5 Write a program to implement Scale 5

6 Write a program to training and testing from given 6


dataset

7 Write a program to Implementation of Decision 7


tree from given dataset

8 Write a program to Implement K-Nearest 8


Neighbors Algorithm from given dataset

9 Write a program to implementation of K- Mean 9


clustering from given dataset

10 10
Write a program to implementation of hierarchical
clustering from dataset
Machine Learning[1010206715] 2107020601029

Practical-1
Aim: - Write a program to Implementation of mean, median and mode.
import statistics
def main():
num_list = input("Enter a list of numbers separated by spaces:
").split() num_list = [int(num) for num in num_list]

# Calculate the mean


mean =
statistics.mean(num_list)
print(f"Mean: {mean}")

# Calculate the median


median =
statistics.median(num_list)
print(f"Median: {median}")

# Calculate the mode


try:
mode =
statistics.mode(num_list)
print(f"Mode: {mode}")
except statistics.StatisticsError:
print("No unique mode found.")
if name == " main ":
main()

Output: -

BAIT,Surat 1
Machine Learning[1010206715] 2107020601029

Practical-2
Aim: - Write a program to implement Data distribution histogram.
import matplotlib.pyplot as
plt import numpy as np
data = np.random.normal(0, 1, 1000) # Generate 1000 random data points with mean 0 and
standard deviation 1
plt.hist(data, bins=20, edgecolor='k') # You can adjust the number of bins as needed

plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Data Distribution Histogram')
plt.show()
Output: -

BAIT,Surat 2
Machine Learning[1010206715] 2107020601029

Practical-3
Aim: - Write a program to implement scatter plot using given dataset.
import matplotlib.pyplot as plt
x1 = [90, 46, 38, 40, 98, 12, 68, 36, 40, 22]
y1 = [24, 48, 6, 38, 68, 98, 56, 74, 60, 12]
x2 = [28, 30, 50, 66, 8, 6, 38, 68, 74, 42]
y2 = [28, 36, 95, 36, 40, 22, 58, 4, 50, 18]

plt.scatter(x1, y1, c ="black", linewidths=2, marker="s",edgecolor="green", s=50)


plt.scatter(x2, y2, c ="yellow", linewidths=2, marker="^", edgecolor="red",
s=200) plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

Output: -

BAIT,Surat 3
Machine Learning[1010206715] 2107020601029

Practical-4
Aim: - Write a program to Implementation of linear regression from given dataset.
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
X = np.array([2, 4, 6, 8, 10]).reshape(-1, 1)
y = np.array([3, 6, 9, 12, 15])
model = LinearRegression()
model.fit(X, y)
y_pred = model.predict(X)
slope = model.coef_[0]
intercept = model.intercept_
print(f"Slope: {slope}")
print(f"Intercept:
{intercept}")
plt.scatter(X, y, label='Data', color='black')
plt.plot(X, y_pred, label='Linear Regression',
color='blue') plt.xlabel('X')
plt.ylabel('y')
plt.title('Linear Regression
Example') plt.legend()
plt.show()

Output: -

BAIT,Surat 4
Machine Learning[1010206715] 2107020601029

Practical-5
Aim: - Write a program to implement Scale.

from sklearn.preprocessing import MinMaxScaler,


StandardScaler import numpy as np

data = np.array([[2.0, 4.0, 6.0],


[3.0, 6.0, 9.0],
[4.0, 8.0, 12.0]])

min_max_scaler = MinMaxScaler()
scaled_data_minmax = min_max_scaler.fit_transform(data)

standard_scaler = StandardScaler()
scaled_data_standard = standard_scaler.fit_transform(data)

print("Min-Max Scaled Data:")


print(scaled_data_minmax)
print("\nStandardized Data:")
print(scaled_data_standard)

Output: -

BAIT,Surat 5
Machine Learning[1010206715] 2107020601029

Practical-6
Aim: - Write a program to training and testing from given dataset.

from sklearn.model_selection import


train_test_split from sklearn.linear_model import
LinearRegression from sklearn.metrics import
mean_squared_error import numpy as np

X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
y = np.array([2, 4, 5, 4, 5])

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


random_state=42) model = LinearRegression()
model.fit(X_train, y_train)

y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
slope = model.coef_[0]
intercept = model.intercept_
print(f"Slope: {slope}")
print(f"Intercept: {intercept}")
print(f"Mean Squared Error: {mse}")

Output: -

BAIT,Surat 6
Machine Learning[1010206715] 2107020601029

Practical-7
Aim: - Write a program to Implementation of Decision tree from given dataset.

from sklearn.datasets import load_iris


from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import
train_test_split
from sklearn.metrics import accuracy_score, classification_report

data = load_iris()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)

clf = DecisionTreeClassifier()
clf.fit(X_train, y_train) y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")

report = classification_report(y_test, y_pred)


print("Classification Report:")
print(report)

Output: -

BAIT,Surat 7
Machine Learning[1010206715] 2107020601029

Practical-8
Aim: - Write a program to Implement K-Nearest Neighbors Algorithm from given dataset.

from sklearn.datasets import load_iris


from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

data = load_iris()
X = data.data
y = data.target

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


random_state=42)
knn =
KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")
report = classification_report(y_test, y_pred, target_names=data.target_names)
print("Classification Report:")
print(report)

confusion = confusion_matrix(y_test, y_pred)


print("Confusion Matrix:")
print(confusion)

Output: -

BAIT,Surat 8
Machine Learning[1010206715] 2107020601029

Practical-9
Aim: - Write a program to implementation of K- Mean clustering from given dataset.

import matplotlib.pyplot as plt


from sklearn.cluster import KMeans
from sklearn.datasets import
make_blobs

X, y = make_blobs(n_samples=300, centers=3,
random_state=42)
kmeans = KMeans(n_clusters=3, random_state=42)
kmeans.fit(X)
labels = kmeans.labels_

plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis')


plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='red',
label='Centroids', marker='x')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title(f'K-Means Clustering
(k={k})') plt.legend()
plt.show()
Output: -

BAIT,Surat 9
Machine Learning[1010206715] 2107020601029

Practical-10 Practical-10
Aim: - Write a program to implementation of hierarchical clustering from dataset.

import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.datasets import make_circles

X, _ = make_circles(n_samples=300, factor=0.5, noise=0.05, random_state=42)


linkage_matrix = linkage(X, method='single') # You can use different linkage methods
dendrogram(linkage_matrix)
plt.title('Hierarchical Clustering
Dendrogram') plt.xlabel('Data Points')
plt.ylabel('Distance')
plt.show()

Output: -

BAIT,Surat 10

You might also like