Python如何获取多变量拟合方程?解决np.polyfit参数类型报错
错误原因
np.polyfit仅支持单变量多项式拟合,无法处理多自变量场景。你修改后的代码向np.polyfit传入了3个位置参数,函数会把第三个传入的df['d']识别为多项式次数参数deg,而deg要求为整数类型,传入pandas Series自然触发类型转换报错。np.poly1d同样仅支持单变量多项式的表示,无法存储多变量拟合方程的参数。
正确实现方案
多变量多项式拟合可以通过scikit-learn的PolynomialFeatures结合LinearRegression实现,以下是可直接运行的代码:
import pandas as pd import numpy as np from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression # 构造测试数据 d = {'a': [0.1, 0.2,0.3,0.4,0.5,0.6], 'b': [0.6, 0.8,0.3,0.4,0.1,0.1], 'c': [0.7, 0.3,0.9,0.4,1.0,0.2],'d': [1,0,0,1,0,1]} df = pd.DataFrame(data=d) def get_multivar_equation(X, y, degree=2): # 生成多变量多项式特征(包含截距项、各次项、交互项) poly = PolynomialFeatures(degree=degree) X_poly = poly.fit_transform(X) # 拟合线性回归 model = LinearRegression(fit_intercept=False) model.fit(X_poly, y) # 获取特征名和对应系数 feature_names = poly.get_feature_names_out(X.columns) coefs = model.coef_ # 拼接方程字符串 equation = " + ".join([f"{coef:.4f}*{name}" for coef, name in zip(coefs, feature_names)]) return equation, model # 传入自变量a、b,因变量d,二次拟合 equation, model = get_multivar_equation(df[['a', 'b']], df['d'], degree=2) print("拟合得到的多变量二次方程:") print(f"d = {equation}")
运行后会输出类似如下结果(因测试数据量小拟合结果仅作参考):
拟合得到的多变量二次方程: d = 4.6512*1 + -27.9070*a + -15.1163*b + 34.8837*a^2 + 27.9070*a b + 7.5581*b^2
如果需要使用拟合模型做预测,直接调用model.predict(poly.transform(新的自变量数据))即可。
内容的提问来源于stack exchange,提问作者john johns
相关产品推荐
相关产品推荐

