Я думаю, что это простая проблема, но я здесь как бы застрял. Мое основное предложение - практиковаться в API. Если вы ввели URL -адрес вручную, пожалуйста, проверьте свое правописание и попробуйте еще раз.
from numpy.lib.twodim_base import tri
import pandas as pd
import numpy as np
import flask
from tensorflow.keras.models import load_model
import joblib
import csv
import codecs
import warnings
def warn(*arg, **kwargs):
pass
warnings.warn = warn
#initialize the flask application
app = flask.Flask(__name__)
#load the pre-trained model
def define_model():
global model
model = load_model('./model/anomaly_model.h5')
return print("Model is loaded")
limit = 10
@app.route("/submit", methods=["POST"])
def submit():
#initialize the data dictionary that will be returned in the response
data_out = {}
#load the data file from our endpoint
if flask.request.method == "POST":
#read the data file
file = flask.request.files['data_file']
if not file:
return "No file submitted"
data = []
stream, = codecs.iterdecode(file.stream, 'utf-8')
for row in csv.reader(stream, dialect=csv.excel):
if row:
data.append(row)
#convert input data to pandas dataframe
df = pd.DataFrame(data)
df.set_index(df.iloc[:, 0], inplace=True)
df2 = df.drop(df.columns[0], axis=1)
df2 = df2.astype(np.float64)
#normalize the data
scaler = joblib.load('./data/combined.csv')
X = scaler.transform(df2)
X = X.reshape(X.shape[0], 1, X.shape[1])
data_out['Analysis'] = []
preds = model.predict(X)
preds = preds.reshape(preds.shape[0], preds.shape[2])
preds = pd.DataFrame(preds, columns=df2.columns)
preds.index = df2.index
scored = pd.DataFrame(index=df2.index)
yhat = X.reshape(X.shape[0], X.reshape[2])
scored['Loss_mae'] = np.mean(np.abs(yhat - preds), axis=1)
scored['Threshold'] = limit
scored['Anomaly'] = scored['Loss_mae'] > scored['threshold']
print(scored)
#determine of an anomaly was detected
triggered = []
for i in range(len(scored)):
temp = scored.iloc[i]
if temp.iloc[2]:
triggered.append(temp)
print(len(triggered))
if len(triggered) > 0:
for j in range(len(triggered)):
out = triggered[j]
result = {"Anomaly": True, "Value":out[0], "filename":out.name}
data_out["Analysis"].append(result)
else:
result = {"Anomaly":"No Anomalies Detected"}
data_out["Analysis"].append(result)
print(data_out)
return flask.jsonify(data_out)
if __name__ == "__main__":
print(("* Loading the Keras model and starting the server ...."
"Please wait until the server has fully started before submitting"))
define_model()
app.run(debug=True)
< /code>
На самом деле я новичок в колбе.
Это моя первая попытка. Я также пытался дать app.run (host = '0,0.0.0'), но не работал для меня. Могу ли я получить помощь ??? < /p>
Это журнал от терминала: < /p>
* Loading the Keras model and starting the server ....Please wait until the server has fully started before submitting
2021-12-27 16:29:45.158086: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Model is loaded
* Serving Flask app 'implementation' (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: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Loading the Keras model and starting the server ....Please wait until the server has fully started before submitting
2021-12-27 16:29:49.283527: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Model is loaded
Model is loaded
* Debugger is active!
* Debugger PIN: 114-980-010
127.0.0.1 - - [27/Dec/2021 16:05:37] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [27/Dec/2021 16:05:38] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [27/Dec/2021 16:05:53] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [27/Dec/2021 16:05:56] "GET / HTTP/1.1" 404 -
Я думаю, что это простая проблема, но я здесь как бы застрял. Мое основное предложение - практиковаться в API. Если вы ввели URL -адрес вручную, пожалуйста, проверьте свое правописание и попробуйте еще раз.[code]from numpy.lib.twodim_base import tri import pandas as pd import numpy as np import flask from tensorflow.keras.models import load_model import joblib import csv import codecs import warnings
def warn(*arg, **kwargs): pass
warnings.warn = warn
#initialize the flask application
app = flask.Flask(__name__)
#load the pre-trained model
def define_model(): global model model = load_model('./model/anomaly_model.h5') return print("Model is loaded")
limit = 10
@app.route("/submit", methods=["POST"])
def submit(): #initialize the data dictionary that will be returned in the response data_out = {} #load the data file from our endpoint if flask.request.method == "POST": #read the data file file = flask.request.files['data_file'] if not file: return "No file submitted" data = [] stream, = codecs.iterdecode(file.stream, 'utf-8') for row in csv.reader(stream, dialect=csv.excel): if row: data.append(row)
triggered = [] for i in range(len(scored)): temp = scored.iloc[i] if temp.iloc[2]: triggered.append(temp) print(len(triggered)) if len(triggered) > 0: for j in range(len(triggered)): out = triggered[j] result = {"Anomaly": True, "Value":out[0], "filename":out.name} data_out["Analysis"].append(result) else: result = {"Anomaly":"No Anomalies Detected"} data_out["Analysis"].append(result) print(data_out)
return flask.jsonify(data_out)
if __name__ == "__main__": print(("* Loading the Keras model and starting the server ...." "Please wait until the server has fully started before submitting")) define_model() app.run(debug=True) < /code> На самом деле я новичок в колбе. Это моя первая попытка. Я также пытался дать app.run (host = '0,0.0.0'), но не работал для меня. Могу ли я получить помощь ??? < /p> Это журнал от терминала: < /p> * Loading the Keras model and starting the server ....Please wait until the server has fully started before submitting 2021-12-27 16:29:45.158086: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. Model is loaded * Serving Flask app 'implementation' (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: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Loading the Keras model and starting the server ....Please wait until the server has fully started before submitting 2021-12-27 16:29:49.283527: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. Model is loaded Model is loaded * Debugger is active! * Debugger PIN: 114-980-010 127.0.0.1 - - [27/Dec/2021 16:05:37] "GET / HTTP/1.1" 404 - 127.0.0.1 - - [27/Dec/2021 16:05:38] "GET / HTTP/1.1" 404 - 127.0.0.1 - - [27/Dec/2021 16:05:53] "GET / HTTP/1.1" 404 - 127.0.0.1 - - [27/Dec/2021 16:05:56] "GET / HTTP/1.1" 404 - [/code] В надежде на помощь Спасибо
Я думаю, что это простая проблема, но я здесь застрял.
Я пытаюсь развернуть модель keras во Flask. Мое главное предложение — попрактиковаться в API.
Но я получаю эту ошибку постоянно всякий раз, когда пытаюсь открыть заданный локальный идентификатор...
При вызове URL-адреса с помощью launchUrl первые один или два раза происходит переход на правильный URL-адрес, но после этого он застревает на определенном URL-адресе. Ниже приведен код, который я использовал.
String getReportUrl() {
final String...