Exp 12 - Train and Save A Machine Learning Model - J062
Exp 12 - Train and Save A Machine Learning Model - J062
(Students must submit the soft copy as per following segments within two hours of the practical. The
soft copy must be uploaded on the Blackboard or emailed to the concerned lab in charge faculties
at the end of the practical in case the there is no Black board access available)
Grade :
B.1 Code:
Models.py
import joblib
X = glass.data
y = glass.target
model.fit(X_train, y_train)
SVKM’s NMIMS
Mukesh Patel School of Technology Management & Engineering (Mumbai Campus)
IMAD
Lab Manual
joblib.dump(model, 'glass_classification_model.pkl')
Views.py
import joblib
def predict_glass_type(request):
prediction = None
if request.method == 'POST':
form = GlassPredictionForm(request.POST)
if form.is_valid():
model = joblib.load('glass_classification_model.pkl')
features = form.get_features_as_array()
prediction = model.predict(features)[0]
else:
form = GlassPredictionForm()
Forms.py
from django import forms
import numpy as np
SVKM’s NMIMS
Mukesh Patel School of Technology Management & Engineering (Mumbai Campus)
IMAD
Lab Manual
class GlassPredictionForm(forms.Form):
feature_1 = forms.FloatField(label="RI")
feature_2 = forms.FloatField(label="Na")
feature_3 = forms.FloatField(label="Mg")
feature_4 = forms.FloatField(label="Al")
feature_5 = forms.FloatField(label="Si")
feature_6 = forms.FloatField(label="K")
feature_7 = forms.FloatField(label="Ca")
feature_8 = forms.FloatField(label="Ba")
feature_9 = forms.FloatField(label="Fe")
def get_features_as_array(self):
features = np.array([
self.cleaned_data['feature_1'],
self.cleaned_data['feature_2'],
self.cleaned_data['feature_3'],
self.cleaned_data['feature_4'],
self.cleaned_data['feature_5'],
self.cleaned_data['feature_6'],
self.cleaned_data['feature_7'],
self.cleaned_data['feature_8'],
self.cleaned_data['feature_9']
])
Prediction.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body {
.container {
max-width: 900px;
margin: 0 auto;
padding: 20px;
display: flex;
gap: 20px;
.form-container, .result-container {
flex: 1;
form {
display: grid;
gap: 10px;
SVKM’s NMIMS
Mukesh Patel School of Technology Management & Engineering (Mumbai Campus)
IMAD
Lab Manual
}
label {
font-weight: bold;
.result-container {
padding: 20px;
background-color: #f0f0f0;
</style>
</head>
<body>
<div class="container">
<div class="form-container">
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<div>
<button type="submit">Predict</button>
</div>
</form>
</div>
<div class="result-container">
SVKM’s NMIMS
Mukesh Patel School of Technology Management & Engineering (Mumbai Campus)
IMAD
Lab Manual
{% if prediction %}
<h2>Prediction Result:</h2>
{% else %}
{% endif %}
</div>
</div>
</body>
</html>
SVKM’s NMIMS
Mukesh Patel School of Technology Management & Engineering (Mumbai Campus)
IMAD
Lab Manual
B.2 Output
B.3 Conclusion:
We learnt to make a reusable Django form that can gather the required features for model prediction. This
form can be used in a Django view to handle user inputs, pass them to the trained model, and display the
classification results, providing a fully interactive experience for the user.
SVKM’s NMIMS
Mukesh Patel School of Technology Management & Engineering (Mumbai Campus)
IMAD
Lab Manual
B.4 Question of Curiosity
1. How does Django handle form data for making machine learning predictions?
Ans: Django uses forms.Form classes to define fields that accept user input and validate it. In a machine
learning application, we create a form with fields corresponding to model input features. When the user
submits the form, Django collects and cleans the data. We can then convert this cleaned data into the
appropriate format (e.g., a NumPy array or Pandas DataFrame) and pass it to the machine learning model
for prediction.
2. How can you save and load a machine learning model in Django?
Ans: To save and load machine learning models in Django, you can use libraries like joblib or pickle.
Here’s how:
● Saving: After training your model, use joblib.dump(model, 'model.pkl') to save it to a file (e.g., in
the models/ directory).
● Loading: Load the model in your Django view with model = joblib.load('path/to/model.pkl').
This allows you to reuse the trained model without retraining it each time.
3. What are the steps involved in integrating a machine learning model with a Django web
application?
Ans:
Train and Save the Model: Train your machine learning model in a Jupyter notebook or script, then
save it as a .pkl or .joblib file.
Create a Django Form: Define a form with fields corresponding to the input features of your model
to capture user input.
Build a View for Prediction: Load the saved model in the view, get the cleaned form data, and use it
as input for the model's predict function.
Display the Result: Pass the prediction result from the model to the HTML template to display it to
the user.
Front-End: Design the form and result display in a Django HTML template, and make the user
experience interactive.
4. What are some advantages of deploying a machine learning model using Django?
Ans:
SVKM’s NMIMS
Mukesh Patel School of Technology Management & Engineering (Mumbai Campus)
IMAD
Lab Manual
Full-Stack Framework: Django provides a complete suite of tools to handle the front end, back end,
and database, allowing for end-to-end deployment.
User-Friendly Interface: With Django’s form and template system, you can easily create user-
friendly interfaces for non-technical users to interact with the model.
Built-In Security: Django provides built-in security features (e.g., CSRF protection, input
sanitization) to ensure safe handling of user input.
Scalability: Django supports horizontal scaling, which allows your application to handle high loads by
adding more servers as needed.
Ecosystem Support: Django integrates well with other technologies and libraries for tasks such as
model serialization, caching, and API creation (e.g., Django REST Framework).
5. How does Django handle user input security in the context of machine learning applications?
Ans: Django has several built-in mechanisms for handling user input securely:
● CSRF Protection: Django uses Cross-Site Request Forgery protection for form submissions,
reducing the risk of malicious requests.
● Input Validation and Sanitization: Django forms automatically validate and sanitize input data,
which helps prevent SQL injection and other attacks.
● XSS Protection: Django escapes any output rendered in templates, protecting against Cross-Site
Scripting (XSS) attacks.
● Field Type Enforcement: When defining forms, Django enforces the data type (e.g., FloatField,
IntegerField), ensuring that only valid data is processed.
6. What challenges might you face when deploying machine learning models with Django in a
production environment?
Ans:
Scalability: Machine learning models can be resource-intensive, and handling multiple requests in real
time may lead to performance bottlenecks.
Latency: Depending on the complexity of the model, generating predictions can take time, which may
lead to delays in a live application.
Dependency Management: ML models often require specific library versions, which can conflict
with Django’s dependencies.
SVKM’s NMIMS
Mukesh Patel School of Technology Management & Engineering (Mumbai Campus)
IMAD
Lab Manual
Model Retraining: Keeping the model updated with new data requires a system for regular retraining
and deployment.
Security: Handling sensitive data securely is crucial, especially if the model uses user data for
predictions.
Resource Allocation: Handling resource-heavy models (like deep learning models) may require
specialized infrastructure (e.g., GPUs or distributed systems).
7. What are some best practices for deploying machine learning models in a Django
application?
Ans:
Use a Separate API for Predictions: Consider using Django REST Framework to create an API
endpoint for predictions, allowing you to decouple the model from the web interface.
Optimize the Model: Use optimized versions of your model, such as pruning or quantization, to
reduce latency.
Implement Caching: Cache frequently requested predictions to reduce computation time and enhance
performance.
Monitor and Log Predictions: Track prediction requests, inputs, and outputs to understand usage
patterns and catch any issues early.
Automate Retraining and Deployment: If your model needs to be updated regularly, set up a
pipeline for model retraining, validation, and deployment.
Use Cloud Services if Needed: For complex models, consider deploying on cloud services with
scalable compute resources (e.g., AWS SageMaker or Google AI Platform) and connecting them to your
Django application.