0% found this document useful (0 votes)
49 views20 pages

Karmbir 19 ML

This document summarizes a project titled "Machine Learning with Python" submitted for a course on Computer Science and Engineering at IGU, Meerpur in 2023-24. It was submitted by Karmbir, a student with registration number 181261103032, to their professor Miss Surbhi.
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)
49 views20 pages

Karmbir 19 ML

This document summarizes a project titled "Machine Learning with Python" submitted for a course on Computer Science and Engineering at IGU, Meerpur in 2023-24. It was submitted by Karmbir, a student with registration number 181261103032, to their professor Miss Surbhi.
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/ 20

Project File

“Machine Learning with Python”

Department
Of
Computer Science and Engineering
2023-24

Submitted To: Submitted By:


Miss Surbhi Name: Karmbir
Prof. Registration: 181261103032
CSE, IGU, Meerpur MCA 3rd Sem.
Rewari, Haryana 2022-2024
Name= karmbir
roll number=19 (181261103032)
# 1. Draw the star patern as following:
*
**
***
****
*****
****
***
**
*
Solu�on:
n=5
for i in range(1,n+1):
print("*"*i)
for i in range(n-1,0,-1):
print("*"*i)

Output:
Name= karmbir
roll number=19 (181261103032)
#2 Write a program to replace vowel from the given string:
Solu�on:

str = "This is a string."


new_str = str.replace("a", "*")
print(new_str)

Output:
Name= karmbir
roll number=19 (181261103032)
#3 Write a program to read a iris dataset:

Solu�on:

import pandas as pd
import numpy as np
data=pd.read_csv("IRIS.csv")
data.head()

Output:
Name= Karmbir
roll number=19 (181261103032)
#4 Write a program to reverse a number:
Solu�on:

n=int(input("Enter number: "))


rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number:",rev)

Output:
Name= Karmbir
roll number=19 (181261103032)
#5 Write a program to mul�ply two array using numpy:
Solu�on:

import numpy as np
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])
mul�ply=array1*array2
mul�ply

Output:
Name= Karmbir
roll number=19 (181261103032)
#6 Draw a graph using matplotlib in 2-D:

Solu�on:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5] # X-axis values
y = [2, 4, 6, 8, 10] # Y-axis values
plt.plot(x, y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.�tle("Simple 2-D Plot")
plt.show()

Output:
Name= Karmbir
roll number=19 (181261103032)
#7 Draw a graph using matplotlib in 3-D:
Solu�on:

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projec�on='3d')

Output:
Name= Karmbir
roll number=19 (181261103032)
#8 draw a pie chart using matplotlib
Solu�on:
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])

plt.pie(y)
plt.show()

OutPut:
Name= Karmbir
roll number=19 (181261103032)
#9 Split the iris dataset in the ra�o of 70:30
Solu�on:
import sklearn.datasets as ds
import sklearn.model_selec�on as ms
iris = ds.load_iris()
X_train, X_test, y_train, y_test = ms.train_test_split(iris.data, iris.target,
test_size=0.3)
print(X_train.shape)
print(X_test.shape)
print(y_train.shape[0])
print(y_test.shape[0])

Output:
Name= Karmbir
roll number=19 (181261103032)
#10 Implement linear regression:
Solu�on:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
X = np.array([1, 2, 3, 6, 8]).reshape(-1, 1)
y = np.array([2, 4, 5, 7, 9])
# Create a linear regression model
model = LinearRegression()
# Fit the model to the data
model.fit(X, y)
# predic�ons
y_pred = model.predict(X)
# Plot the data and the linear regression line
plt.scater(X, y, label='Actual Data')
plt.plot(X, y_pred, color='red', label='Linear Regression Line')
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.legend()
plt.show()
print(f'Intercept (b0): {model.intercept_}')
print(f'Coefficient (b1): {model.coef_}')
Output:
Name= Karmbir
roll number=19 (181261103032)
#11 Implement logis�c regression to find accuracy:
Solu�on:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selec�on import train_test_split
from sklearn.linear_model import Logis�cRegression
from sklearn.metrics import accuracy_score, confusion_matrix
# Generate some sample data for binary classifica�on
X = np.random.rand(100, 2) # Independent variables
y = (X[:, 0] + X[:, 1] > 1).astype(int) # Binary target variable
# Split the data into training and tes�ng sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
# Create a logis�c regression model
model = Logis�cRegression()
# Fit the model to the training data
model.fit(X_train, y_train)
# Make predic�ons on the tes�ng data
y_pred = model.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')
# Create a confusion matrix
confusion = confusion_matrix(y_test, y_pred)
print('Confusion Matrix:')
print(confusion)
# Plot the decision boundary (op�onal)
plt.scater(X_test[:, 0], X_test[:, 1], c=y_test, cmap=plt.cm.Paired)
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
xx, yy = np.meshgrid(np.linspace(xlim[0], xlim[1], 50),
np.linspace(ylim[0], ylim[1], 50))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])

Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.5)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.�tle('Logis�c Regression Decision Boundary')
plt.show()

Output:
Name= Karmbir
roll number=19 (181261103032)
#12 Implement decision tree to find accuracy:
Solu�on:
# Import necessary libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selec�on import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, confusion_matrix
# Generate some sample data for binary classifica�on
X = np.random.rand(100, 2) # Independent variables
y = (X[:, 0] + X[:, 1] > 1).astype(int) # Binary target variable
# Split the data into training and tes�ng sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create a decision tree classifier
model = DecisionTreeClassifier()
# Fit the model to the training data
model.fit(X_train, y_train)
# Make predic�ons on the tes�ng data
y_pred = model.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')
# Create a confusion matrix
confusion = confusion_matrix(y_test, y_pred)
print('Confusion Matrix:')
print(confusion)
# Plot the decision tree (op�onal)
plt.scater(X_test[:, 0], X_test[:, 1], c=y_test, cmap=plt.cm.Paired)
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
xx, yy = np.meshgrid(np.linspace(xlim[0], xlim[1], 50),
np.linspace(ylim[0], ylim[1], 50))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.5)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.�tle('Decision Tree Decision Boundary')
plt.show()

Output:
Name= Karmbir
roll number=19 (181261103032)
#13 Implement SVM to find accuracy:
Solu�on:
import numpy as np
from sklearn import datasets
from sklearn.model_selec�on import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# Load the Iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
# Split the data into training and tes�ng sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create an SVM classifier
svm_classifier = SVC(kernel='linear')
# Train the SVM classifier on the training data
svm_classifier.fit(X_train, y_train)
# Make predic�ons on the test data
y_pred = svm_classifier.predict(X_test)
# Calculate the accuracy of the classifier
accuracy = accuracy_score(y_test, y_pred)

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

Output:
Name= Karmbir
roll number=19 (181261103032)
#14 Implement k- means algorithem:
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
# some sample data
data = np.array([[1, 2], [5, 8], [1.5, 1.8], [8, 8], [1, 0.6], [9, 11]])
# Specify the number of clusters (k)
k=2
kmeans = KMeans(n_clusters=k)
# Fit the data to the KMeans model
kmeans.fit(data)
centroids = kmeans.cluster_centers_
labels = kmeans.labels_
# Visualize the data and cluster centers
colors = ["g.", "r.", "c.", "y."]
for i in range(len(data)):
plt.plot(data[i][0], data[i][1], colors[labels[i]], markersize=10)
plt.scater(centroids[:, 0], centroids[:, 1], marker="x", s=200, linewidths=3, color="k")
plt.show()

Output:
Name= Karmbir
roll number=19 (181261103032)
#15 Draw a tree using turtle:
import turtle

# Create a Turtle screen


screen = turtle.Screen()
screen.bgcolor("white")
# Create a Turtle object
t = turtle.Turtle()
t.speed(0) # Set the drawing speed (0 is the fastest)
# Define a recursive func�on to draw branches of the tree
def draw_branch(branch_length, t):
if branch_length > 5:
# Draw the current branch
t.forward(branch_length)

# Right branch
t.right(20)
draw_branch(branch_length - 15, t)

# Le� branch
t.le�(40)
draw_branch(branch_length - 15, t)

# Return to the original posi�on


t.right(20)
t.backward(branch_length)
# Set the ini�al posi�on and heading
t.up()
t.goto(0, -200)
t.setheading(90)
t.down()
draw_branch(100, t)
screen.exitonclick()

Output:

You might also like