如何修改Python多元线性回归代码批量输出多组预测值
修改后可实现5组预测的完整代码
import pandas as pd from sklearn import linear_model import statsmodels.api as sm Stock_Market = {'Year': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016], 'Month': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1], 'Interest_Rate': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75], 'Unemployment_Rate': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1], 'Stock_Index_Price': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719] } df = pd.DataFrame(Stock_Market,columns=['Year','Month','Interest_Rate','Unemployment_Rate','Stock_Index_Price']) X = df[['Interest_Rate','Unemployment_Rate']] Y = df['Stock_Index_Price'] # sklearn模型训练 regr = linear_model.LinearRegression() regr.fit(X, Y) print('Intercept: \n', regr.intercept_) print('Coefficients: \n', regr.coef_) # -------------------修改的预测部分开始------------------- # 输入5组自变量 new_interest_rates = [2.75, 3, 4, 1, 2] new_unemployment_rates = [5.3, 4, 3, 2, 1] # 拼接为符合输入要求的二维数组,每行对应一组预测数据 new_X = [[i, u] for i, u in zip(new_interest_rates, new_unemployment_rates)] # 输出5组预测结果 predicted_prices = regr.predict(new_X) print("\nSklearn模型预测结果:") for idx, price in enumerate(predicted_prices, 1): print(f"第{idx}组 利率={new_interest_rates[idx-1]} 失业率={new_unemployment_rates[idx-1]} 预测股指价格:{price:.2f}") # -------------------修改的预测部分结束------------------- # statsmodels模型训练 X_sm = sm.add_constant(X) model = sm.OLS(Y, X_sm).fit() predictions = model.predict(X_sm) print_model = model.summary() print("\nStatsmodels模型报告:\n", print_model) # (可选)Statsmodels模型多组预测 new_X_sm = sm.add_constant(new_X) sm_predicted_prices = model.predict(new_X_sm) print("\nStatsmodels模型预测结果:") for idx, price in enumerate(sm_predicted_prices, 1): print(f"第{idx}组 利率={new_interest_rates[idx-1]} 失业率={new_unemployment_rates[idx-1]} 预测股指价格:{price:.2f}")
说明
- 核心修改逻辑是将原单组预测的标量输入替换为二维数组输入,
predict方法支持传入多组数据批量输出预测结果 - 代码可直接在Jupyter Notebook中运行,输出会分别展示两种模型的5组预测结果
- 若不需要statsmodels的预测结果,删除对应可选部分即可
内容的提问来源于stack exchange,提问作者user2543
相关产品推荐
相关产品推荐

