Menu

Machine Learning - (LAB PROGRAMS)


Week 2

  Study of Python Basic Libraries such as Statistics, Math, Numpy and Scipy

Solution :


Python is a powerful programming language widely used for data analysis, scientific research, and statistical computing. Several libraries in Python make it particularly strong in these areas:

1. Statistics Library:

The statistics module provides functions to perform basic statistical operations like calculating the mean, median, mode, variance, and standard deviation.

Key Functions:

  • mean(data): Returns the arithmetic mean of the data.
  • median(data): Returns the median value.
  • mode(data): Returns the mode (most frequent value).
  • variance(data): Returns the variance of the data.
  • stdev(data): Returns the standard deviation.

  Library Installation :

Don't need to install statistics module library, because this is a built-in module in Python 3.4 and later versions.


Source Code:

File Name: Stat_Lib.py


import statistics
# Input data from user
data=input("Enter data separated by comma:")
data=[int(x) for x in data.split(',')]
# Compute Mean
mean=statistics.mean(data)
# Compute Median
median=statistics.median(data)
# Compute Mode
mode=statistics.mode(data)
# Compute Standard Deviation
std_dev=statistics.stdev(data)
# Compute Variance
variance=statistics.variance(data)
# Output results
print(f"Mean={mean}")
print(f"Median={median}")
print(f"Mode={mode}")
print(f"Standard Deviation={std_dev}")
print(f"Variance={variance}")


Output:


Sample Run:
--------------
$python3 Stat_Lib.py.py
Enter data separated by comma:1,2,3,4,4,5,6
Mean=3.5714285714285716
Median=4
Mode=4
Standard Deviation=1.7182493859684491
Variance=2.9523809523809526



2. Math Library:

The math module offers a range of mathematical functions that operate on numbers and perform tasks such as trigonometric calculations, logarithms, and square roots.

Key Functions:

  • math.ceil(x): Returns the smallest integer greater than or equal to x.
  • math.factorial(x): Returns the factorial of a non-negative integer x.
  • math.exp(x): Returns exe^xex, where eee is the base of natural logarithms (approximately 2.718).
  • math.sqrt(x): Returns the square root of x.
  • math.floor(x): Returns the largest integer less than or equal to x.
  • math.gcd(x, y): Returns the greatest common divisor (GCD) of two integers x and y.
  • math.pow(x, y): Returns xyx^yxy (x raised to the power of y).
  • math.radians(angle): Converts an angle from degrees to radians.
  • math.sin(x): Returns the sine of x, where x is in radians.
  • math.cos(x): Returns the cosine of x, where x is in radians.
  • math.tan(x): Returns the tangent of x, where x is in radians.

  Library Installation:

Don't need to install math module library, because this is a built-in module in Python.


Source Code:

File Name: Math_Lib.py


import math
x=int(input("Enter a number:"))
result1=math.ceil(x)
result2=math.factorial(x)
result3=math.exp(x)
result4=math.sqrt(x)
result5=math.floor(x)
n1=int(input("Enter number1:"))
n2=int(input("Enter number2:"))
result6=math.gcd(n1,n2)
result7=math.pow(n1,n2)
angle=int(input("Enter an angle:"))
a=math.radians(angle)
result8=math.sin(a)
result9=math.cos(a)
result10=math.tan(a)
print(f"Using math.ceil({x}): {result1}")
print(f"Using math.factorial({x}):{result2}")
print(f"Using math.exp({x}):{result3}")
print(f"Using math.sqrt({x}):{result4}")
print(f"Using math.floor({x}):{result5}")
print(f"Using math.gcd({n1},{n2}):{result6}")
print(f"Using math.pow({n1},{n2}):{result7}")
print(f"Using math.sin({angle}):{result8}")
print(f"Using math.cos({angle}):{result9}")
print(f"Using math.tan({angle}):{result10:.15f}")


Output:


Sample Run:
--------------
$python3 Math_Lib.py.py

Enter a number:4
Enter number1:3
Enter number2:2
Enter an angle:1
Using math.ceil(4): 4
Using math.factorial(4):24
Using math.exp(4):54.598150033144236
Using math.sqrt(4):2.0
Using math.floor(4):4
Using math.gcd(3,2):1
Using math.pow(3,2):9.0
Using math.sin(1):0.01745240643728351
Using math.cos(1):0.9998476951563913
Using math.tan(1):0.017455064928218



3. Numpy Library:

numpy is a library for numerical computing in Python. It is used for working with arrays and matrices, along with a collection of mathematical functions to operate on these data structures.

Key Functions:

  • np.array(data): Creates a numpy array from the given list of elements.
  • reshape(rows, cols): Reshapes an array into the specified number of rows and columns.
  • np.ones((rows, cols)): Creates an array filled with ones of the specified shape (number of rows and columns).
  • np.zeros((rows, cols)): Creates an array filled with zeros of the specified shape (number of rows and columns).
  • np.transpose(array): Returns the transpose of the given array, flipping rows into columns and vice versa.
  • np.min(array): Finds the minimum value in the array.
  • np.max(array): Finds the maximum value in the array.

Library Installation:

To install Numpy library, Open Command Prompt or Terminal and execute the following commands


# To install numpy on Linux
$ sudo apt install python3-numpy
(or)
$ pip3 install numpy

# To install numpy on Windows
pip install numpy

Source Code:

File Name: Numpy_Lib.py


import numpy as np
# Get number of rows and columns from user
rows=int(input("Enter number of rows:"))
cols=int(input("Enter number of columns:"))
# Get array elements from user
elements=list(map(float, input(f"Enter {rows*cols} elements separated by spaces:").split()))
# Create an array from user input
user_array=np.array(elements).reshape(rows,cols)
# Create an array of ones and zeros
ones_array=np.ones((rows, cols))
zeros_array=np.zeros((rows, cols))
# Transpose the user array
transposed_array=np.transpose(user_array)
# Reshape the user array (to a flat array and back to the original shape for demonstration)
reshaped_array = user_array.reshape(rows * cols)
min_value=np.min(elements)
max_value=np.max(elements)
# Display the results
print("User Array:\n",user_array)
print("Ones Array:\n",ones_array)
print("Zeros Array:\n",zeros_array)
print("Transposed Array:\n",transposed_array)
print("Reshaped Array (flattened):\n",reshaped_array)
print("Minimum Value:",min_value)
print("Maximum Value:",max_value)


Output:


Sample Run:
--------------
$python3 Numpy_Lib.py
Enter number of rows:2
Enter number of columns:2
Enter 4 elements separated by spaces:1 2 3 4
User Array:
 [[1. 2.]
 [3. 4.]]
Ones Array:
 [[1. 1.]
 [1. 1.]]
Zeros Array:
 [[0. 0.]
 [0. 0.]]
Transposed Array:
 [[1. 3.]
 [2. 4.]]
Reshaped Array (flattened):
 [1. 2. 3. 4.]
Minimum Value: 1.0
Maximum Value: 4.0



4. Scipy Library:

Scipy builds on numpy and provides a wide range of advanced mathematical, scientific, and engineering functions, including optimization, integration, interpolation, and statistical operations.

Key Functions:

From scipy.constants:

  • constants.minute: Returns the number of seconds in a minute (60.0).
  • constants.hour: Returns the number of seconds in an hour (3600.0).
  • constants.inch: Returns the length of an inch in meters (0.0254).
  • constants.liter: Returns the volume of a liter in cubic meters (0.001).

From scipy.special:

  • special.exp10(x): Calculates 10x, where x is the exponent provided by the user.
  • special.sindg(angle): Returns the sine of an angle (in degrees).
  • special.cosdg(angle): Returns the cosine of an angle (in degrees).

From scipy.linalg:

  • linalg.det(matrix): Calculates the determinant of a square matrix. If the input matrix is not square, the determinant cannot be calculated.

From numpy:

  • np.array(data): Creates a NumPy array from the provided list of elements.
  • reshape(rows, cols): Reshapes the array into the specified number of rows and columns.

Library Installation:

To install scipy library, Open Command Prompt or Terminal and execute the following commands


# To install scipy on Linux
$ sudo apt install python3-scipy
(or)
$ pip3 install scipy

# To install scipy on Windows
pip install scipy

Source Code:

File Name: Scipy_Lib.py


from scipy import linalg
import numpy as np
from scipy import special
from scipy import constants
# Print constants
print("Seconds in a minute:",constants.minute) # 60.0
print("Seconds in an hour:",constants.hour) # 3600.0
print("Length of an inch in meters:",constants.inch) # 0.0254
print("Volume of a liter in cubic meters:",constants.liter) # 0.001
# Dynamic input for exponentiation
exp_input = float(input("Enter the exponent for 10^x:"))
print(f"10^{exp_input} =",special.exp10(exp_input))
# Dynamic input for angles in degrees
angle=float(input("Enter an angle for sine and cosine(in degrees):"))
#Calculate sine and cosine of the input angles
print(f"sin({angle} degrees):",special.sindg(angle))
print(f"cos({angle} degrees):",special.cosdg(angle))
# Dynamic input for matrix
rows = int(input("Enter the number of rows for the matrix:"))
cols = int(input("Enter the number of columns for the matrix:"))
mat = list(map(float, input(f"Enter {rows * cols} elements separated by spaces:").split()))
# Convert the flat list into a 2D NumPy array
mat=np.array(mat).reshape((rows, cols))
# Calculate the determinant if the matrix is square
if rows == cols:
	x = linalg.det(mat)
	print(f'Determinant of the matrix\n{mat}\n is: {x}')
else:
	print("Determinant can only be calculated for square matrices.")


Output:


Sample Run:
--------------
$python Scipy_Lib.py
Seconds in a minute: 60.0
Seconds in an hour: 3600.0
Length of an inch in meters: 0.0254
Volume of a liter in cubic meters: 0.001
Enter the exponent for 10^x:2
10^2.0 = 100.0
Enter an angle for sine and cosine(in degrees):90
sin(90.0 degrees): 1.0
cos(90.0 degrees): -0.0
Enter the number of rows for the matrix:2
Enter the number of columns for the matrix:2
Enter 4 elements separated by spaces:2 3 4 5
Determinant of the matrix
[[2. 3.]
 [4. 5.]]
 is: -2.0000000000000004



Related Content :

Machine Learning Lab Programs

1) Write a python program to compute
  •  Central Tendency Measures: Mean, Median,Mode
  •  Measure of Dispersion: Variance, Standard Deviation
  View Solution

2) Study of Python Basic Libraries such as Statistics, Math, Numpy and Scipy   View Solution

3) Study of Python Libraries for ML application such as Pandas and Matplotlib   View Solution

4) Write a Python program to implement Simple Linear Regression   View Solution

5) Implementation of Multiple Linear Regression for House Price Prediction using sklearn   View Solution

6) Implementation of Decision tree using sklearn and its parameter tuning   View Solution

7) Implementation of KNN using sklearn   View Solution

8) Implementation of Logistic Regression using sklearn   View Solution

9) Implementation of K-Means Clustering   View Solution

10) Performance analysis of Classification Algorithms on a specific dataset (Mini Project)   View Solution