Python中的回归模型没有意义

2024-10-01 00:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python建立一个回归模型,在能源评级和房价之间,看看能源评级是否会影响房价

Dataset看起来像:

下面是使用线性回归实现的模型

import statsmodels.formula.api as smf

# Initialise and fit linear regression model using `statsmodels`
model = smf.ols('price ~ energyrating', data=df)

model = model.fit()
model.params

#price=2.004943e+06 + (-.913381e+05)*energyrating

Intercept       2.004943e+06
energyrating   -3.913381e+05
dtype: float64
# Predict values
pred = model.predict()

# Plot regression against actual data
plt.figure(figsize=(12, 6))
plt.plot(df['energyrating'], df['price'], 'o')           # scatter plot showing actual data
plt.plot(df['energyrating'], pred, 'r', linewidth=2)   # regression line
plt.xlabel('Energy ratings')
plt.ylabel('Price')
plt.title('Energy ratings Vs. Price')

plt.show()

enter image description here

这个模型没有给出任何有意义的知识,对于正确的图,我已经对energyrating进行了平方,因为与price相比,这些值很小,但仍然不正确。我是否遗漏了重要的一点

我如何创建一个模型,在energy ratingprice之间提供有意义的关系

欢迎其他车型的建议提前感谢


Tags: 模型dfdatamodelplotpltpricefit
1条回答
网友
1楼 · 发布于 2024-10-01 00:33:09

您错过了这段代码,因此应该将其放在“model=smf.ols('price~energyrating',data=df)”和“model=model.fit()”之间。 也许

#Divide test data and training data into 7 and 3
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

model = model.fit(x_train, y_train)

相关问题 更多 >