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

基于FastAPI与多项式回归的房价预测Reshape报错求助

问题排查与解决方案

核心问题分析

你的代码存在多个逻辑错误,导致reshape报错无法解决:

  1. 输入特征维度错误:fit_transform要求输入为二维数组(形状为(样本数, 特征数)),但你传入的是一维list,直接触发维度不匹配错误。
  2. 模型使用逻辑错误:在预测接口里调用model.fit完全错误——fit是训练模型的方法,预测时应该用训练好的模型调用predict;且model.fit返回的是模型本身,不是特征数据,你后续的reshape操作完全无效。
  3. 路由与函数逻辑混乱:predict函数定义不符合FastAPI规范,且错误尝试从路由函数中获取不存在的属性。

修正后的完整代码

1. 基础结构导入与模型准备(假设你已提前训练好模型)

from fastapi import FastAPI
from pydantic import BaseModel
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

app = FastAPI()

# 提前训练并加载模型(示例,实际需替换为你已训练好的模型)
model = LinearRegression()
poly = PolynomialFeatures(2)
# 此处省略训练过程,实际中应从文件加载训练好的model和poly对象

2. 修正后的请求模型与预测路由

class Features(BaseModel):
    X2_house_age: float
    X3_distance_to_the_nearest_MRT_station: float
    X4_number_of_convenience_stores: float
    year: int

@app.post("/predict")
def predict_house_price(req: Features):
    # 将单样本特征转为二维数组(1个样本,4个特征)
    input_features = [
        [req.X2_house_age,
         req.X3_distance_to_the_nearest_MRT_station,
         req.X4_number_of_convenience_stores,
         req.year]
    ]
    
    # 转换为多项式特征
    poly_features = poly.transform(input_features)
    
    # 执行预测
    prediction = model.predict(poly_features)
    
    return {"predicted_house_price": round(prediction[0], 2)}

关键修改点说明

  • 特征维度修正:将输入特征包装为二维列表[[特征1, 特征2, ...]],满足PolynomialFeatures和模型predict的输入要求(形状为(1, 4))。
  • 移除错误的fit调用:预测阶段无需重新训练模型,直接用提前训练好的模型和多项式特征转换器处理输入后预测。
  • 简化路由逻辑:将预测逻辑整合到单个路由函数中,符合FastAPI的请求处理流程,避免无效的函数间调用。
  • 规范返回格式:返回格式化的预测结果,可读性更强。

内容的提问来源于stack exchange,提问作者Hanan Zatar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:15:47