无法使用Python中的散点图正确绘制回归线

时间:2018-05-31 14:20:05

标签: python matplotlib machine-learning scikit-learn linear-regression

我正在修读关于数据科学中Python编程的EdX课程。当使用给定函数绘制我的线性回归模型的结果时,图形似乎非常偏离,所有散点都聚集在底部,回归线向上顶部。

我不确定定义的函数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 个答案:

答案 0 :(得分:1)

在drawLine函数中,我将ax.scatter更改为plt.scatter。我还将roomBoardaccStudent更改为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)