本文介绍了OSError: SavedModel 文件不存在于:../dnn/mpg_model.h5/{saved_model.pbtxt|saved_model.pb}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

**

代码编辑器:vscode

cmd:anaconda 提示符

我遵循了教程,但为什么会出现此错误?**

第一个错误是 ModuleNotFoundError: No module named 'tensorflow'但我制作了 env 并安装了它第二个错误是 ModuleNotFoundError: No module named 'flask'但我制作了 env 并安装了它我修复了它们,它们在 python 上工作我该如何解决这个问题?

# T81-558:深度神经网络的应用# 模块 13:高级/其他主题# 讲师:[Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/默认.aspx)# 有关更多信息,请访问 [类网站](https://sites.wustl.edu/jeffheaton/t81-558/).# 仅使用 Flask 部署简单的 Keras 表格模型.从烧瓶导入烧瓶,请求,jsonify导入 uuid导入操作系统从 tensorflow.keras.models 导入 load_model将 numpy 导入为 npapp = Flask(__name__)# 用于验证预期 = {气缸":{最小":3,最大":8},"位移":{"min":68.0,"max":455.0},"马力":{"min":46.0,"max":230.0},重量":{分钟":1613,最大":5140},"加速度":{"min":8.0,"max":24.8},年":{分钟":70,最大":82},"原点":{"min":1,"max":3}}# Flask 启动时加载神经网络模型 = load_model(os.path.join("../dnn/","mpg_model.h5"))@app.route('/api/mpg', methods=['POST'])def calc_mpg():内容 = request.json错误 = []# 检查有效的输入字段对于内容中的名称:如果名称在预期中:expected_min = EXPECTED[name]['min']expected_max = EXPECTED[name]['max']值 = 内容[名称]如果值预期最大:errors.append(f"Out of bounds: {name}, has value of: {value},但应该在 {expected_min} 和 {expected_max} 之间.")别的:errors.append(f"Unexpected field: {name}.")# 检查缺少的输入字段对于预期中的名称:如果名称不在内容中:errors.append(f"缺失值:{name}.")如果 len(errors) 
#conda(tf-gpu) (HelloWold) C:\Users\ASUS\t81_558_deep_learning\py>python mpg_server_1.py2020-05-09 17:25:38.498181: 我tensorflow/stream_executor/platform/default/dso_loader.cc:44] 成功打开动态库cudart64_101.dll回溯(最近一次调用最后一次): 中的文件mpg_server_1.py",第 26 行模型 = load_model(os.path.join("../dnn/","mpg_model.h5"))文件C:\Users\ASUS\Envs\HelloWold\lib\site-packages\tensorflow\python\keras\saving\save.py",第 189 行,在 load_modelloader_impl.parse_saved_model(文件路径)文件C:\Users\ASUS\Envs\HelloWold\lib\site-packages\tensorflow\python\saved_model\loader_impl.py",第 113 行,在 parse_saved_model常量.SAVED_MODEL_FILENAME_PB))OSError: SavedModel 文件不存在于:../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"ipynbhttps://www.youtube.com/watch?v=H73m9XvKHug&t=1056s

解决方案

发生错误是因为您的代码正在尝试加载不存在的模型.从您链接的 Notebook 文件中,您很可能必须运行以下命令:

from werkzeug.wrappers import Request, Response从烧瓶进口烧瓶app = Flask(__name__)@app.route("/")定义你好():返回世界你好!"如果 __name__ == '__main__':从 werkzeug.serving 导入 run_simple运行_简单('本地主机',9000,应用程序)从 tensorflow.keras.models 导入顺序从 tensorflow.keras.layers 导入密集,激活从 sklearn.model_selection 导入 train_test_split从 tensorflow.keras.callbacks 导入 EarlyStopping将熊猫导入为 pd导入 io导入操作系统进口请求将 numpy 导入为 np从 sklearn 导入指标df = pd.read_csv("https://data.heatonresearch.com/data/t81-558/auto-mpg.csv",na_values=['NA', '?'])汽车 = df['name']# 处理缺失值df['horsepower'] = df['horsepower'].fillna(df['horsepower'].median())# Pandas 到 Numpyx = df[['汽缸','排量','马力','重量','加速度'、'年份'、'起源']].valuesy = df['mpg'].values # 回归# 分成验证集和训练集x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=42)# 构建神经网络模型 = 顺序()model.add(Dense(25, input_dim=x.shape[1], activation='relu')) # 隐藏 1model.add(Dense(10, activation='relu')) # 隐藏 2model.add(Dense(1)) # 输出model.compile(loss='mean_squared_error', 优化器='adam')monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, 耐心=5,verbose=1, mode='auto',restore_best_weights=真)model.fit(x_train,y_train,validation_data=(x_test,y_test),callbacks=[monitor],verbose=2,epochs=1000)预测 = 模型.预测(x_test)# 测量 RMSE 误差.RMSE 对于回归很常见.分数 = np.sqrt(metrics.mean_squared_error(pred,y_test))打印(f加载后分数(RMSE):{分数}")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"))

**

code editor: vscode

cmd: anaconda prompt

I followed the tutorial but why this error?**

# 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}
解决方案

The error occurs because your code is trying to load a model that does not exist. From the Notebook file you linked, you will most likely have to run the following:

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"))

This will train and save the model that your code is loading.

It also looks like you have a small typo on the line: model = load_model(os.path.join("../dnn/","mpg_model.h5")) which should be changed to model = load_model(os.path.join("./dnn/","mpg_model.h5"))

这篇关于OSError: SavedModel 文件不存在于:../dnn/mpg_model.h5/{saved_model.pbtxt|saved_model.pb}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 17:41