Develop Programs To Understand Concept of Class and Object in Python
Develop Programs To Understand Concept of Class and Object in Python
Practical 5
Aim: Develop programs to understand concept of Class and Object in python.
Theory:
- Class: A blueprint for creating objects. It defines attributes (data) and methods (behavior).
- Example:
```python
class ClassName:
- Object: An instance of a class. Objects hold the actual data and behavior defined by the
class.
- Example:
```python
obj = ClassName()
```
- Instance Variables: Unique to each object, defined inside the constructor (` init `).
- Class Variables: Shared by all objects of the class.
- Constructor (` init `): A special method called when an object is created, used to
initialize instance variables.
- Method: A function defined inside a class, used to define behavior for the objects.
Answer :
class Person:
def init (self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
Diagram:
Practical 6
Aim: Develop programs to demonstrate use of NumPy
import numpy as np
print("Numpy version :",np. version )
print("Numpy Configuration :\n",np.show_config())
Diagram:
import numpy as np
arr = np.arange(10, 70)
print("Array:", arr)
print("Shape:", arr.shape)
print("Data Type:", arr.dtype)
print("Number of Dimensions:", arr.ndim)
Diagram:
import numpy as np
null_vector=np.zeros(5)
print("Null Vector:", null_vector)
Diagram:
4. Create a vector of size 10 initialized with a seed equal to last four digits
of your enrolment number.
import numpy as np
import random
seed=2029
np.random.seed(seed)
random_vector=np.random.randint(0,100,10)
print("Random vector:",random_vector)
Diagram:
5. Create a matrix of size 5x5 initialized with random integers with a seed
equal to last four digits of your enrolment number.
import numpy as np
seed=2029
np.random.seed(seed)
random_int_vector=np.random.randint(1,10,size=(5,5))
print("Random Integer Vector:\n",random_int_vector)
Diagram:
import numpy as np
identity=np.identity(5)
print("Identity Matrix:\n",identity)
Diagram:
7. Do the following
a. Create a numpy array mat1 of size5x2 with numbers ranging from 1 to
10.
b. Create an other numpy array mat2 of size2x5 with floating point
numbers between 10 to 20.
c. Calculate the matrix product of mat1 and mat2.
d. Print vector containing minimum and maximum in each row of mat1.
e. Print vector containing mean and standard deviation in each column of
mat2 Perform vstackand hstack on mat1 and mat2.
f. Perform vstackand hstack on mat1 and mat2.
g. Split mat1 horizontal into 2 and split mat2 vertical into 2 parts.
Answer:
import numpy as np
mat1 = np.arange(1, 11).reshape(5, 2)
print("Matrix 1 (mat1):\n", mat1)
split_mat1 = np.hsplit(mat1, 2)
split_mat2 = np.vsplit(mat2, 2)
print("Split mat1 into 2 parts horizontally:\n", split_mat1)
print("Split mat2 into 2 parts vertically:\n", split_mat2)
Diagram:
import numpy as np
from numpy.linalg import inv
mat = vec.reshape(5, 4)
print("Matrix mat:\n", mat)
vec[1::2] = 1
print("vec after assigning every number at even location to 1:\n", vec)
vec[:10:2] = 0
print("vec after assigning every second element from start to 10th position to 0:\n", vec)
vec = vec[::-1]
print("Reversed vec:\n", vec)
print("sin(vec):\n", np.sin(vec))
print("sqrt(vec):\n", np.sqrt(vec))
print("cos(vec):\n", np.cos(vec))
print("exp(vec):\n", np.exp(vec))
mat_transpose = np.transpose(mat)
print("Transpose of mat:\n", mat_transpose)
try:
mat_inverse = inv(mat)
print("Inverse of mat:\n", mat_inverse)
except np.linalg.LinAlgError:
print("Inverse of mat is not possible due to matrix dimensions or rank.")
Diagram:
shallow_copy = mat.view()
deep_copy = mat.copy()
shallow_copy[0, 0] = 999
deep_copy[1, 1] = 888
print("Original mat:\n", mat)
Diagram:
Practical 7
Aim: Python File Handling to load text & image data
Diagram:
even_records = []
with open("data.txt", "r") as file:
next(file)
for i, line in enumerate(file, start=1):
if i % 2 == 0:
x, y = line.strip().split("\t")
even_records.append((int(x), int(y)))
import random
random_records = []
with open("data.txt", "r") as file:
next(file)
lines = file.readlines()
random_records = random.sample(lines, 5)
print("Random records:")
for line in random_records:
x, y = line.strip().split("\t")
print(f"{x}\t{y}")
Diagram:
import requests
from PIL import Image
from io import BytesIO
image_url = "https://images.unsplash.com/photo-1542744173-05336fcc7ad4?ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8MTB8fGNoYXJ0fGVufDB8fDB8fHww&w
=1000&q=80"
try:
response = requests.get(image_url, allow_redirects=True)
if response.status_code == 200:
image = Image.open(BytesIO(response.content))
image.show()
print("Image Displayed Successfully!!")
else:
print("Failed to download the image. Status code:", response.status_code)
except Exception as e:
Diagram:
PRACTICAL – 8
1. Read the xml file (test.xml) and create a dataframe from it and do the
following. Find and print duplicate records. Remove duplicates and save data in
other dataframe.
import pandas as pd
Diagram :
Fig : test.xml
import pandas as pd
import numpy as np
Diagram :
(b) Print information about data such as data types of each column.
Diagram:
Diagram:
Diagram:
Diagram:
Diagram:
Diagram:
(h) Print average cooking_time & prep_time for vegetarian diet type.
Diagram:
(i) Insert a new column with column name as total_time which contains sum of
cooking_time & prep_time into existing dataframe.
# Insert a new column ‘total_time’ with the sum of cooking_time and prep_time
df[‘total_time’] = df[‘cook_time’] + df[‘prep_time’]
# Print the DataFrame to verify the new column
print(df)
Diagram:
Diagram :
# Group the data by 'region' and 'flavor_profile', and get the count
flavor_profile_count = df.groupby(['region',
'flavor_profile']).size().reset_index(name='count')
# Print the count of items with various flavor profiles per region
print("Count of items with various flavor profiles per region:")
print(flavor_profile_count)
Diagram:
(l) Find & print records with missing data in the state column. Fill missing data
in the state column with -.
# Find and print records with missing data in the 'state' column
missing_state_records = df[df['state'].isnull()]
print("Records with missing data in the 'state' column:")
print(missing_state_records)
# Fill missing data in the 'state' column with "-" and set categories
df['state'].cat.add_categories(['-'], inplace=True)
df['state'].fillna('-', inplace=True)
Diagram :
Practical 9
Aim: Develop programs to visualize the data using matplotlib
1. Line plot
import matplotlib.pyplot as plt
x = [10, 8, 3, 2, 1]
y = [7, 6, 5, 4, 2]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')plt.show()
Diagram:
2. Scatter Plot
import matplotlib.pyplot as plt
x = [6, 12, 13, 4, 5]
y = [3, 4, 8, 1, 2]
plt.scatter(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot')
plt.show()
Diagram:
3. Bar Chart
import matplotlib.pyplot as plt
categories = ['Category A', 'Category B', 'Category C']
values = [14, 5, 9]
plt.bar(categories, values)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart')
plt.show()
Diagram:
4. Histogram
Diagram:
5. Pie Chart
Diagram:
Practical 10
Aim: Demonstration of Scikit-learn and other machine learning libraries such as
keras, tensorflow etc.
1. Scikit-Learn:
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
feature_names = iris.feature_names
target_names = iris.target_names
Diagram:
2. Keras:
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop
batch_size = 128
num_classes = 10
epochs = 5
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))
model.summary()
Diagram:
Practical 11
Beyond Syllabus
Aim: Apply knowledge of Data Science to analyze and visualize any real-life
dataset using python libraries.
Diagram: