python - 即使在安装后导入 tensorflow 包也会出现错误消息
问题描述
今天是个好日子。我从互联网上得到了一个模块,这是一个关于 NMT 的模块。在模块中,我有一个 tensorflow 的导入,但不幸的是,即使在我的系统中使用 pip 安装了 tensorflow,我仍然会收到错误消息。这是错误
from tensorflow.keras.models import load_model
ModuleNotFoundError: No module named 'tensorflow'
模块 hello_app.py 如下:
from flask import Flask
from flask import request
from flask import jsonify
import uuid
import os
from tensorflow.keras.models import load_model
import numpy as np
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 = []
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:
x = np.zeros( (1,7) )
# Predict
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:
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)
请非常感谢您的回答。谢谢你。
这是我获得代码的 github 存储库 https://github.com/jeffheaton/t81_558_deep_learning/blob/master/t81_558_class_13_01_flask.ipynb
解决方案
为避免包或版本冲突,可以使用虚拟环境。
pip install virtualenv
virtualenv -p /usr/bin/python3 tf
source tf/bin/activate
tf$ pip install tensorflow
如果你有 Anaconda 或 conda
#Set Up Anaconda Environments
conda create --name tf python=3
#Activate the new Environment
source activate tf
tf$pip install tensorflow
推荐阅读
- python - Python:如何循环列表并附加到新列表
- javascript - JavaScript中的'let'和'this'有什么区别?
- amazon-web-services - 尝试运行 New-EBApplicationVersion 以更新我的弹性 beanstalk 环境时出现 URIFormatException
- android - Jetpack 导航片段生命周期不正确
- c++ - 将指针的 std::vector 复制到 std::list
- python - 如果其他行或列小部件与该列或行的大小不同(大部分较大),如何对齐/粘贴两个小部件?
- r - R CARET 预测中的 model.frame.default 错误
- c# - System.Linq.Dynamic.Core 无法比较“对象”类型
- apache-spark - 将文件导入为 RDD 与 DF 之间的区别
- sql - 如何在 SQL Server 数据库中将外键设为 NULL?