0% found this document useful (0 votes)
23 views33 pages

Machine

Uploaded by

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

Machine

Uploaded by

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

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 = np.array([10, 20, 30, 40, 50])

print("Single Dimension Array:")

print(single_array)

# Multi-dimension array

multi_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print("\nMulti-Dimension Array:")

print(multi_array)

# Array of all ones

ones_array = np.ones((3, 3)) * 9

print("\nArray of All Nines:")

print(ones_array)

# Array of all zeros

zeros_array = np.zeros((2, 4))

print("\nArray of All Zeros:")

print(zeros_array)

# Array with random values within a range

random_array = np.random.randint(5, 15, size=(3, 3))

print("\nArray with Random Values within a Range (5-14):")

print(random_array)

# Diagonal matrix

diagonal_matrix = np.diag([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 = np.random.randint(0, 10, size=(3, 3))


# Compute the size of the matrix

matrix_size = matrix.shape

print("Size of the matrix:", matrix_size)

# Size/length of a particular row/column

row_length = matrix.shape[0] # Length of rows

col_length = matrix.shape[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

np.savetxt("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 = np.loadtxt("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 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])


matrix2 = np.array([[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 = np.dot(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 = np.array([[10, -20, 30], [-40, 50, -60], [70, -80, 90]])

# Convert matrix data to absolute values

abs_matrix = np.abs(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 = np.array([[100, -110, 120]])

matrix_with_new_row = np.vstack((matrix, new_row))

print("\nMatrix with a New Row:")

print(matrix_with_new_row)

# Remove a row from the matrix

matrix_without_row = np.delete(matrix, 1, axis=0)

print("\nMatrix without the Second Row:")


print(matrix_without_row)

# Add a column to the matrix

new_col = np.array([[130], [-140], [150]])

matrix_with_new_col = np.hstack((matrix, new_col))

print("\nMatrix with a New Column:")

print(matrix_with_new_col)

# Remove a column from the matrix

matrix_without_col = np.delete(matrix, 1, axis=1)

print("\nMatrix without the Second Column:")

print(matrix_without_col)

# Find the maximum value in the matrix

max_value = np.max(matrix)

print("\nMaximum Value in the Matrix:", max_value)

# Find the minimum value in the matrix

min_value = np.min(matrix)

print("Minimum Value in the Matrix:", min_value)

# Find the maximum value in each column


max_values_columns = np.max(matrix, axis=0)

print("\nMaximum Values in Each Column:", max_values_columns)

# Find the minimum value in each row

min_values_rows = np.min(matrix, axis=1)

print("Minimum Values in Each Row:", min_values_rows)

# Find the sum of all elements in the matrix

sum_matrix = np.sum(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 matplotlib.pyplot as plt

# Create data for histograms

data = np.random.normal(loc=0, scale=1, size=1000)

# Plot a histogram

plt.figure(figsize=(8, 6))

plt.hist(data, bins=30, color='skyblue', edgecolor='black', alpha=0.7)

plt.xlabel('Value')

plt.ylabel('Frequency')

plt.title('Histogram of Random Data')

plt.grid(True)

plt.show()

# Create data for sine and cosine functions

x = np.linspace(0, 2*np.pi, 100)

y1 = np.sin(x)

y2 = np.cos(x)

# Plot based on sine/cosine functions


plt.figure(figsize=(8, 6))

plt.plot(x, y1, label='sin(x)', color='blue', linestyle='-')

plt.plot(x, y2, label='cos(x)', color='red', linestyle='--')

# Labeling axes and data in the plot

plt.xlabel('x-axis')

plt.ylabel('y-axis')

plt.title('Plot of Sine and Cosine Functions')

plt.legend()

# Show the plot

plt.grid(True)

plt.show()
9: Generate different subplots from a given plot and color plot
data.

import numpy as np

import matplotlib.pyplot as plt

# Create data for the plot

x = np.linspace(0, 10, 100)

y1 = np.sin(x)

y2 = np.cos(x)

# Create a figure and axis objects for subplots

fig, axs = plt.subplots(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

plt.show()

# 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 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

matrix2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])

# Finding the transpose of a matrix

transpose_matrix1 = np.transpose(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 = np.matmul(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 matplotlib.pyplot 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 = np.array([60, 80, 100, 120, 150]).reshape(-1, 1) # Reshape to make it
a 2D array
prices = np.array([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


model.fit(X_train, y_train)
# Make predictions on the testing data
predictions = model.predict(X_test)

# Visualize the training data and the fitted line


plt.scatter(X_train, y_train, color='blue', label='Training Data')
plt.plot(X_train, model.predict(X_train), color='red', label='Fitted Line')
plt.xlabel('Area (sqm)')
plt.ylabel('Price ($k)')
plt.title('Linear Regression: House Price Prediction')
plt.legend()
plt.show()

# Predict the price of a new house with an area of 90 sqm


new_area = np.array([[90]])
predicted_price = model.predict(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 matplotlib.pyplot 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 = np.array([[3, 1, 2, 5], [4, 0, 1, 10], [2, 1, 1, 3], [5, 1, 3, 8],
[3, 0, 2, 6]]) # Features

y = np.array([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

model.fit(X_train, y_train)

# Make predictions on the testing data

predictions = model.predict(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 = np.array([[4, 1, 2, 7]])

predicted_price = model.predict(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 matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix

# Load the Iris dataset


iris = load_iris()
X = iris.data
y = (iris.target == 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


model.fit(X_train, y_train)

# Make predictions on the testing data


predictions = model.predict(X_test)

# Calculate accuracy
accuracy = accuracy_score(y_test, predictions)
print("Accuracy:", accuracy)

# Plot confusion matrix


cm = confusion_matrix(y_test, predictions)
plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
plt.colorbar()
plt.title('Confusion Matrix')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()

OUTPUT:
Accuracy: 1.0
15. Use some function for regularization of dataset based on
problem 14

import numpy as np

import matplotlib.pyplot as plt

from sklearn.datasets import load_iris

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LogisticRegression

from sklearn.metrics 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 = iris.data

y = (iris.target == 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

model.fit(X_train, y_train)

# Make predictions on the testing data

predictions = model.predict(X_test)

# Calculate accuracy

accuracy = accuracy_score(y_test, predictions)

print("Accuracy:", accuracy)

# Plot confusion matrix

cm = confusion_matrix(y_test, predictions)

plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)

plt.colorbar()

plt.title('Confusion Matrix')

plt.xlabel('Predicted Label')

plt.ylabel('True Label')

plt.show()
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 sklearn.metrics 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 sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = (iris.target == 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 = tf.keras.utils.normalize(X_train, axis=1)
X_test = tf.keras.utils.normalize(X_test, axis=1)

# Build the neural network model


model = tf.keras.models.Sequential([
tf.keras.layers.Dense(64, activation=tf.nn.relu),
tf.keras.layers.Dense(64, activation=tf.nn.relu),
tf.keras.layers.Dense(2, activation=tf.nn.softmax)
])

# Compile the model


model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

# Train the model


model.fit(X_train, y_train, epochs=10)

# Evaluate the model


test_loss, test_acc = model.evaluate(X_test, y_test)
print("Test accuracy:", test_acc)

# Make predictions
predictions = model.predict(X_test)
predicted_classes = np.argmax(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)

You might also like