【问题标题】:How can I add a scatterplot and the line of best fit to my Linear Regression program using Matplotlib如何使用 Matplotlib 向我的线性回归程序添加散点图和最佳拟合线
【发布时间】:2021-11-12 13:12:10
【问题描述】:
from matplotlib import pyplot as plt


data = pd.read_csv("student-mat.csv", sep=";")

data = data[["G1", "G2", "G3", "studytime", "failures", "absences"]]

predict = "G3"

X = np.array(data.drop([predict], 1))
y = np.array(data[predict])

x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, test_size = 0.1)

linear = linear_model.LinearRegression()

linear.fit(x_train, y_train)
accuracy = linear.score(x_test, y_test)
print(accuracy*100)

print('Coefficient: \n', linear.coef_)
print('Intercept: \n', linear.intercept_)

predictions = linear.predict(x_test)

for x in range(len(predictions)):
    print(predictions[x], x_test[x], y_test[x])

【问题讨论】:

标签: python matplotlib machine-learning linear-regression


【解决方案1】:

示例(类似于上面的评论):

import seaborn as sns
sns.regplot(x=y_test, y=predictions, ci=None, color="r")

【讨论】:

    【解决方案2】:

    您可以使用以下代码使用matplotlib绘制折线图:

    a = linear.coef_
    b = linear.intercept_
    plt.plot(x_train, a*x_train + b)
    

    或另一种可能的解决方案是:

    m = linear.coef_
    b = linear.intercept_
    regression_line = [(m*x)+b for x in x_train]
    import matplotlib.pyplot as plt
    from matplotlib import style
    style.use('ggplot')
    plt.scatter(x_train,y_train,color='#003F72')
    plt.plot(x_train, regression_line)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多