Visual Studio中tensorflow.keras报错:Pylance提示keras非已知成员
解决Pylance报错:"keras" is not a known member of module "tensorflow"
问题情况
我已经通过pip成功安装了tensorflow和keras,但在Visual Studio中运行代码时,出现报错:
"keras" is not a known member of module "tensorflow" Pylance (reportAttributeAccessIssue)
我的代码如下:
from flask import Flask, request, jsonify from PIL import Image import numpy as np import tensorflow as tf import os # Initialize Flask application app = Flask(__name__) # Load the trained model model = tf.keras.models.load_model("trained_model.h5") # Define route for model prediction @app.route("/predict", methods=["POST"]) def predict(): # Check if request contains file data if "file" not in request.files: return jsonify({"error": "No file provided"}), 400 # Get the file from the request file = request.files["file"] # Save the file to a temporary location temp_image_path = "temp_image.jpg" file.save(temp_image_path) # Preprocess the image img = Image.open(temp_image_path) img = img.resize((180, 180)) # Resize image to match model input size img = np.array(img) / 255.0 # Normalize pixel values img = np.expand_dims(img, axis=0) # Add batch dimension # Make prediction prediction = model.predict(img) # Remove temporary image file os.remove(temp_image_path) # Return prediction result return jsonify({"prediction": int(np.argmax(prediction))}), 200 # Run the Flask app if __name__ == "__main__": app.run(debug=True)
解决方法
调整导入方式
直接导入keras模块,替换tf.keras的写法:
先添加导入语句:import keras然后把加载模型的代码改成:
model = keras.models.load_model("trained_model.h5")这样能避开Pylance对tensorflow子模块的识别问题。
更新TensorFlow和Pylance版本
- 升级TensorFlow到最新稳定版:
pip install --upgrade tensorflow - 在VS Code扩展市场搜索Pylance,点击更新按钮,确保使用最新版本的Pylance。新版本对TensorFlow内部模块的识别更准确。
- 升级TensorFlow到最新稳定版:
添加类型忽略注释
不想修改代码结构的话,直接在报错行加注释让Pylance跳过检查:model = tf.keras.models.load_model("trained_model.h5") # type: ignore检查Python解释器环境
确认VS Code使用的是安装了TensorFlow的那个解释器:- 按
Ctrl+Shift+P(Windows/Linux)或Cmd+Shift+P(Mac),输入Python: Select Interpreter。 - 选择之前安装TensorFlow的虚拟环境或全局环境,避免因解释器不匹配导致Pylance识别不到模块。
- 按
内容的提问来源于stack exchange,提问作者DEVINENI MANI MANVITH
相关产品推荐
相关产品推荐

