gpt4 book ai didi

python - OSError : SavedModel file does not exist at: . ./dnn/mpg_model.h5/{saved_model.pbtxt|saved_model.pb}

转载 作者:行者123 更新时间:2023-12-04 10:03:37 28 4
gpt4 key购买 nike

**

代码编辑器:vscode

cmd:anaconda 提示符

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

first error was ModuleNotFoundError: No module named 'tensorflow' but i make env and install it second error was ModuleNotFoundError: No module named 'flask' but i make env and install it i fix them and they work on python How can I solve this?


# 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}

from 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

最佳答案

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

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

关于python - OSError : SavedModel file does not exist at: . ./dnn/mpg_model.h5/{saved_model.pbtxt|saved_model.pb},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61699140/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com