Skip to content

Commit

Permalink
added model_details function
Browse files Browse the repository at this point in the history
  • Loading branch information
Kushagra1taneja committed Oct 29, 2024
1 parent 7d62f5b commit 9b00f51
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
import pandas as pd
import pickle
import os

import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
# Load the data
df = pd.read_csv('50_Startups.csv')
X = df.iloc[:, :-1].values
Expand Down Expand Up @@ -41,3 +42,38 @@
pickle.dump(ct, scaler_file)

print("Model and preprocessing objects saved successfully!")

def save_evaluation_to_pickle(train_X, train_Y, test_X, test_Y, output_file="evaluation_results.pkl"):
# Calculate R^2 score
train_r2 = r2_score(train_Y, model.predict(train_X))
test_r2 = r2_score(test_Y, y_pred)

# Create plot
fig, ax = plt.subplots(figsize=(10, 6))
ax.scatter(test_Y, y_pred, alpha=0.6, color='blue', label='Predicted')
ax.plot([test_Y.min(), test_Y.max()], [test_Y.min(), test_Y.max()], 'r--', label='Perfect Prediction')
ax.set_xlabel("Actual")
ax.set_ylabel("Predicted")
ax.set_title("Actual vs Predicted Values (Test Set)")
ax.legend()
ax.grid(True)

# Save the plot as a PNG file
plot_file = "actual_vs_predicted.png"
fig.savefig(plot_file)

# Package results
results = {
"Train_R2": train_r2,
"Test_R2": test_r2,
"plot_file": plot_file # Save the plot file path
}

# Save results to a pickle file
with open(output_file, "wb") as f:
pickle.dump(results, f)

print(f"Evaluation and plot data saved to {output_file}")
print(f"Plot saved as {plot_file}")
# Run this function once to generate the evaluation file
save_evaluation_to_pickle(X_train, y_train, X_test, y_test)
24 changes: 22 additions & 2 deletions models/business_performance_forecasting/predict.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
# import os
import os
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import pickle
from models.business_performance_forecasting.model import load_model_and_scaler # Import the function from model.py

# Define the prediction function
def get_prediction(RnD_Spend, Administration, Marketing_Spend, State):
# Load the model and scaler
# Load the model and scalers
model, scaler = load_model_and_scaler()
# Prepare input features as a NumPy array
input_data = np.array([[RnD_Spend, Administration, Marketing_Spend, State]])
Expand All @@ -18,3 +22,19 @@ def get_prediction(RnD_Spend, Administration, Marketing_Spend, State):

return prediction[0] # Return the predicted profit


class ModelEvaluation:
def __init__(self):
metrics_file= os.path.join(os.path.dirname(__file__), 'saved_models', 'evaluation_results.pkl')
# Load evaluation metrics from a pickle file
with open(metrics_file, "rb") as f:
self.metrics = pickle.load(f)
print("Loaded metrics:", self.metrics)
def evaluate(self):
metrics = self.metrics
return metrics, None, None, None

def model_details():
evaluator = ModelEvaluation()
return evaluator

Binary file not shown.
17 changes: 9 additions & 8 deletions page_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,12 @@ def render_model_details(self, model_module,tab):

# Display the scatter plot for predicted vs actual values
#used clear_figure to clear the plot once displayed to avoid conflict
st.subheader("Model Prediction Plot")
st.pyplot(prediction_plot, clear_figure=True)

st.subheader("Error Plot")
st.pyplot(error_plot, clear_figure=True)

st.subheader("Model Performance Plot")
st.pyplot(performance_plot, clear_figure=True)
if prediction_plot!=None:
st.subheader("Model Prediction Plot")
st.pyplot(prediction_plot, clear_figure=True)
if error_plot!=None:
st.subheader("Error Plot")
st.pyplot(error_plot, clear_figure=True)
if performance_plot!=None:
st.subheader("Model Performance Plot")
st.pyplot(performance_plot, clear_figure=True)

0 comments on commit 9b00f51

Please sign in to comment.