Shrishti Jain
Shrishti Jain

Reputation: 23

Result not being displayed for machine learning prediction on the webpage

I am working on Malicious Webpage Detection using logistic regression and have used a dataset from kaggle. Using flask and html i want to predict whether the url is good or bad.

this is the code snippet in app.py

if request.method=='POST':
        comment=request.form['comment']
        X_predict1=[comment]
        predict1 = vectorizer.transform(X_predict1)
        New_predict1 = logit.predict(predict1)
        new = New_predict1.tolist()
        new1 = " ".join(str(x) for x in new)
    return render_template('result.html',prediction=new1)

this code i have written in result.html

{% if prediction == 1%}

 <h2 style="color:red;">Bad</h2>
 {% elif prediction == 0%}
 <h2 style="color:blue;">Good</h2>
 {% endif %}

Why the results (Bad/Good) are not being displayed for this code?

Upvotes: 1

Views: 299

Answers (1)

arshovon
arshovon

Reputation: 13661

I assume in app.py:

  • New_predict1.tolist() returns a list.
  • " ".join(str(x) for x in new) returns a concatenated string value.

In result.html:

  • prediction == 1 or prediction == 0 compares the value of prediction to integer. But from app.py you are sending a concatenated string value. So, this Bad or Good will not be shown in template.
  • You need to use String comparison like: prediction == "some constant"

I reproduced your scenario:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods = ['GET', 'POST'])
def home():
    if request.method == "POST":
        comment=request.form.get('comment')
        X_predict1=[comment]
        # Do some operations
        #predict1 = vectorizer.transform(X_predict1)
        #New_predict1 = logit.predict(predict1)
        #new = New_predict1.tolist()
        #new1 = " ".join(str(x) for x in new)

        # Dummy list
        new = [1, 2, 3]
        # " ".join() returns a string
        new1 = " ".join(str(x) for x in new)
        return render_template('result.html', prediction=new1)
    return render_template('result.html')

if __name__ == "__main__":
    app.run(debug=True)

result.html:

<html>
<head>
    <title>Home</title>
</head>
<body>
    <form action="/" method="post">
        Comment:
        <input type="text" name="comment"/>
        <input type="submit" value="Submit">
    </form>

    <h3>Prediction Result</h3>
    {% if prediction == 1 %}
    <h2 style="color:red;">Bad</h2>
    {% elif prediction == 0 %}
    <h2 style="color:blue;">Good</h2>
    {% else %}
    <h2 style="color:black;">{{prediction}}</h2>
    {% endif %}
</body>
</html>

Output:

reproduced OP's scenario

As you can see the else block is triggered in the template as both if and elif block is skipped.

Upvotes: 1

Related Questions