Python 多元线性回归,留一法测试回归效果

任务描述

现在想预测一个项目的 profit,影响 profit 的变量主要有以下三个:

  1. R & D profit
  2. Administration
  3. Marketing Spend

数据信息

这些数据保存在excel表格里格式如下(部分数据):

 数据链接🔗:Multiple-Linear-Regression dataset 

借助散点图来看一下每种因素与 profit 的相关趋势

 从散点图中可以看出,R&D spend 以及 marketing spend 与 profit 的相关程度要大一些

线性回归预测,留一法验证

首先利用单变量线性回归,分别对三种因素的预测能力进行评估,结果如下图第一行所示。从单变量的预测结果中可以看出,Administration这个变量的 R2 < 0,表明其预测效果比均值预测还要差,因此在后续的多变量预测中不建议将其作为输入;第二行的左图是用三个变量的预测结果,右图是用除 Administration 这个变量之外的预测结果,可以看出的确是不添加 Administration 的结果要好一些。【下图中的x轴表示预测结果,y轴表示实际结果】

Python 代码如下

import numpy as np
import xlrd
from sklearn import preprocessing
from sklearn.model_selection import LeaveOneOut
from sklearn.linear_model import LinearRegression
from sklearn import metrics
import matplotlib.pyplot as plt


def excel_to_matrix(path, data_norm=True):
    table = xlrd.open_workbook(path).sheets()[0]
    row = table.nrows
    col = table.ncols
    datamatrix = np.zeros((row - 1, col))
    for x in range(col):
        cols = np.array(table.col_values(x))
        datamatrix[:, x] = cols[1:]  # 不读标题行
    if data_norm:
        min_max_scaler = preprocessing.MinMaxScaler()
        datamatrix = min_max_scaler.fit_transform(datamatrix)
    return datamatrix


def linear_regression_loo(X, Y, Xlabel, Ylabel):
    Y_pred = []
    Y_true = []
    loo = LeaveOneOut()
    loo.get_n_splits(X)
    for train_index, test_index in loo.split(X):
        X_train, X_test = X[train_index], X[test_index]
        Y_train, Y_test = Y[train_index], Y[test_index]
        fitor = LinearRegression()
        model = fitor.fit(X_train, Y_train)
        Y_pred.append(model.predict(X_test))
        Y_true.append(Y_test)
    print('R2 = ', metrics.r2_score(Y_true, Y_pred))
    print('MSE = ', metrics.mean_squared_error(Y_true, Y_pred))
    plt.figure()
    plt.scatter(Y_pred, Y_true)
    plt.plot([0, 1], [0, 1])
    plt.xlabel(Xlabel)
    plt.ylabel(Ylabel)


if __name__ == '__main__':
    path = r'.\example_data.xlsx'
    data = excel_to_matrix(path)
    Y = data[:, 3]
    # 单变量线性回归
    X1 = data[:, 0].reshape(-1, 1)
    linear_regression_loo(X1, Y, 'R&D Spend', 'Profit')

    X2 = data[:, 1].reshape(-1, 1)
    linear_regression_loo(X2, Y, 'Administration', 'Profit')

    X3 = data[:, 2].reshape(-1, 1)
    linear_regression_loo(X3, Y, 'Marketing Spend', 'Profit')

    # 多变量线性回归
    X = data[:, [0, 2]]
    linear_regression_loo(X, Y, 'R&D + Marketing Spend', 'Profit')

    X = data[:, 0:3]
    linear_regression_loo(X, Y, 'All', 'Profit')

    plt.show()

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值