在烧瓶中提交回归模型的值后,在运行时出现错误

时间:2020-05-28 13:38:00

标签: python flask keras regression artificial-intelligence

错误:

   Traceback (most recent call last):
  File "D:\Anaconda\lib\site-packages\flask\app.py", line 2463, in __call__
    return self.wsgi_app(environ, start_response)
  File "D:\Anaconda\lib\site-packages\flask\app.py", line 2449, in wsgi_app
    response = self.handle_exception(e)
  File "D:\Anaconda\lib\site-packages\flask\app.py", line 1866, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Anaconda\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "D:\Anaconda\lib\site-packages\flask\app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\Anaconda\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "D:\Anaconda\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Anaconda\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "D:\Anaconda\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "D:\Anaconda\lib\site-packages\flask\app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:\Flask\app.py", line 30, in login
    ypred = model.predict(np.array(total))
  File "D:\Anaconda\lib\site-packages\keras\engine\training.py", line 1462, in predict
    callbacks=callbacks)
  File "D:\Anaconda\lib\site-packages\keras\engine\training_arrays.py", line 324, in predict_loop
    batch_outs = f(ins_batch)
  File "D:\Anaconda\lib\site-packages\tensorflow\python\keras\backend.py", line 3292, in __call__
    run_metadata=self.run_metadata)
  File "D:\Anaconda\lib\site-packages\tensorflow\python\client\session.py", line 1458, in __call__
    run_metadata_ptr)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable dense_3/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/dense_3/bias)
     [[{{node dense_3/BiasAdd/ReadVariableOp}}]]

app.py文件

 from flask import Flask,request,render_template
from keras.models import load_model
import numpy as np
global model, graph
import tensorflow as tf
graph =  tf.get_default_graph()

model = load_model('regressor.h5')

app = Flask(__name__)

@app.route('/')#when even the browser finds localhost:5000 then
def home():#excecute this function
    return render_template('index.html')#this function is returing the index.html file
@app.route('/login', methods =['POST']) #when you click submit on html page it is redirection to this url
def login():#as soon as this url is redirected then call the below functionality
    a = request.form['a']
    b = request.form['b']
    c = request.form['c']
    d = request.form['s']
    if (d == "newyork"):
        s1,s2,s3 = 0,0,1
    if (d == "florida"):
        s1,s2,s3 = 0,1,0
    if (d == "california"):
        s1,s2,s3 = 1,0,0

    total = [[s1,s2,s3,a,b,c]]
    with graph.as_default():
        ypred = model.predict(np.array(total))
        y = ypred[0][0]
        print(ypred)

    # from html page what ever the text is typed  that is requested from the form functionality and is stored in a name variable
    return render_template('index.html' ,abc = y)#after typing the name show this name on index.html file where we have created a varibale abc


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

html文件:

<html>
<body>
<form action = "http://localhost:5000/login" method = "post">
<p>enter marketing speed amount</p>
<p> <input type = "text" name = "a" /></p>
<p>enter Administartive amount</p>
<p> <input type = "text" name = "b" /></p>
<p>enter R and d amount</p>
<p> <input type = "text" name = "c" /></p>
<select name = 's'>
<option value = "newyork"> newyork </option>

<option value = "florida"> florida </option>
<option value = "california"> california </option>
</select>

<p> <input  type = "submit" value = "submit"/></p>
</form>
<b>{{abc}}</b>
</body>
</html>

回归文件:

import numpy as np
import pandas as pd
import sklearn
import keras
data=pd.read_csv(r"C:\Users\anil\Anaconda3\50_Startups.csv")
from sklearn.preprocessing import LabelEncoder
le=LabelEncoder()
x=data.iloc[:,:4].values
y=data.iloc[:,-1:].values
x[:,3]=le.fit_transform(x[:,3])

from sklearn.preprocessing import OneHotEncoder
one=OneHotEncoder()
z=one.fit_transform(x[:,3:]).toarray()
x=np.delete(x,3,axis=1)
x=np.concatenate((z,x),axis=1)
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)
from sklearn.preprocessing import StandardScaler
sc=StandardScaler()
x_train=sc.fit_transform(x_train)
x_test=sc.transform(x_test)
from keras.models import Sequential
from keras.layers import Dense
regressor=Sequential()
regressor.add(Dense(units=6,init="random_uniform",activation="relu"))
regressor.add(Dense(units=7,init="random_uniform",activation="relu"))
regressor.add(Dense(units=8,init="random_uniform",activation="relu"))
regressor.add(Dense(units=9,init="random_uniform",activation="relu"))
regressor.add(Dense(units=9,init="random_uniform",activation="relu"))
regressor.add(Dense(units=9,init="random_uniform",activation="relu"))
regressor.add(Dense(units=9,init="random_uniform",activation="relu"))
regressor.add(Dense(units=9,init="random_uniform",activation="relu"))
regressor.add(Dense(units=9,init="random_uniform",activation="relu"))
regressor.add(Dense(units=9,init="random_uniform",activation="relu"))

regressor.add(Dense(units=1,init="random_uniform"))
regressor.compile(optimizer='adam',loss='mse',metrics=['mse'])
regressor.fit(x_train,y_train,batch_size=10,epochs=170)
y_pred = regressor.predict(x_test)
print(y_pred)
import matplotlib.pyplot as plt
plt.plot(y_pred,color='red')
plt.plot(y_test,color='blue')
from sklearn.metrics import r2_score
accuracy = r2_score(y_test,y_pred)
print(accuracy)
regressor.save('regressor.h5')

请帮助,我似乎不了解该错误。 数据来自名为50_Startups.csv的csv文件 我是烧瓶新手。 该模型经过培训,可以通过研究以下输入来预测初创公司的利润: 状态,市场支出,研发支出,行政支出。

0 个答案:

没有答案