基于FastAPI与多项式回归的房价预测Reshape报错求助
问题排查与解决方案
核心问题分析
你的代码存在多个逻辑错误,导致reshape报错无法解决:
- 输入特征维度错误:
fit_transform要求输入为二维数组(形状为(样本数, 特征数)),但你传入的是一维list,直接触发维度不匹配错误。 - 模型使用逻辑错误:在预测接口里调用
model.fit完全错误——fit是训练模型的方法,预测时应该用训练好的模型调用predict;且model.fit返回的是模型本身,不是特征数据,你后续的reshape操作完全无效。 - 路由与函数逻辑混乱:
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
相关产品推荐
相关产品推荐

