0% found this document useful (0 votes)
31 views2 pages

Iris Flower Prediction with Flask App

This document outlines a Flask web application that uses a linear regression model trained on the Iris dataset to predict petal length based on user input for sepal length, sepal width, and petal width. It includes routes for rendering a web page with a scatter plot of predictions and for handling JSON requests to return predictions. The application also manages user input validation and error handling.

Uploaded by

Anand Shilu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views2 pages

Iris Flower Prediction with Flask App

This document outlines a Flask web application that uses a linear regression model trained on the Iris dataset to predict petal length based on user input for sepal length, sepal width, and petal width. It includes routes for rendering a web page with a scatter plot of predictions and for handling JSON requests to return predictions. The application also manages user input validation and error handling.

Uploaded by

Anand Shilu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

from flask import Flask, render_template, request, jsonify

from [Link] import load_iris


from sklearn.linear_model import LinearRegression
import [Link] as plt
import seaborn as sns
import numpy as np
import io
import base64

app = Flask(__name__)

# Load dataset and train model


iris = load_iris()
X = [Link][:, :3] # sepal length, sepal width, petal width
y = [Link][:, 2] # petal length
model = LinearRegression()
[Link](X, y)
predictions = [Link](X)

@[Link]('/', methods=['GET', 'POST'])


def index():
user_prediction = None
user_point = None

if [Link] == 'POST':
try:
sl = float([Link]['sepal_length'])
sw = float([Link]['sepal_width'])
pw = float([Link]['petal_width'])

user_features = [Link]([[sl, sw, pw]])


user_prediction = [Link](user_features)[0]
user_point = (user_prediction, user_prediction) # mark on diagonal
except:
user_prediction = "Invalid input"
user_point = None

# Plot
[Link](style="whitegrid")
[Link](figsize=(8, 6))
[Link](x=y, y=predictions, label='Dataset Predictions')
[Link]("Actual Petal Length")
[Link]("Predicted Petal Length")
[Link]("Iris Linear Regression")

if user_point:
[Link](user_point[0], user_point[1], color='red', s=100, label='Your
Prediction')
[Link]()

buf = [Link]()
[Link](buf, format='png')
[Link](0)
[Link]()

img_base64 = base64.b64encode([Link]()).decode('utf-8')
img_uri = f"data:image/png;base64,{img_base64}"

return render_template('[Link]', plot_url=img_uri,


user_prediction=round(user_prediction, 2) if
isinstance(user_prediction, float) else user_prediction)

@[Link]('/predict', methods=['POST'])
def predict_api():
if not request.is_json:
return jsonify({'error': 'Request must be JSON'}), 400

data = request.get_json()
required_fields = ['sepal_length', 'sepal_width', 'petal_width']

if not all(field in data for field in required_fields):


return jsonify({'error': 'Missing required fields'}), 400

try:
sl = float(data['sepal_length'])
sw = float(data['sepal_width'])
pw = float(data['petal_width'])

input_array = [Link]([[sl, sw, pw]])


predicted = [Link](input_array)[0]

return jsonify({'predicted_petal_length': round(predicted, 2)})

except ValueError:
return jsonify({'error': 'Invalid input values'}), 400

if __name__ == '__main__':
[Link](debug=True)

You might also like