机器学习线性回归实践,广告投放收益预测,手写梯度下降

数据集介绍

数据集共包含200条记录,特征值共有三个,分别是TV,Rodio,Newspaper。分别表示三个不同的广告投放路径。预测收益。
三级标题

代码

数据导入

导入需要的python包

# 导入数据处理库
import numpy as np
import pandas as pd
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import datasets

导入数据

# 导入数据
path = '../Data/Advertising.csv'
data = pd.read_csv(path,usecols = [1,2,3,4])

查看数据

data.head(10)

特征缩放

因为数据差异比较大,进行一下特征缩放,减小数据间的差异性

# 特征缩放 (x-平均值)/标准差
data = (data - data.mean())/data.std()
# 查看特征缩放后的数据
data.head(10)

这样数据就比较归一了,也能防止出现数据溢出

绘制三个不同地方广告投入与收益的散点图

# 绘制数据散点图
data.plot(kind = 'scatter', x = 'TV', y = 'Sales', color = 'm')
data.plot(kind = 'scatter', x = 'Radio', y = 'Sales', color = 'k')
data.plot(kind = 'scatter', x = 'Newspaper', y = 'Sales',color = 'c')



数据处理

# 变量初始化
# 最后一列为y,其余为x
cols = data.shape[1] #列数 shape[0]行数 [1]列数
X = data.iloc[:,0:cols-1]       #取前cols-1列,即输入向量
y = data.iloc[:,cols-1:cols]    #取最后一列,即目标变量
X.head(10)

# 划分训练集和测试集
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)
# 将数据转换成numpy矩阵
X_train = np.matrix(X_train.values)
y_train = np.matrix(y_train.values)
X_test = np.matrix(X_test.values)
y_test = np.matrix(y_test.values)
# 初始化theta矩阵
theta = np.matrix([0,0,0,0])
X_train.shape,X_test.shape,y_train.shape,y_test.shape

添加偏置列

#添加偏置列,值为1,axis = 1 添加列 
X_train = np.insert(X_train, 0, 1, axis=1) 
X_test = np.insert(X_test,0,1,axis=1)
X_train.shape,X_test.shape,y_train.shape,y_test.shape

定义代价函数

# 代价函数
def CostFunction(X,y,theta):
    inner = np.power(X*theta.T-y, 2)
    return np.sum(inner)/(2*len(X))
# 正则化代价函数
def regularizedcost(X,y,theta,l):
    reg = (l/(2*len(X)))*(np.power(theta, 2).sum())    
    return CostFunction(X,y,theta) + reg

梯度下降

# 梯度下降
def GradientDescent(X,y,theta,l,alpha,epoch):
    temp = np.matrix(np.zeros(np.shape(theta)))   # 定义临时矩阵存储tehta
    parameters = int(theta.flatten().shape[1])    # 参数 θ的数量
    cost = np.zeros(epoch)  # 初始化一个ndarray,包含每次epoch的cost
    m = X.shape[0]  # 样本数量m
    for i in range(epoch):
        # 利用向量化一步求解
        temp = theta - (alpha / m) * (X * theta.T - y).T * X - (alpha*l/m)*theta     # 添加了正则项
        theta = temp
        cost[i] = regularizedcost(X, y, theta, l)      # 记录每次迭代后的代价函数值

    return theta,cost

初始化参数

alpha = 0.01  #学习速率
epoch = 500  #迭代步数
l = 5      #正则化参数

进行训练

#运行梯度下降算法 并得出最终拟合的theta值 代价函数J(theta)
final_theta, cost = GradientDescent(X_train, y_train, theta, l, alpha, epoch)
print(final_theta)

经过500次迭代,拟合出来的参数
在这里插入图片描述

模型评估

# 模型评估
y_hat_train = X_train * final_theta.T
y_hat_test = X_test * final_theta.T
mse = np.sum(np.power(y_hat_test-y_test,2))/(len(X_test))
rmse = np.sqrt(mse)
R2_train = 1 - np.sum(np.power(y_hat_train - y_train,2))/np.sum(np.power(np.mean(y_train) - y_train,2))
R2_test = 1 - np.sum(np.power(y_hat_test - y_test,2))/np.sum(np.power(np.mean(y_test) - y_test,2))
print('MSE = ', mse)
print('RMSE = ', rmse)
print('R2_train = ', R2_train)
print('R2_test = ', R2_test)

绘制迭代曲线

# 绘制迭代曲线
fig, ax = plt.subplots(figsize=(8,4))
ax.plot(np.arange(epoch), cost, 'r')  # np.arange()返回等差数组
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title('Error vs. Training Epoch')
plt.show()

查看拟合效果

# 图例展示预测值与真实值的变化趋势
plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标签
plt.rcParams['axes.unicode_minus']=False 
plt.figure(facecolor='w')
t = np.arange(len(X_test))  #创建等差数组
plt.plot(t, y_test, 'r-', linewidth=2, label=u'真实数据')
plt.plot(t, y_hat_test, 'b-', linewidth=2, label=u'预测数据')
plt.legend(loc='upper right')
plt.title(u'线性回归预测销量', fontsize=18)
plt.grid(b=True, linestyle='--')

猜你喜欢

转载自blog.csdn.net/weixin_44209013/article/details/106448110