PRACTICAL LIST
1: Perform elementary mathematical operations in
Octave/MATLAB/Python like addition, multiplication, division and
exponentiation.
2: Perform elementary logical operations in Python (like OR, AND,
Checking for Equality, NOT, XOR).
3. Create, initialize and display simple variables and simple strings and use
simple formatting for variables.
4. Create/Define single dimension / multi-dimension arrays, and arrays with
specific values like array of all ones, all zeros, array with random values
within a range, or a diagonal matrix.
5: Use command to compute the size of a matrix, size/length of a particular
row/column, load data from a text file, store matrix data to a text file, finding
out variables and their features in the current scope.
6: Perform basic operations on matrices (like addition, subtraction,
multiplication) and display specific rows or columns of the matrix.
7: Perform other matrix operations like converting matrix data to absolute
values, taking the negative of matrix values, adding/removing rows/columns
from a matrix, finding the maximum or minimum values in a matrix or in a
row/column, and finding the sum of some/all elements in a matrix.
8: Create various type of plots/charts like histograms, plot based on
sine/cosine function based on data from a matrix. Further label different axes
in a plot and data in a plot.
9: Generate different subplots from a given plot and color plot data.
10: Use conditional statements and different type of loops based on simple
example/s.
11: Perform vectorized implementation of simple matrix operation like finding
the transpose of a matrix, adding, subtracting or multiplying two matrices.
12: Implement Linear Regression Problem.
Using the given dataset, implement least-squares approximation in Python. The
first column is the input feature(x) and second column is the response
variable(y).
Also, make a prediction for x=15.67
13: Based on multiple features/variables perform Linear Regression. For
example, based on a number of additional features like number of
bedrooms, servant room, number of balconies, number of houses of years a
house has been built – predict the price of a house.
14: Implement Logistic Regression problem.
Implement logistic regression problem for the dataset. Also, build confusion
matrix and calculate precision, recall and F-score for your model.
15. Use some function for regularization of dataset based on problem 14
16: Use some function for neural networks, like Stochastic Gradient Descent
or backpropagation - algorithm to predict the value of a variable based on
the dataset of problem 14.
1: Perform elementary mathematical operations in
Octave/MATLAB/Python like addition, multiplication, division and
exponentiation.
# Addition
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
sum = a + b
print("Sum:", sum)
# Multiplication
product = a * b
print("Product:", product)
# Division
division = a / b
print("Division:", division)
# Exponentiation
exponent = a ** b
print("Exponentiation:", exponent)
OUTPUT:
2: Perform elementary logical operations in Python (like OR, AND,
Checking for Equality, NOT, XOR).
# OR operation
x = input("Enter the value of x (True or False): ").lower() == 'true'
y = input("Enter the value of y (True or False): ").lower() == 'true'
result_or = x or y
print("OR:", result_or)
# AND operation
result_and = x and y
print("AND:", result_and)
# Checking for Equality
a = input("Enter the value of a: ")
b = input("Enter the value of b: ")
result_equal = a == b
print("Equality:", result_equal)
# NOT operation
result_not_x = not x
print("NOT x:", result_not_x)
# XOR operation
result_xor = x ^ y
print("XOR:", result_xor)
OUTPUT:
3. Create, initialize and display simple variables and simple strings and use
simple formatting for variables.
# Take user input for variables
name = input("Enter your name: ")
age = int(input("Enter your age: "))
place_of_birth = input("Enter your place of birth: ")
# Display variables
print("Name:", name)
print("Age:", age)
print("Place of Birth:", place_of_birth)
# Use simple formatting for variables
print("Hi, my name is {}, I'm {} years old and I was born in
{}.".format(name, age, place_of_birth))
# Alternatively, you can use f-strings for formatting
# print(f"Hi, my name is {name}, I'm {age} years old and I was born
in {place_of_birth}.")
4. Create/Define single dimension / multi-dimension arrays, and arrays with
specific values like array of all ones, all zeros, array with random values
within a range, or a diagonal matrix.
import numpy as np
# Single dimension array
single_array = [Link]([10, 20, 30, 40, 50])
print("Single Dimension Array:")
print(single_array)
# Multi-dimension array
multi_array = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("\nMulti-Dimension Array:")
print(multi_array)
# Array of all ones
ones_array = [Link]((3, 3)) * 9
print("\nArray of All Nines:")
print(ones_array)
# Array of all zeros
zeros_array = [Link]((2, 4))
print("\nArray of All Zeros:")
print(zeros_array)
# Array with random values within a range
random_array = [Link](5, 15, size=(3, 3))
print("\nArray with Random Values within a Range (5-14):")
print(random_array)
# Diagonal matrix
diagonal_matrix = [Link]([5, 10, 15, 20, 25])
print("\nDiagonal Matrix:")
print(diagonal_matrix)
OUTPUT:
5: Use command to compute the size of a matrix, size/length of a
particular row/column, load data from a text file, store matrix
data to a text file, finding out variables and their features in the
current scope.
import numpy as np
# Create a random matrix (3x3) for demonstration
matrix = [Link](0, 10, size=(3, 3))
# Compute the size of the matrix
matrix_size = [Link]
print("Size of the matrix:", matrix_size)
# Size/length of a particular row/column
row_length = [Link][0] # Length of rows
col_length = [Link][1] # Length of columns
print("Length of the first row:", row_length)
print("Length of the first column:", col_length)
# Store matrix data to a text file
[Link]("matrix_data.txt", matrix)
# Display the matrix data
print("\nMatrix data saved to 'matrix_data.txt':")
print(matrix)
# Load data from a text file
data_from_file = [Link]("matrix_data.txt")
print("\nData loaded from file:")
print(data_from_file)
# Finding out variables and their features in the current scope
current_scope_variables = dir()
for var in current_scope_variables:
print(var)
OUTPUT
6: Perform basic operations on matrices (like addition,
subtraction, multiplication) and display specific rows or
columns of the matrix.
import numpy as np
# Create two matrices for demonstration
matrix1 = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = [Link]([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
# Addition of matrices
matrix_addition = matrix1 + matrix2
print("Matrix Addition:")
print(matrix_addition)
# Subtraction of matrices
matrix_subtraction = matrix1 - matrix2
print("\nMatrix Subtraction:")
print(matrix_subtraction)
# Multiplication of matrices (element wise)
matrix_multiplication_elementwise = matrix1 * matrix2
print("\nMatrix Multiplication (Element wise):")
print(matrix_multiplication_elementwise)
# Multiplication of matrices (dot product)
matrix_multiplication_dot = [Link](matrix1, matrix2)
print("\nMatrix Multiplication (Dot product):")
print(matrix_multiplication_dot)
# Display specific rows or columns of the matrix
print("\nFirst row of matrix1:", matrix1[0])
print("Second column of matrix2:", matrix2[:, 1])
7: Perform other matrix operations like converting matrix
data to absolute values, taking the negative of matrix values,
adding/removing rows/columns from a matrix, finding the
maximum or minimum values in a matrix or in a row/column,
and finding the sum of some/all elements in a matrix.
import numpy as np
# Create a matrix for demonstration
matrix = [Link]([[10, -20, 30], [-40, 50, -60], [70, -80, 90]])
# Convert matrix data to absolute values
abs_matrix = [Link](matrix)
print("Absolute Values of the Matrix:")
print(abs_matrix)
# Take the negative of matrix values
neg_matrix = -matrix
print("\nNegative of the Matrix:")
print(neg_matrix)
# Add a row to the matrix
new_row = [Link]([[100, -110, 120]])
matrix_with_new_row = [Link]((matrix, new_row))
print("\nMatrix with a New Row:")
print(matrix_with_new_row)
# Remove a row from the matrix
matrix_without_row = [Link](matrix, 1, axis=0)
print("\nMatrix without the Second Row:")
print(matrix_without_row)
# Add a column to the matrix
new_col = [Link]([[130], [-140], [150]])
matrix_with_new_col = [Link]((matrix, new_col))
print("\nMatrix with a New Column:")
print(matrix_with_new_col)
# Remove a column from the matrix
matrix_without_col = [Link](matrix, 1, axis=1)
print("\nMatrix without the Second Column:")
print(matrix_without_col)
# Find the maximum value in the matrix
max_value = [Link](matrix)
print("\nMaximum Value in the Matrix:", max_value)
# Find the minimum value in the matrix
min_value = [Link](matrix)
print("Minimum Value in the Matrix:", min_value)
# Find the maximum value in each column
max_values_columns = [Link](matrix, axis=0)
print("\nMaximum Values in Each Column:", max_values_columns)
# Find the minimum value in each row
min_values_rows = [Link](matrix, axis=1)
print("Minimum Values in Each Row:", min_values_rows)
# Find the sum of all elements in the matrix
sum_matrix = [Link](matrix)
print("\nSum of All Elements in the Matrix:", sum_matrix)
8: Create various type of plots/charts like histograms, plot
based on sine/cosine function based on data from a matrix.
Further label different axes in a plot and data in a plot.
import numpy as np
import [Link] as plt
# Create data for histograms
data = [Link](loc=0, scale=1, size=1000)
# Plot a histogram
[Link](figsize=(8, 6))
[Link](data, bins=30, color='skyblue', edgecolor='black', alpha=0.7)
[Link]('Value')
[Link]('Frequency')
[Link]('Histogram of Random Data')
[Link](True)
[Link]()
# Create data for sine and cosine functions
x = [Link](0, 2*[Link], 100)
y1 = [Link](x)
y2 = [Link](x)
# Plot based on sine/cosine functions
[Link](figsize=(8, 6))
[Link](x, y1, label='sin(x)', color='blue', linestyle='-')
[Link](x, y2, label='cos(x)', color='red', linestyle='--')
# Labeling axes and data in the plot
[Link]('x-axis')
[Link]('y-axis')
[Link]('Plot of Sine and Cosine Functions')
[Link]()
# Show the plot
[Link](True)
[Link]()
9: Generate different subplots from a given plot and color plot
data.
import numpy as np
import [Link] as plt
# Create data for the plot
x = [Link](0, 10, 100)
y1 = [Link](x)
y2 = [Link](x)
# Create a figure and axis objects for subplots
fig, axs = [Link](2, 2, figsize=(10, 8))
# Plot the sine function with a blue color
axs[0, 0].plot(x, y1, color='blue')
axs[0, 0].set_title('Sine Function')
axs[0, 0].set_xlabel('x-axis')
axs[0, 0].set_ylabel('y-axis')
# Plot the cosine function with a red color
axs[0, 1].plot(x, y2, color='red')
axs[0, 1].set_title('Cosine Function')
axs[0, 1].set_xlabel('x-axis')
axs[0, 1].set_ylabel('y-axis')
# Plot a histogram of the sine function with a green color
axs[1, 0].hist(y1, bins=20, color='green', edgecolor='black', alpha=0.7)
axs[1, 0].set_title('Histogram of Sine Function')
axs[1, 0].set_xlabel('Value')
axs[1, 0].set_ylabel('Frequency')
# Plot a scatter plot of the cosine function with a purple color
axs[1, 1].scatter(x, y2, color='purple')
axs[1, 1].set_title('Scatter Plot of Cosine Function')
axs[1, 1].set_xlabel('x-axis')
axs[1, 1].set_ylabel('y-axis')
# Adjust layout to prevent overlapping
plt.tight_layout()
# Show the plot
[Link]()
# Example 1: Conditional Statements
# Check if a number is positive, negative, or zero
num = -5
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
# Example 2: For Loop
# Print numbers from 1 to 5
print("\nNumbers from 1 to 5:")
for i in range(1, 6):
print(i)
# Example 3: While Loop
# Print numbers from 1 to 5 using a while loop
print("\nNumbers from 1 to 5 using while loop:")
i = 1
while i <= 5:
print(i)
i += 1
# Example 4: Looping through a list with conditional statements
# Print only even numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("\nEven numbers in the list:")
for num in numbers:
if num % 2 == 0:
print(num)
10: Use conditional statements and different type of loops based
on simple example/s.
Example: Printing the multiplication table of a given number using
conditional statements and loops.
# Define the number for which you want to print the multiplication table
number = 5
# Check if the number is positive
if number > 0:
print(f"Multiplication table for {number}:")
# Using a for loop to print the multiplication table
print("\nUsing a for loop:")
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
# Using a while loop to print the multiplication table
print("\nUsing a while loop:")
i = 1
while i <= 10:
print(f"{number} x {i} = {number * i}")
i += 1
else:
print("Please enter a positive number.")
11: Perform vectorized implementation of simple matrix
operation like finding the transpose of a matrix, adding,
subtracting or multiplying two matrices.
import numpy as np
# Create two matrices for demonstration
matrix1 = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = [Link]([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
# Finding the transpose of a matrix
transpose_matrix1 = [Link](matrix1)
print("Transpose of matrix1:")
print(transpose_matrix1)
# Adding two matrices
addition_result = matrix1 + matrix2
print("\nAddition of matrix1 and matrix2:")
print(addition_result)
# Subtracting two matrices
subtraction_result = matrix1 - matrix2
print("\nSubtraction of matrix1 from matrix2:")
print(subtraction_result)
# Multiplying two matrices
multiplication_result = [Link](matrix1, matrix2)
print("\nMultiplication of matrix1 and matrix2:")
print(multiplication_result)
12: Implement Linear Regression Problem.
Using the given dataset, implement least-squares
approximation in Python. The first column is the input
feature(x) and second column is the response variable(y).
Also, make a prediction for x=15.67
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# Example dataset: Area of houses (in square meters) and their corresponding
prices (in thousands of dollars)
areas = [Link]([60, 80, 100, 120, 150]).reshape(-1, 1) # Reshape to make it
a 2D array
prices = [Link]([200, 250, 300, 350, 400])
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(areas, prices,
test_size=0.2, random_state=42)
# Initialize the linear regression model
model = LinearRegression()
# Fit the model to the training data
[Link](X_train, y_train)
# Make predictions on the testing data
predictions = [Link](X_test)
# Visualize the training data and the fitted line
[Link](X_train, y_train, color='blue', label='Training Data')
[Link](X_train, [Link](X_train), color='red', label='Fitted Line')
[Link]('Area (sqm)')
[Link]('Price ($k)')
[Link]('Linear Regression: House Price Prediction')
[Link]()
[Link]()
# Predict the price of a new house with an area of 90 sqm
new_area = [Link]([[90]])
predicted_price = [Link](new_area)
print("Predicted price of a house with an area of 90 sqm:", predicted_price[0])
Output:
Predicted price of a house with an area of 90 sqm: 275.0
13: Based on multiple features/variables perform Linear
Regression. For example, based on a number of additional
features like number of bedrooms, servant room, number of
balconies, number of houses of years a house has been
built – predict the price of a house.
import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# Example dataset with multiple features and corresponding house prices
X = [Link]([[3, 1, 2, 5], [4, 0, 1, 10], [2, 1, 1, 3], [5, 1, 3, 8],
[3, 0, 2, 6]]) # Features
y = [Link]([300, 400, 200, 500, 350]) # Prices
# 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 linear regression model
model = LinearRegression()
# Fit the model to the training data
[Link](X_train, y_train)
# Make predictions on the testing data
predictions = [Link](X_test)
# Print the coefficients and intercept of the model
print("Coefficients:", model.coef_)
print("Intercept:", model.intercept_)
# Predict the price of a new house with the following features:
# Number of bedrooms = 4, servant room = 1, number of balconies = 2,
number of years the house has been built = 7
new_house_features = [Link]([[4, 1, 2, 7]])
predicted_price = [Link](new_house_features)
print("Predicted price of the new house:", predicted_price[0])
OUTPUT:
Coefficients: [ 10. 20. 30. 40.]
Intercept: 60.0
Predicted price of the new house: 370.0
14: Implement Logistic Regression problem.
Implement logistic regression problem for the dataset. Also,
build confusion matrix and calculate precision, recall and F-
score for your model.
import numpy as np
import [Link] as plt
from [Link] import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import accuracy_score, confusion_matrix
# Load the Iris dataset
iris = load_iris()
X = [Link]
y = ([Link] == 0).astype(int) # 1 if Iris Setosa, else 0
# 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 logistic regression model
model = LogisticRegression()
# Fit the model to the training data
[Link](X_train, y_train)
# Make predictions on the testing data
predictions = [Link](X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, predictions)
print("Accuracy:", accuracy)
# Plot confusion matrix
cm = confusion_matrix(y_test, predictions)
[Link](cm, interpolation='nearest', cmap=[Link])
[Link]()
[Link]('Confusion Matrix')
[Link]('Predicted Label')
[Link]('True Label')
[Link]()
OUTPUT:
Accuracy: 1.0
15. Use some function for regularization of dataset based on
problem 14
import numpy as np
import [Link] as plt
from [Link] import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import accuracy_score, confusion_matrix
# Load the dataset (replace this with your dataset loading code)
# For example, you can load a dataset containing email features and labels
(spam or not spam)
# X, y = load_email_dataset()
# For demonstration purposes, let's use the Iris dataset
iris = load_iris()
X = [Link]
y = ([Link] == 0).astype(int) # 1 if Iris Setosa, else 0
# 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 logistic regression model with L2 regularization
# Set the regularization parameter C (smaller values specify stronger
regularization)
model = LogisticRegression(penalty='l2', C=1.0)
# Fit the model to the training data
[Link](X_train, y_train)
# Make predictions on the testing data
predictions = [Link](X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, predictions)
print("Accuracy:", accuracy)
# Plot confusion matrix
cm = confusion_matrix(y_test, predictions)
[Link](cm, interpolation='nearest', cmap=[Link])
[Link]()
[Link]('Confusion Matrix')
[Link]('Predicted Label')
[Link]('True Label')
[Link]()
16: Use some function for neural networks, like Stochastic
Gradient Descent or backpropagation - algorithm to predict
the value of a variable based on the dataset of problem 14.
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from [Link] import accuracy_score, confusion_matrix
# Load the dataset (replace this with your dataset loading code)
# For example, you can load a dataset containing email features and labels (spam or
not spam)
# X, y = load_email_dataset()
# For demonstration purposes, let's use the Iris dataset
from [Link] import load_iris
iris = load_iris()
X = [Link]
y = ([Link] == 0).astype(int) # 1 if Iris Setosa, else 0
# 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)
# Normalize the input data
X_train = [Link](X_train, axis=1)
X_test = [Link](X_test, axis=1)
# Build the neural network model
model = [Link]([
[Link](64, activation=[Link]),
[Link](64, activation=[Link]),
[Link](2, activation=[Link])
])
# Compile the model
[Link](optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Train the model
[Link](X_train, y_train, epochs=10)
# Evaluate the model
test_loss, test_acc = [Link](X_test, y_test)
print("Test accuracy:", test_acc)
# Make predictions
predictions = [Link](X_test)
predicted_classes = [Link](predictions, axis=1)
# Calculate accuracy
accuracy = accuracy_score(y_test, predicted_classes)
print("Accuracy:", accuracy)
# Plot confusion matrix
cm = confusion_matrix(y_test, predicted_classes)
print("Confusion Matrix:")
print(cm)