Machine learning linear regression model, advertising placement and revenue prediction, gradient descent method implemented in python
Dataset introduction
The data set contains a total of 200 records, and there are three feature values, namely TV, Rodio, and Newspaper. Respectively represent three different ad delivery paths. Forecast earnings.
Level 3 heading
the code
data import
Import the required python packages
# 导入数据处理库
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
Import Data
# 导入数据
path = '../Data/Advertising.csv'
data = pd.read_csv(path,usecols = [1,2,3,4])
view data
data.head(10)
feature scaling
Because the data difference is relatively large, perform feature scaling to reduce the difference between data
# 特征缩放 (x-平均值)/标准差
data = (data - data.mean())/data.std()
# 查看特征缩放后的数据
data.head(10)
In this way, the data is relatively normalized, and data overflow can also be prevented.
Draw a scatter diagram of advertising investment and revenue in three different places
# 绘制数据散点图
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')
data processing
# 变量初始化
# 最后一列为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
add offset column
#添加偏置列,值为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
Define the cost function
# 代价函数
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
gradient descent
# 梯度下降
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
Initialization parameters
alpha = 0.01 #学习速率
epoch = 500 #迭代步数
l = 5 #正则化参数
to train
#运行梯度下降算法 并得出最终拟合的theta值 代价函数J(theta)
final_theta, cost = GradientDescent(X_train, y_train, theta, l, alpha, epoch)
print(final_theta)
After 500 iterations, the fitted parameters
model evaluation
# 模型评估
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)
draw iteration curve
# 绘制迭代曲线
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()
View the fitting effect
# 图例展示预测值与真实值的变化趋势
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='--')