我在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 pdimport numpy as npimport matplotlibimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dfrom sklearn import linear_modelfrom sklearn.model_selection import train_test_splitmatplotlib.style.use('ggplot') # Look Pretty# Reading in dataX = pd.read_csv('Datasets/College.csv', index_col=0)# Wrangling dataX.Private = X.Private.map({'Yes':1, 'No':0})# Splitting dataroomBoard = 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 modelmodel = linear_model.LinearRegression()model.fit(X_train, y_train)score = model.score(X_test, y_test)# Visualise resultsdrawLine(model, X_test, y_test, "Accept(Room&Board)", score)
我使用的数据可以在这里找到 这里
谢谢你的时间。
任何帮助或建议都将不胜感激。
回答:
在你的drawLine函数中,我将ax.scatter
改成了plt.scatter
。我还将roomBoard
和accStudent
从pandas.Series改成了numpy数组。最后,我改变了你更新”private”列的方式为
X.loc[:, "Private"] = X.Private.map({'Yes':1, 'No':0})
Pandas文档解释了我为什么要做这个改变。其他的小改动是美观上的。
我成功运行了以下代码:
import pandas as pdimport numpy as npimport matplotlibimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dfrom sklearn import linear_modelfrom sklearn.model_selection import train_test_splitmatplotlib.style.use('ggplot') # Look Pretty# Reading in dataX = pd.read_csv('College.csv', index_col=0)# Wrangling dataX.loc[:, "Private"] = X.Private.map({'Yes':1, 'No':0})# Splitting dataroomBoard = 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 modelmodel = linear_model.LinearRegression()model.fit(X_train, y_train)score = model.score(X_test, y_test)# Visualise resultsdef 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)