该模型由2个特征(经度和纬度)组成,并执行单标签回归。
当我在网上输入经度和纬度的值并单击“预测”按钮时,就会出现间隔服务器错误。
Python version: 3.6.9
Flask version: 1.1.2
Code:
"""
Initialize the server by creating Flask class object
Name the app as app
"""
app = Flask(__name__)
# Load the ML model as pickle file
file = open('regr.pkl', 'rb')
model = load(file)
# Run web-app on a VM
run_with_ngrok(app)
# Define web pages using decorator
@app.route('/')
def home():
return render_template('index.html')
# Decorator to use the 'Predict' button in our web-app
@app.route('/predict', methods=['POST'])
def predict():
"""
An inference app named 'predict' that
renders results on HTML GUI and
retrieves values from the form with
function parameters specified as float datatype
"""
init_features = [float(x) for x in request.form.values()]
final_features = [array(init_features)]
print(len(final_features))
# Make prediction
prediction = model.predict(final_features)
output = round(prediction[0], 2)
return render_template('index.html', prediction_text=f'The Midpoint of X could be: {output}')
if __name__ == '__main__':
app.run()
HTML:
%%writefile templates/index.html
<!doctype html>
<html lang="en" style="width: 100%; height: 100%; overflow: hidden;">
<head>
<meta charset="utf-8">
<title>MPX Predictor</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="A Scikit-Learn-based ML model that predicts the midpoint of X">
<!-- Render correctly on mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, shrink-to-fit=no">
<!-- Add to homescreen for Chrome on Android -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="application-name" content="MPX Predictor">
<meta name="theme-color" content="#303F9F">
<!-- Add to homescreen for Safari on iOS -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="MPX Predictor">
<meta name="apple-mobile-web-app-status-bar-style" content="#303F9F">
<!-- Tile icon for Win8 -->
<meta name="msapplication-TileColor" content="#3372DF">
<meta name="msapplication-navbutton-color" content="#303F9F">
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-135532366-1"></script>
<script>function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[], gtag("js", new Date), gtag("config", "UA-135532366-1");</script>
<!-- Web Application Manifest -->
<link rel="manifest" href='data:application/manifest+json, { "name": "MPX Predictor", "short_name": "MPX Predictor", "display": "standalone" }' media="screen />
<!-- Master CSS and JS -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons", media="screen">
<link rel="stylesheet" type="text/css" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css" media="screen">
<script type="text/javascript" defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>
</head>
<body>
<!-- Fixed header -->
<div style="margin: 40px;" class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header mdl-color-text--white mdl-color--indigo-700">
<!-- Grid -->
<div class="mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-grid">
<div class="mdl-layout__header-row mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--12-col-desktop"">
<h3> MPX Predictor </h3>
</div>
</div>
</header>
<h4> Predict the Midpoint of X </h4>
<h5> Enter the following values to predict the Midpoint of X </h5>
<!-- Numeric textfields with floating label -->
<form action="{{ url_for('predict')}}" method="post">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" style="height: 25px;" name="X1" id="long" required="required" pattern="-?[0-9]*(\.[0-9]+)?">
<label class="mdl-textfield__label" for="long">Longitude</label>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" style="height: 25px;" name="X1" id="lat" required="required" pattern="-?[0-9]*(\.[0-9]+)?">
<label class="mdl-textfield__label" for="lat">Latitude</label>
</div>
<!-- Accent-colored raised button with ripple -->
<button type="submit" style="margin: 15px;" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Predict</button>
</form>
<br>
<br>
{{ prediction_text }}
</div>
</body>
</html>
Complete traceback:
* Serving Flask app "__main__" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Running on http://9becd2f4e911.ngrok.io
* Traffic stats available on http://127.0.0.1:4040
127.0.0.1 - - [22/Oct/2020 19:28:12] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [22/Oct/2020 19:28:13] "GET /favicon.ico HTTP/1.1" 404 -
[2020-10-22 19:28:18,533] ERROR in app: Exception on /predict [POST]
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.6/dist-packages/flask/_compat.py", line 39, in reraise
raise value
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "<ipython-input-22-28ae2839ef41>", line 37, in predict
prediction = model.predict(final_features)
File "/usr/local/lib/python3.6/dist-packages/sklearn/utils/metaestimators.py", line 116, in <lambda>
out = lambda *args, **kwargs: self.fn(obj, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/sklearn/pipeline.py", line 419, in predict
Xt = transform.transform(Xt)
File "/usr/local/lib/python3.6/dist-packages/tpot/builtins/stacking_estimator.py", line 93, in transform
X_transformed = np.hstack((np.reshape(self.estimator.predict(X), (-1, 1)), X_transformed))
File "/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/_base.py", line 225, in predict
return self._decision_function(X)
File "/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/_base.py", line 209, in _decision_function
dense_output=True) + self.intercept_
File "/usr/local/lib/python3.6/dist-packages/sklearn/utils/extmath.py", line 151, in safe_sparse_dot
ret = a @ b
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 1)
127.0.0.1 - - [22/Oct/2020 19:28:18] "POST /predict HTTP/1.1" 500 -
链接到Colab笔记本:https://colab.research.google.com/drive/1jVRhIZEV8rjdsQFPvWJof9R7wJcdF-cd?usp=sharing
final_features
的长度为1,而拟合特征的数量应为2,这会导致错误。如何将两个功能都提供给预测功能?