This is my views (django), help me add classification report and prediction probablity
from django.shortcuts import render
Import necessary libraries for the API
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import GradientBoostingClassifier, AdaBoostClassifier
from xgboost import XGBClassifier # Ensure you have xgboost installed
import joblib
import numpy as np
# Load dataset and split (using the Iris dataset for example)
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
# Train based on selected model type
if model_type == 'random_forest':
model = RandomForestClassifier(n_estimators=epochs)
elif model_type == 'decision_tree':
model = DecisionTreeClassifier()
elif model_type == 'logistic_regression':
model = LogisticRegression(max_iter=epochs)
elif model_type == 'svm':
model = SVC()
elif model_type == 'knn':
model = KNeighborsClassifier(n_neighbors=epochs) # Using epochs as number of neighbors
elif model_type == 'naive_bayes':
model = GaussianNB()
elif model_type == 'gradient_boosting':
model = GradientBoostingClassifier(n_estimators=epochs)
elif model_type == 'adaboost':
model = AdaBoostClassifier(n_estimators=epochs)
elif model_type == 'xgboost':
model = XGBClassifier(n_estimators=epochs)
else:
return Response({'error': 'Invalid model type'}, status=status.HTTP_400_BAD_REQUEST)
# Train the model
model.fit(X_train, y_train)
# Save the model
joblib.dump(model, f'{model_type}_model.joblib')
return Response({'status': f'Model {model_type} trained successfully'}, status=status.HTTP_202_ACCEPTED)
Assistant
class PredictView(APIView):
def post(self, request):
global model
# Get the model type and input data from the request
model_type = request.data.get('modelType')
input_data = request.data.get('inputData')
code
# Load the corresponding model
try:
model = joblib.load(f'{model_type}_model.joblib')
except FileNotFoundError:
return Response({'error': 'Model not found'}, status=status.HTTP_404_NOT_FOUND)
# Ensure input data is in the correct format
try:
# Convert input data to a NumPy array
input_features = np.array(input_data).reshape(1, -1) # Reshape for a single sample
prediction = model.predict(input_features)
# Return the prediction result
return Response({'prediction': prediction.tolist()}, status=status.HTTP_200_OK)
except Exception as e:
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
Certainly! To enhance your Django views with a classification report and prediction probabilities, you'll need to make the following updates:
Add a Classification Report after Training:
Use sklearn.metrics.classification_report to generate a detailed classification report.
Return this report in the response of the TrainModelView.
Add Prediction Probabilities in Predictions:
Utilize model.predict_proba to obtain prediction probabilities.
Handle cases where the model might not support probability predictions (e.g., some configurations of SVM).
Below is the updated code with these features integrated:
python
from django.shortcuts import render
# Import necessary libraries for the API
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import GradientBoostingClassifier, AdaBoostClassifier
from xgboost import XGBClassifier # Ensure you have xgboost installed
import joblib
import numpy as np
from sklearn.metrics import classification_report
# Global variable to store the model (optional)
model = None
class TrainModelView(APIView):
def post(self, request):
model_type = request.data.get('modelType')
epochs = int(request.data.get('epochs', 100))
# Load dataset and split (using the Iris dataset for example)
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=42
)
# Initialize the model based on selected model type
try:
if model_type == 'random_forest':
model = RandomForestClassifier(n_estimators=epochs, random_state=42)
elif model_type == 'decision_tree':
model = DecisionTreeClassifier(random_state=42)
elif model_type == 'logistic_regression':
model = LogisticRegression(max_iter=epochs, random_state=42)
elif model_type == 'svm':
model = SVC(probability=True, random_state=42) # Enable probability
elif model_type == 'knn':
model = KNeighborsClassifier(n_neighbors=epochs) # Using epochs as number of neighbors
elif model_type == 'naive_bayes':
model = GaussianNB()
elif model_type == 'gradient_boosting':
model = GradientBoostingClassifier(n_estimators=epochs, random_state=42)
elif model_type == 'adaboost':
model = AdaBoostClassifier(n_estimators=epochs, random_state=42)
elif model_type == 'xgboost':
model = XGBClassifier(n_estimators=epochs, use_label_encoder=False, eval_metric='mlogloss')
else:
return Response(
{'error': 'Invalid model type'}, status=status.HTTP_400_BAD_REQUEST
)
except Exception as e:
return Response(
{'error': f'Error initializing model: {str(e)}'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
# Train the model
try:
model.fit(X_train, y_train)
except Exception as e:
return Response(
{'error': f'Error during training: {str(e)}'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
# Save the model
try:
joblib.dump(model, f'{model_type}_model.joblib')
except Exception as e:
return Response(
{'error': f'Error saving model: {str(e)}'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
# Generate classification report
try:
y_pred = model.predict(X_test)
report = classification_report(y_test, y_pred, output_dict=True)
except Exception as e:
return Response(
{'error': f'Error generating classification report: {str(e)}'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
return Response(
{
'status': f'Model {model_type} trained successfully',
'classification_report': report
},
status=status.HTTP_202_ACCEPTED
)
class PredictView(APIView):
def post(self, request):
model_type = request.data.get('modelType')
input_data = request.data.get('inputData')
if not model_type or not input_data:
return Response(
{'error': 'modelType and inputData are required'}, status=status.HTTP_400_BAD_REQUEST
)
# Load the corresponding model
try:
model = joblib.load(f'{model_type}_model.joblib')
except FileNotFoundError:
return Response(
{'error': 'Model not found. Please train the model first.'},
status=status.HTTP_404_NOT_FOUND
)
except Exception as e:
return Response(
{'error': f'Error loading model: {str(e)}'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
# Ensure input data is in the correct format
try:
# Convert input data to a NumPy array
input_features = np.array(input_data).reshape(1, -1) # Reshape for a single sample
# Make prediction
prediction = model.predict(input_features)
prediction_proba = None
# Attempt to get prediction probabilities if available
if hasattr(model, 'predict_proba'):
prediction_proba = model.predict_proba(input_features).tolist()
elif hasattr(model, 'decision_function'):
# For models like SVM without predict_proba, use decision_function
decision_scores = model.decision_function(input_features).tolist()
prediction_proba = decision_scores # You might want to process this differently
else:
prediction_proba = 'Probability estimates not available for this model.'
# Return the prediction result and probabilities
response_data = {
'prediction': prediction.tolist()
}
if prediction_proba is not None:
response_data['probabilities'] = prediction_proba
return Response(response_data, status=status.HTTP_200_OK)
except Exception as e:
return Response(
{'error': f'Error during prediction: {str(e)}'},
status=status.HTTP_400_BAD_REQUEST
)
Explanation of Changes:
Classification Report in TrainModelView:
Import: Added from sklearn.metrics import classification_report.
Model Initialization:
Added random_state=42 for reproducibility across various models.
For SVC, set probability=True to enable probability predictions.
For XGBClassifier, added use_label_encoder=False and eval_metric='mlogloss' to suppress warnings and set an appropriate evaluation metric.
Error Handling: Added try-except blocks around model initialization, training, saving, and report generation to handle potential errors gracefully.
Classification Report:
After training, predictions are made on the test set using y_pred = model.predict(X_test).
The classification report is generated with classification_report(y_test, y_pred, output_dict=True), which returns the report as a dictionary.
The report is included in the response alongside the training status.
Prediction Probabilities in PredictView:
Input Validation: Ensured that both modelType and inputData are provided in the request.
Loading the Model: Added error handling to manage scenarios where the model file might not exist or fails to load.
Making Predictions:
Converted inputData to a NumPy array and reshaped it appropriately.
Performed prediction using model.predict(input_features).
Prediction Probabilities:
Checked if the model has the predict_proba method using hasattr(model, 'predict_proba').
If available, obtained probabilities with model.predict_proba(input_features).tolist().
For models like SVM that might not have predict_proba even if probability=True, checked for decision_function. This provides decision scores which can be used as a proxy for probabilities, but they are not calibrated probabilities.
If neither is available, provided a message indicating that probability estimates are not available.
Additional Recommendations:
Model Persistence:
Consider storing metadata about your models (e.g., model type, training parameters, performance metrics) in a database for better management and retrieval.
Security:
Ensure that only authorized users can train models or make predictions, especially if deploying this API publicly.
Input Validation:
Validate the shape and type of inputData to match the training data’s requirements. This can prevent runtime errors during prediction.
Performance:
For large-scale applications, consider optimizing model loading and possibly keeping models in memory instead of loading them from disk on every prediction request.
Here, 0 corresponds to the first class in the Iris dataset, and the probabilities indicate high confidence in this prediction.
By incorporating these features, your API will provide more insightful information both during training and when making predictions, enhancing its utility for end-users.