NAME OF THE EXP PAGE SIGNATURE
Draw the star diamond pattern 03
Write a program to replace vowel from the given string 05
Write a program to read an iris dataset 07
Write a program to reverse a number 09
Write a program to multiply two arrays using NumPy 11
Draw a graph using matplotlib in 2-D 13
Draw a graph using matplotlib in 3-D 15
Draw a tree using turtle 17
Implement linear regression 19
Split the iris dataset in the ratio of 70:30 21
Implement logistic regression to find: Accuracy, Precision, Recall and F1 23
score
Implement decision tree to find: Accuracy, Precision, Recall and F1 Score 25
Implement SVM to find Accuracy, Precision, Recall and F1 Score 27
Implement SVM to find accuracy 29
Implement K-means algorithm 31
Draw a pie-chart using matplotlib 33
INDEX
3
Output: Star Pattern
5
1. Draw the star diamond pattern
# Number of rows for the upper half of the diamond
n=5
# Print the upper half of the diamond
for i in range(n):
# Print leading spaces
print(' ' * (n - i - 1), end='')
# Print stars
print('* ' * (i + 1))
# Print the lower half of the diamond
for i in range(n - 1, 0, -1):
# Print leading spaces
print(' ' * (n - i), end='')
# Print stars
print('* ' * i)
Output: Program to replace vowel from string
7
2. Write a program to replace vowel from
the given string
def replace_vowels(input_string, replacement_char='*'):
# Define vowels
vowels = "AEIOUaeiou"
# Replace each vowel in the string with the replacement character
result = ''.join([replacement_char if char in vowels else char for char in
input_string])
return result
# Input from user
input_string = input("Enter a string: ")
# Call the function and print the result
print("String after replacing vowels:", replace_vowels(input_string))
Output: program to read iris dataset
9
3. Write a program to read an iris dataset
from sklearn.datasets import load_iris
import pandas as pd
# Load the Iris dataset
iris = load_iris()
# Convert the dataset to a pandas DataFrame for easier manipulation
iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
iris_df['target'] = iris.target # Add the target labels as a new column
# Display the first few rows of the dataset
print("First five rows of the Iris dataset:")
print(iris_df.head())
Output: program to reverse a number
11
4. Write a program to reverse a
number
def reverse_number(number):
# Convert the number to a string, reverse it, and convert it back to an integer
reversed_num = int(str(number)[::-1])
return reversed_num
# Input from the user
number = int(input("Enter a number: "))
# Call the function and display the result
print("Reversed number:", reverse_number(number))
Output: program to multiply two arrays using NumPy
13
5. Write a program to multiply two
arrays using NumPy
import numpy as np
# Define two arrays
array1 = np.array([1, 2, 3, 4])
array2 = np.array([5, 6, 7, 8])
# Multiply the arrays element-wise
result = np.multiply(array1, array2)
# Display the result
print("Result of element-wise multiplication:", result)
Output: Draw a graph using matplotlib in 2D
15
6. Draw a graph using matplotlib in 2-D
import matplotlib.pyplot as plt
import numpy as np
# Generate x values from 0 to 2π
x = np.linspace(0, 2 * np.pi, 100)
# Generate y values as the sine of x
y = np.sin(x)
# Create the plot
plt.figure(figsize=(8, 5))
plt.plot(x, y, label='Sine Wave', color='blue', linewidth=2)
# Adding labels and title
plt.xlabel("X values (radians)")
plt.ylabel("Y values (sine of x)")
plt.title("2D Plot of Sine Wave")
plt.grid(True)
plt.legend()
plt.show()
Output: Draw a graph using matplotlib in 3D
17
7. Draw a graph using matplotlib in 3-D
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# Generate data for a 3D helix
theta = np.linspace(0, 4 * np.pi, 100) # Angle values
z = np.linspace(0, 2, 100) # z-axis values
x = np.sin(theta) # x = sin(theta)
y = np.cos(theta) # y = cos(theta)
# Create a 3D plot
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
# Plot the 3D curve
ax.plot(x, y, z, label='3D Helix Curve', color='purple', linewidth=2)
# Adding labels and title
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.set_title("3D Plot of a Helix Curve")
# Add legend
ax.legend()
# Show the plot
plt.show()
Output: Draw a tree using turtle
19
8. Draw a tree using turtle
import turtle
# Set up the screen
screen = turtle.Screen()
screen.bgcolor("skyblue")
tree = turtle.Turtle()
tree.speed(5)
def draw_trunk():
tree.color("brown")
tree.begin_fill()
for _ in range(2):
tree.forward(20)
tree.left(90)
tree.forward(100)
tree.left(90)
tree.end_fill()
def draw_canopy():
tree.color("green")
tree.begin_fill()
tree.circle(50) # Draw a circle with radius 50
tree.end_fill()
tree.penup()
tree.goto(-10, -100) # Position the turtle to draw the trunk
tree.pendown()
draw_trunk()
tree.penup()
tree.goto(0, 0)
tree.pendown()
draw_canopy()
tree.hideturtle()
screen.exitonclick()
Output: Implement linear regression
21
9. Implement linear regression
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 7, 11])
x_mean = np.mean(x)
y_mean = np.mean(y)
numerator = np.sum((x - x_mean) * (y - y_mean))
denominator = np.sum((x - x_mean) ** 2)
slope = numerator / denominator
intercept = y_mean - slope * x_mean
# Display the equation of the line
print(f"Linear Regression Line: y = {slope:.2f}x + {intercept:.2f}")
y_pred = slope * x + intercept
import matplotlib.pyplot as plt
plt.scatter(x, y, color="blue", label="Data Points")
plt.plot(x, y_pred, color="red", label="Regression Line")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend()
plt.show()
Output: Split the iris dataset in the ratio of 7:3
23
10. Split the iris dataset in the ratio of 7:3
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# Load the Iris dataset
iris = load_iris()
# Split the data into features (X) and target (y)
X = iris.data
y = iris.target
# Split the dataset into training (70%) and testing (30%) sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)
# Display the shapes of the resulting splits
print(f"Training features shape: {X_train.shape}")
print(f"Test features shape: {X_test.shape}")
print(f"Training labels shape: {y_train.shape}")
print(f"Test labels shape: {y_test.shape}")
Output: Implement logistic regression to find Accuracy,
Precision, Recall and F1 score
25
11 .Implement logistic regression to find: Accuracy,
Precision, Recall and F1 score
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from sklearn.metrics import recall_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
# Load the Iris dataset
iris = load_iris()
X = iris.data # Features
y = iris.target # Target variable
# Split the dataset into training and testing sets with
a 70:30 ratio
X_train, X_test, y_train, y_test = train_test_split(X,
y, test_size=0.3, random_state=0)
# Create a logistic regression model
model = LogisticRegression()
# Train the model using the training data
model.fit(X_train, y_train)
# Make predictions using the test data
predictions = model.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, predictions)
print("Accuracy:", accuracy)
# Calculate precision
precision = precision_score(y_test, predictions,
average='weighted')
print("Precision:", precision)
# Calculate recall
recall = recall_score(y_test, predictions,
average='weighted')
print("Recall:", recall)
# Calculate F1 score
f1 = f1_score(y_test, predictions, average='weighted')
print("F1 Score:", f1)
Output: Implement decision tree to find: Accuracy,
Precision, Recall and F1 Score
27
12 Implement decision tree to find
Accuracy, Precision, Recall and F1
Score
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score,
precision_score, recall_score, f1_score
# Load the Iris dataset
iris = load_iris()
X = iris.data # Features
y = iris.target # Target variable
# Split the dataset into training and testing sets with
a 70:30 ratio
X_train, X_test, y_train, y_test = train_test_split(X,
y, test_size=0.3, random_state=0)
# Create a Decision Tree classifier model
model = DecisionTreeClassifier(random_state=0)
# Train the model using the training data
model.fit(X_train, y_train)
# Make predictions using the test data
predictions = model.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, predictions)
print("Accuracy:", accuracy)
# Calculate precision
precision = precision_score(y_test, predictions,
average='weighted')
print("Precision:", precision)
# Calculate recall
recall = recall_score(y_test, predictions,
average='weighted')
print("Recall:", recall)
# Calculate F1 score
f1 = f1_score(y_test, predictions, average='weighted')
print("F1 Score:", f1)
Output: Implement SVM to find Accuracy, Precision,
Recall and F1 Score
29
13 Implement SVM to find accuracy
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score,
precision_score, recall_score, f1_score
# Load the Iris dataset
iris = load_iris()
X = iris.data # Features
y = iris.target # Target variable
# Split the dataset into training and testing sets with
a 70:30 ratio
X_train, X_test, y_train, y_test = train_test_split(X,
y, test_size=0.3, random_state=0)
# Create an SVM classifier model
model = SVC()
# Train the model using the training data
model.fit(X_train, y_train)
# Make predictions using the test data
predictions = model.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, predictions)
print("Accuracy:", accuracy)
# Calculate precision
precision = precision_score(y_test, predictions,
average='weighted')
print("Precision:", precision)
# Calculate recall
recall = recall_score(y_test, predictions,
average='weighted')
print("Recall:", recall)
# Calculate F1 score
f1 = f1_score(y_test, predictions, average='weighted')
print("F1 Score:", f1)
Output: Implement K-means algorithm
31
14 Implement k- means algorithm
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
# Load the Iris dataset
iris = load_iris()
X = iris.data
# Features
# Create a K-means model with 3 clusters (as there are three classes in the Iris
dataset)
kmeans = KMeans(n_clusters=3, random_state=0)
# Fit the model to the data
kmeans.fit(X)
# Get cluster labels and centroids
labels = kmeans.labels_
centroids = kmeans.cluster_centers_
# Visualize the clusters (for the first two features)
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', marker='o', edgecolors='k')
plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=200, linewidths=3,
color='r')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('K-means Clustering')
plt.show()
Output: Pie-chart using matplotlib
33
15. Draw a pie-chart using matplotlib
import matplotlib.pyplot as plt
# Data for the pie chart labels = ['A', 'B', 'C', 'D']
sizes = [30, 40, 20, 10] # Values representing the sizes of
each slice in the pie chart colors = ['gold', 'yellowgreen',
'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0) # Explode the 1st slice (i.e., 'A')
# Plot the pie chart
plt.figure(figsize=(8, 6))
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal') # Equal aspect ratio ensures that pie is
drawn as a circle.
# Set the title of the pie chart
plt.title('Sample Pie Chart')
# Show the pie chart
plt.show()