0% found this document useful (0 votes)
3 views11 pages

ML

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)
3 views11 pages

ML

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 [3170724] 191390107018

Practical-1
Aim: - Write a program to Implementation of mean, median and mode.
Code :-
import statistics

# Input: Read a list of numbers from the user


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 with error handling


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

Output: -

BAIT,Surat 1
Machine Learning [3170724] 191390107018

Practical-2
Aim: - Write a program to implement Data distribution histogram.
Code :-
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 [3170724] 191390107018

Practical-3
Aim: - Write a program to implement scatter plot using given dataset.
Code :-
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 [3170724] 191390107018

Practical-4
Aim: - Write a program to Implementation of linear regression from given dataset.
Code :-
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 [3170724] 191390107018

Practical-5
Aim: - Write a program to implement Scale.
Code :-
from sklearn.preprocessing import MinMaxScaler, StandardScaler
import numpy as np

# Input data
data = np.array([
[2.0, 4.0, 6.0],
[3.0, 6.0, 9.0],
[4.0, 8.0, 12.0]
])

# Apply Min-Max Scaling


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

# Apply Standard Scaling


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

# Print the results


print("Min-Max Scaled Data:")
print(scaled_data_minmax)

print("\nStandardized Data:")
print(scaled_data_standard)
Output: -

BAIT,Surat 5
Machine Learning [3170724] 191390107018

Practical-6
Aim: - Write a program to training and testing from given dataset.
Code :-
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

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

# Split the data 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)

# Create and train the Linear Regression model


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

# Predict the target values for the test set


y_pred = model.predict(X_test)

# Calculate the mean squared error


mse = mean_squared_error(y_test, y_pred)

# Get the slope and intercept


slope = model.coef_[0]
intercept = model.intercept_

# Print the results


print(f"Slope: {slope}")
print(f"Intercept: {intercept}")
print(f"Mean Squared Error: {mse}")
Output: -

BAIT,Surat 6
Machine Learning [3170724] 191390107018

Practical-7
Aim: - Write a program to Implementation of Decision tree from given dataset.
Code :-
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

# Load the Iris dataset


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

# Split the data 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)

# Create and train the DecisionTreeClassifier model


clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)

# Predict the target values for the test set


y_pred = clf.predict(X_test)

# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")

# Generate the classification report


report = classification_report(y_test, y_pred)
print("Classification Report:")
print(report)
Output: -

BAIT,Surat 7
Machine Learning [3170724] 191390107018

Practical-8
Aim: - Write a program to Implement K-Nearest Neighbors Algorithm from given dataset.
Code :-
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 [3170724] 191390107018

Practical-9
Aim: - Write a program to implementation of K- Mean clustering from given dataset.
Code :-
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)

means = 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('K-Means Clustering (k=3)')
plt.legend()
plt.show()
Output: -

BAIT,Surat 9
Machine Learning [3170724] 191390107018

Practical-10
Aim: - Write a program to implementation of hierarchical clustering from dataset.
Code :-
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.datasets import make_circles

# Generate synthetic data


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

# Perform hierarchical/agglomerative clustering using 'single' linkage method


linkage_matrix = linkage(X, method='single') # You can use different linkage methods

# Plot the dendrogram


dendrogram(linkage_matrix)

# Add title and labels to the plot


plt.title('Hierarchical Clustering Dendrogram')
plt.xlabel('Data Points')
plt.ylabel('Distance')

# Show the plot


plt.show()

Output: -

BAIT,Surat 10

You might also like