无法在 Python 中使用散点图正确绘制回归线
Posted
技术标签:
【中文标题】无法在 Python 中使用散点图正确绘制回归线【英文标题】:Unable to plot regression line correctly with scatter plot in Python 【发布时间】:2018-11-10 14:22:37 【问题描述】:我正在学习有关 EdX 的课程,该课程是在数据科学中使用 Python 进行编程。当使用给定函数绘制我的线性回归模型的结果时,图表似乎非常偏离,所有散点都聚集在底部,而回归线则居高不下。
我不确定是定义的函数drawLine
不正确还是我的建模过程有问题。
这里是定义的函数
def drawLine(model, X_test, y_test, title, R2):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(X_test, y_test, c='g', marker='o')
ax.plot(X_test, model.predict(X_test), color='orange', linewidth=1, alpha=0.7)
title += " R2: " + str(R2)
ax.set_title(title)
print(title)
print("Intercept(s): ", model.intercept_)
plt.show()
这是我写的代码
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import linear_model
from sklearn.model_selection import train_test_split
matplotlib.style.use('ggplot') # Look Pretty
# Reading in data
X = pd.read_csv('Datasets/College.csv', index_col=0)
# Wrangling data
X.Private = X.Private.map('Yes':1, 'No':0)
# Splitting data
roomBoard = X[['Room.Board']]
accStudent = X[['Accept']]
X_train, X_test, y_train, y_test = train_test_split(roomBoard, accStudent, test_size=0.3, random_state=7)
# Training model
model = linear_model.LinearRegression()
model.fit(X_train, y_train)
score = model.score(X_test, y_test)
# Visualise results
drawLine(model, X_test, y_test, "Accept(Room&Board)", score)
我使用的数据可以在here找到
感谢您的宝贵时间。 感谢您提供任何帮助或建议。
【问题讨论】:
【参考方案1】:在你的 drawLine 函数中,我将 ax.scatter
更改为 plt.scatter
。我还将roomBoard
和accStudent
更改为numpy 数组而不是pandas.Series。最后,我将您更新“私人”列的方式更改为
X.loc[:, "Private"] = X.Private.map('Yes':1, 'No':0)
Pandas docs 解释了我进行此更改的原因。其他小的变化是装饰性的。
我得到了以下工作:
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import linear_model
from sklearn.model_selection import train_test_split
matplotlib.style.use('ggplot') # Look Pretty
# Reading in data
X = pd.read_csv('College.csv', index_col=0)
# Wrangling data
X.loc[:, "Private"] = X.Private.map('Yes':1, 'No':0)
# Splitting data
roomBoard = X.loc[:, 'Room.Board'].values.reshape((len(X),1))
accStudent = X.loc[:, 'Accept'].values.reshape((len(X),1))
X_train, X_test, y_train, y_test = train_test_split(roomBoard, accStudent, test_size=0.3, random_state=7)
# Training model
model = linear_model.LinearRegression()
model.fit(X_train, y_train)
score = model.score(X_test, y_test)
# Visualise results
def drawLine(model, X_test, y_test, title, R2):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.scatter(X_test, y_test, c='g', marker='o')
y_pred = model.predict(X_test)
plt.plot(X_test, y_pred, color='orange', linewidth=1, alpha=0.7)
title += " R2: " + str(R2)
ax.set_title(title)
print(title)
print("Intercept(s): ", model.intercept_)
plt.xticks(())
plt.yticks(())
plt.show()
drawLine(model, X_test, y_test, "Accept(Room&Board)", score)
【讨论】:
感谢您的帮助!我尝试一次进行一项更改,并意识到roomBoard
和accStudent
的类型似乎是创建正确图形最重要的。但是,我很确定在我的原始代码 roomBoard = X[['Room.Board']]
返回一个 pandas.DataFrame。你能告诉我为什么 numpy 2DArray 可以工作,而 DataFrame 不能吗?
Scikit-Learn Docs 说输入必须是一个numpy数组以上是关于无法在 Python 中使用散点图正确绘制回归线的主要内容,如果未能解决你的问题,请参考以下文章