You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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版本

    1. 升级TensorFlow到最新稳定版:
      pip install --upgrade tensorflow
      
    2. 在VS Code扩展市场搜索Pylance,点击更新按钮,确保使用最新版本的Pylance。新版本对TensorFlow内部模块的识别更准确。
  • 添加类型忽略注释
    不想修改代码结构的话,直接在报错行加注释让Pylance跳过检查:

    model = tf.keras.models.load_model("trained_model.h5")  # type: ignore
    
  • 检查Python解释器环境
    确认VS Code使用的是安装了TensorFlow的那个解释器:

    1. 按Ctrl+Shift+P(Windows/Linux)或Cmd+Shift+P(Mac),输入Python: Select Interpreter。
    2. 选择之前安装TensorFlow的虚拟环境或全局环境,避免因解释器不匹配导致Pylance识别不到模块。

内容的提问来源于stack exchange,提问作者DEVINENI MANI MANVITH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 19:52:41