0% found this document useful (0 votes)
5 views17 pages

Lab1 ML Eac22050

Uploaded by

am.en.u4eac22015
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)
5 views17 pages

Lab1 ML Eac22050

Uploaded by

am.en.u4eac22015
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/ 17

Name: PARTTHIV MURALI R P Roll number:AM.EN.

U4EAC22050

DEPARTMENT OF ELECTRONICS AND COMMUNICATION


ENGINEERING
19EAC381 MACHINE LEARNING WITH PYTHON
LABSHEET 1
Introduction to python
Course Outcome: Date:

Aim: (Objective)
• To familiarize with Python language.
• To familiarize with commonly used packages for Machine Learning and
Data Manipulation in Python.
Introduction:
Python is a great general-purpose programming language on its own, but with
the help of a few popular libraries/packages it becomes a powerful environment
for scientific computing. This lab sheet is a brief introduction to some of the
popular packages that we would be using throughout the course of the Lab.

EXAMPLES:
Create Arrays
Special Arrays

Slicing of Arrays

Rank 1 and Rank 2 View of Arrays


Integer Indexing

Boolean Indexing

Mathematical Operations on Arrays


x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
# Elementwise sum; both produce the array
print(x + y)
print(np.add(x, y))
# Elementwise difference; both produce the array
print(x - y)
print(np.subtract(x, y))
# Elementwise product; both produce the array
print(x * y)
print(np.multiply(x, y))
# Elementwise division; both produce the array
print(x / y)
print(np.divide(x, y))
# Elementwise square root; produces the array
print(np.sqrt(x))
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
v = np.array([9,10])
w = np.array([11, 12])
# Inner product of vectors
print(v.dot(w))
print(np.dot(v, w))
# Matrix / vector product; both produce the rank 1 array [29 67]
print(x.dot(v))
print(np.dot(x, v))
print(x @ v)

x = np.array([[1,2],[3,4]])
print(np.sum(x)) # Compute sum of all elements; prints "10"
print(np.sum(x, axis=0)) # Compute sum of each column; prints "[4 6]"
print(np.sum(x, axis=1)) # Compute sum of each row
#Transpose
print(x)
print("transpose\n",x.T)

# Broadcasting
# We will add the vector v to each row of the matrix x,
# Storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x) # Create an empty matrix with the same shape as x
# Add the vector v to each row of the matrix x with an explicit loop
for i in range(4):
y[i, :] = x[i, :] + v
print(y)
# Another Method
vv = np.tile(v, (4, 1)) # Stack 4 copies of v on top of each other
print(vv)
y = x + vv # Add x and vv elementwise
print(y)
Linear Algebra Package
A = np.array([[6, 1, 1],
[4, -2, 5],
[2, 8, 7]])

B = np.array([[1,2,3],
[4,5,6]])
# Rank of a matrix
print("Rank of A:",np.linalg.matrix_rank(A))

# Determinant of a matrix
print("\nDeterminant of A:",np.linalg.det(A))

# Inverse of matrices
print("\nInverse of A:\n",np.linalg.inv(A))

#Pseudoinverse of a matrix
print("\n Pseudoinverse of B:\n",np.linalg.pinv(B))

#Matrix raised to the power 3


print("\nMatrix A raised to power 3:\n",np.linalg.matrix_power(A, 3))

#Eigen value calculation


a = np.diag((1, 2, 3))
print("\n Array is :\n",a)

# calculating an eigen value


# using eig() function
c,d = np.linalg.eig(a)
print("\nEigen value is :\n",c)
print("\nEigen vector is :\n",d)

Plotting
Reading Images
Pandas Package
EXERCISES

Explanation:

In NumPy, reshape an array can be done to change its structure while keeping the data the same, as
long as the total number of elements remains constant. For example, a 3x4 array (12 elements) can
be reshaped into a 2x2x3 array using the reshape() function.

Explanation:

To create a matrix of size m×nm \times nm×n with random values in the range [−2,5][-2, 5][−2,5]
using NumPy, the user inputs the dimensions, and the numpy.random.uniform(low, high,
size) function generates the matrix. This method efficiently produces random values for
applications like data analysis and simulations.
Explanation:

To create 100 random 10-dimensional vectors, we use NumPy to generate a 10×10010 \times
10010×100 matrix filled with random values using numpy.random.rand(). This matrix is then
saved to a CSV file using numpy.savetxt(), facilitating easy data storage for various applications.

Explanation:

To compute the mean and covariance matrix from random points in a CSV file using NumPy, we read
the matrix XXX of 100 random 10-dimensional vectors. The mean (μ\muμ) is calculated with
np.mean(), and the covariance matrix (CCC) is obtained using np.cov(), which reveals the
relationships between dimensions.
Explanation:

To plot the function y=3x+2y = 3x + 2y=3x+2 over the interval [−10,10][-10, 10][−10,10], we use
NumPy to generate evenly spaced xxx values and calculate the corresponding yyy values. We then
utilize Matplotlib to create the plot, adding labels, a title, and grid lines for clarity. This visualization
helps analyze the linear relationship represented by the function.

#6
import numpy as np
import matplotlib.pyplot as plt

# Parameters for the ellipse


a = 10 # Semi-major axis
b = 5 # Semi-minor axis
center_x = 5 # Center of the ellipse along x-axis
# Number of points
num_points = 1000

# Generate random angles between 0 and 2pi


theta = np.random.uniform(0, 2 * np.pi, num_points)

# Generate random radii to ensure points are uniformly distributed within the
ellipse
r = np.random.uniform(0, 1, num_points)

# Parametric equations for the ellipse


x = center_x + (r * a * np.cos(theta))
y = r * b * np.sin(theta)

# Plot the points


plt.figure(figsize=(6, 6))
plt.scatter(x, y, s=5, color='blue')
plt.title('1000 Points within an Ellipse')
plt.xlabel('X')
plt.ylabel('Y')
plt.gca().set_aspect('equal') # Set equal aspect ratio to make the ellipse
look correct
plt.show()

Explanation:

To generate 1000 points within the ellipse defined by the given equation, we sample random angles
ttt uniformly from 000 to 2π2\pi2π and radial distances from a uniform distribution (scaled by the
square root for uniformity). These are converted to Cartesian coordinates to get xxx and yyy values.
Finally, we visualize the points and the ellipse boundary using Matplotlib.
Evaluation:
Participation Ethics Conduct Result Total
/20

Signature of the Faculty:


Date:

You might also like