21
loading...
This website collects cookies to deliver better user experience
While sending data over the internet the data is transfered mostly in Json form (JSON is a format that encodes objects in a string and deserialization it (convert string -> object))
Hugh Machine Learning Model that are trained on hugh amount of data ,need to stored in some form for later use ,we cannot re-train them again and again , that is where serialization help
to store ML model state.
Big Data system uses serialization and deseralization to store large amount of data.
dump() − The dump() method serializes to an open file (file-like object).
dumps() − Serializes to a string
load() − Deserializes from an open-like object.
loads() − Deserializes from a string.
import pickle
class Student:
def __init__(self,firstname,lastname,age,standard):
self.firstname = firstname
self.lastname = lastname
self.age = age
self.standard = standard
def showinfo(self):
print(f"Firstname :- {self.firstname}")
print(f"Lastname :- {self.lastname}")
print(f"Age :- {self.age}")
print(f"Standarad :- {self.standard}")
student1 = Student("Adarsh","Raven",21,"12th")
student2 = Student("Ankit",'Raven',24,'11th')
# Student Info
print("Student1 :- ")
student1.showinfo()
print("\nStudent2 :- ")
student2.showinfo()
# Serializing object
picked_student1 = pickle.dumps(student1)
picked_student2 = pickle.dumps(student2)
# Object stored in Byte steam
print("serialized student",picked_student1)
Output :-
Student1 :-
Firstname :- Adarsh
Lastname :- Raven
Age :- 21
Standarad :- 12th
Student2 :-
Firstname :- Ankit
Lastname :- Raven
Age :- 24
Standarad :- 11th
serialized student b'\x80\x03c__main__\nStudent\nq\x00)\x81q\x01}q\x02(X\t\x00\x00\x00firstnameq\x03X\x06\x00\x00\x00Adarshq\x04X\x08\x00\x00\x00lastnameq\x05X\x05\x00\x00\x00Ravenq\x06X\x03\x00\x00\x00ageq\x07K\x15X\x08\x00\x00\x00standardq\x08X\x04\x00\x00\x0012thq\tub.'
orignal_student1 = pickle.loads(picked_student1)
orignal_student2 = pickle.loads(picked_student2)
print("\n\nAfter Getting object back from the saved state :- \n")
print("Student1 :- ")
orignal_student1.showinfo()
print("\nStudent2 :- ")
orignal_student2.showinfo()
Output :-
After Getting object back from the saved state :-
Student1 :-
Firstname :- Adarsh
Lastname :- Raven
Age :- 21
Standarad :- 12th
Student2 :-
Firstname :- Ankit
Lastname :- Raven
Age :- 24
Standarad :- 11th