sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.svm import SVC from joblib import dump, load # Load dataset df = pd.read_csv("data/iris.csv") # Extract features (X) and labels (y) X = df[["SepalLengthCm", "SepalWidthCm", "PetalLengthCm", "PetalWidthCm"]].values y = df["Species"].values # Split into training and testing data X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20, random_state=1 )
y_train) # Make predictions on validation dataset predictions = model.predict(X_test) # Evaluate model accuracy accuracy = accuracy_score(y_test, predictions) print(f"Model Accuracy: {accuracy:.2f}") # Print accuracy score # Save model using joblib dump(model, "models/iris.joblib") # Load model using joblib model = load("models/iris.joblib")
and Matplotlib for visualizations import seaborn as sns import matplotlib.pyplot as plt # Pairplot to visualize relationships between features sns.pairplot(df, hue="Species", diag_kind="kde") plt.show()
and business logic • View (V) --> Acts as Controller in MVC, process requests and match template • Template (T) --> Presentation layer, HTML+ CSS + data
None form_data = {} # To store user inputs if request.method == "POST": try: # Store form inputs form_data = { "sepal_length": request.POST.get("sepal_length"), "sepal_width": request.POST.get("sepal_width"), "petal_length": request.POST.get("petal_length"), "petal_width": request.POST.get("petal_width"), } # Convert inputs to float and make a prediction features = np.array([[float(v) for v in form_data.values()]]) prediction = model.predict(features)[0] except Exception as e: prediction = f"Error: {str(e)}" return render( request, "predict.html", {"prediction": prediction, "form_data": form_data}
numpy as np from django.shortcuts import render from .models import IrisPrediction. # new # Load the trained model model = joblib.load("iris.joblib") def predict(request): prediction = None form_data = {} if request.method == "POST": try: ... # Save prediction to database IrisPrediction.objects.create( sepal_length=form_data["sepal_length"], sepal_width=form_data["sepal_width"], petal_length=form_data["petal_length"], petal_width=form_data["petal_width"], prediction=prediction, )
add environment variables with environs • create a .env file and update the .gitignore file • update DEBUG, ALLOWED_HOSTS, SECRET_KEY, and CSRF_TRUSTED_ORIGINS • update DATABASES to run PostgreSQL in production and install psycopg • install Gunicorn as a production WSGI server • create a Procfile • update the requirements.txt file • create a new Heroku project, push the code to it, and start a dyno web process