我将如何用最适合的线绘制我的线性回归模型?
How would I plot my linear regression model with a line of best fit?
我刚刚训练了一个线性回归模型,得到了基于“number_rooms”和“价格”的房价截距和系数。但是我有点不确定如何使用具有最佳拟合线的散点图来绘制我的回归模型。
如能提供有关如何执行此操作的任何帮助,我们将不胜感激 - 谢谢!
这是我的代码:
rgr = linear_model.LinearRegression()
rgr.fit(X=sample['number_rooms'].values.reshape(-1,1), y=sample['price'].values)
print(rgr.intercept_, rgr.coef_[0])
predictions = rgr.predict(X=sample['number_rooms'].values.reshape(-1,1))
metrics.mean_squared_error(y_pred=predictions, y_true=sample['price'], squared=False)
很简单,试试这个-
import matplotlib.pyplot as plt
# to plot predictions
plt.scatter(sample['number_rooms'].values, predictions.array.reshape(-1, 1), c='g', label='predicted prices')
# to plot the best fit line
min_rooms = 0 # or 1
max_rooms = 10 #say
rooms_range = range(min_rooms, max_rooms+1)
plt.plot(rooms_range, rgr.predict(X=rooms_range).array.reshape(-1, 1), c='r', label='best fit')
plt.legend()
您可以尝试的另一件事是:
鉴于现在您知道斜率和截距,找到一个合理的范围 - 一个最能描述房间数量的范围,然后
y = m*number_of_beds + 截距
然后在散点图上绘制 y 和 x
让我们研究一下它的数学原理
给定 x
的 y
线性回归拟合一条直线,可最大限度地减少误差。此行使用:y = w*x +b
w = rgr.coef_[0]
bias = rgr.intercept_
number_rooms = sample['number_rooms'].values
plt.plot([min(number_rooms), max(number_rooms)],
[w*min(number_rooms)+bias, w*max(number_rooms)+bias])
我刚刚训练了一个线性回归模型,得到了基于“number_rooms”和“价格”的房价截距和系数。但是我有点不确定如何使用具有最佳拟合线的散点图来绘制我的回归模型。
如能提供有关如何执行此操作的任何帮助,我们将不胜感激 - 谢谢!
这是我的代码:
rgr = linear_model.LinearRegression()
rgr.fit(X=sample['number_rooms'].values.reshape(-1,1), y=sample['price'].values)
print(rgr.intercept_, rgr.coef_[0])
predictions = rgr.predict(X=sample['number_rooms'].values.reshape(-1,1))
metrics.mean_squared_error(y_pred=predictions, y_true=sample['price'], squared=False)
很简单,试试这个-
import matplotlib.pyplot as plt
# to plot predictions
plt.scatter(sample['number_rooms'].values, predictions.array.reshape(-1, 1), c='g', label='predicted prices')
# to plot the best fit line
min_rooms = 0 # or 1
max_rooms = 10 #say
rooms_range = range(min_rooms, max_rooms+1)
plt.plot(rooms_range, rgr.predict(X=rooms_range).array.reshape(-1, 1), c='r', label='best fit')
plt.legend()
您可以尝试的另一件事是:
鉴于现在您知道斜率和截距,找到一个合理的范围 - 一个最能描述房间数量的范围,然后
y = m*number_of_beds + 截距
然后在散点图上绘制 y 和 x
让我们研究一下它的数学原理
给定 x
的 y
线性回归拟合一条直线,可最大限度地减少误差。此行使用:y = w*x +b
w = rgr.coef_[0]
bias = rgr.intercept_
number_rooms = sample['number_rooms'].values
plt.plot([min(number_rooms), max(number_rooms)],
[w*min(number_rooms)+bias, w*max(number_rooms)+bias])