任务描述
现在想预测一个项目的 profit,影响 profit 的变量主要有以下三个:
- R & D profit
- Administration
- 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()