機械学習線形回帰モデル、広告掲載と収益予測、Python で実装された勾配降下法
データセットの紹介
データ セットには合計 200 レコードが含まれており、TV、Rodio、新聞という 3 つの特徴値があります。それぞれ 3 つの異なる広告配信パスを表します。収益を予測します。
レベル 3 の見出し
コード
データインポート
必要な 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)
これにより、データが比較的正規化され、データのオーバーフローも防ぐことができます。
3 つの異なる場所での広告投資と収益の散布図を描画します。
# 绘制数据散点图
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='--')