OSError: файл SavedModel не существует по адресу: ../dnn/mpg_model.h5/{saved_model.pbtxt|saved_model.pb} - PullRequest
0 голосов
/ 09 мая 2020

**

редактор кода: vscode

cmd: подсказка anaconda

Я выполнил руководство, но почему эта ошибка? **

первая ошибка была ModuleNotFoundError: нет модуля с именем «tensorflow», но я делаю env и устанавливаю его вторая ошибка: ModuleNotFoundError: нет модуля с именем «flask», но я делаю env и устанавливаю его. исправьте их, и они работают на python Как я могу это решить?

# T81-558: Applications of Deep Neural Networks
# Module 13: Advanced/Other Topics
# Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)
# For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/).
# Deploy simple Keras tabular model with Flask only.
from flask import Flask, request, jsonify
import uuid
import os
from tensorflow.keras.models import load_model
import numpy as np

app = Flask(__name__)

# Used for validation
EXPECTED = {
  "cylinders":{"min":3,"max":8},
  "displacement":{"min":68.0,"max":455.0},
  "horsepower":{"min":46.0,"max":230.0},
  "weight":{"min":1613,"max":5140},
  "acceleration":{"min":8.0,"max":24.8},
  "year":{"min":70,"max":82},
  "origin":{"min":1,"max":3}
}

# Load neural network when Flask boots up
model = load_model(os.path.join("../dnn/","mpg_model.h5"))

@app.route('/api/mpg', methods=['POST'])
def calc_mpg():
    content = request.json
    errors = []

    # Check for valid input fields 
    for name in content:
      if name in EXPECTED:
        expected_min = EXPECTED[name]['min']
        expected_max = EXPECTED[name]['max']
        value = content[name]
        if value < expected_min or value > expected_max:
          errors.append(f"Out of bounds: {name}, has value of: {value}, but should be between {expected_min} and {expected_max}.")
      else:
        errors.append(f"Unexpected field: {name}.")

    # Check for missing input fields
    for name in EXPECTED:
      if name not in content:
        errors.append(f"Missing value: {name}.")

    if len(errors) <1:
      # Predict
      x = np.zeros( (1,7) )

      x[0,0] = content['cylinders']
      x[0,1] = content['displacement'] 
      x[0,2] = content['horsepower']
      x[0,3] = content['weight']
      x[0,4] = content['acceleration'] 
      x[0,5] = content['year']
      x[0,6] = content['origin']

      pred = model.predict(x)
      mpg = float(pred[0])
      response = {"id":str(uuid.uuid4()),"mpg":mpg,"errors":errors}
    else:
      # Return errors
      response = {"id":str(uuid.uuid4()),"errors":errors}


    print(content['displacement'])

    return jsonify(response)

if __name__ == '__main__':
    app.run(host= '0.0.0.0',debug=True)
#conda
(tf-gpu) (HelloWold) C:\Users\ASUS\t81_558_deep_learning\py>python mpg_server_1.py
2020-05-09 17:25:38.498181: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_101.dll
Traceback (most recent call last):
  File "mpg_server_1.py", line 26, in <module>
    model = load_model(os.path.join("../dnn/","mpg_model.h5"))
  File "C:\Users\ASUS\Envs\HelloWold\lib\site-packages\tensorflow\python\keras\saving\save.py", line 189, in load_model
    loader_impl.parse_saved_model(filepath)
  File "C:\Users\ASUS\Envs\HelloWold\lib\site-packages\tensorflow\python\saved_model\loader_impl.py", line 113, in parse_saved_model
    constants.SAVED_MODEL_FILENAME_PB))
OSError: SavedModel file does not exist at: ../dnn/mpg_model.h5/{saved_model.pbtxt|saved_model.pb}

от https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_13_01_flask.ipynb https://www.youtube.com/watch?v=H73m9XvKHug&t=1056s

1 Ответ

0 голосов
/ 09 мая 2020

Ошибка возникает из-за того, что ваш код пытается загрузить несуществующую модель. Из файла записной книжки, который вы связали, вам, скорее всего, придется запустить следующее:

from werkzeug.wrappers import Request, Response
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 9000, app)

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
from sklearn.model_selection import train_test_split
from tensorflow.keras.callbacks import EarlyStopping
import pandas as pd
import io
import os
import requests
import numpy as np
from sklearn import metrics

df = pd.read_csv(
    "https://data.heatonresearch.com/data/t81-558/auto-mpg.csv", 
    na_values=['NA', '?'])

cars = df['name']

# Handle missing value
df['horsepower'] = df['horsepower'].fillna(df['horsepower'].median())

# Pandas to Numpy
x = df[['cylinders', 'displacement', 'horsepower', 'weight',
       'acceleration', 'year', 'origin']].values
y = df['mpg'].values # regression

# Split into validation and training sets
x_train, x_test, y_train, y_test = train_test_split(    
    x, y, test_size=0.25, random_state=42)

# Build the neural network
model = Sequential()
model.add(Dense(25, input_dim=x.shape[1], activation='relu')) # Hidden 1
model.add(Dense(10, activation='relu')) # Hidden 2
model.add(Dense(1)) # Output
model.compile(loss='mean_squared_error', optimizer='adam')

monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=5, verbose=1, mode='auto',
        restore_best_weights=True)
model.fit(x_train,y_train,validation_data=(x_test,y_test),callbacks=[monitor],verbose=2,epochs=1000)

pred = model.predict(x_test)
# Measure RMSE error.  RMSE is common for regression.
score = np.sqrt(metrics.mean_squared_error(pred,y_test))
print(f"After load score (RMSE): {score}")

model.save(os.path.join("./dnn/","mpg_model.h5"))

Это обучит и сохранит модель, которую загружает ваш код.

Также похоже, что вы есть небольшая опечатка в строке: model = load_model(os.path.join("../dnn/","mpg_model.h5")), которую следует заменить на model = load_model(os.path.join("./dnn/","mpg_model.h5"))

...